emailverifier.dev
Posts

Email Verification Code Security: Expiry, Attempts, and Replay

| 7 min read | Usama Ejaz
An email enters a server-side verification challenge where a spent attempt and superseded old code lead to one active single-use code.

An email verification code is secure enough for address confirmation when it is generated with a cryptographic random number generator, expires quickly, has a strict guess limit, becomes invalid after one use, and is replaced rather than duplicated on resend.

The server needs to enforce every one of those properties. A six-digit value in an email is only the user-facing part of a challenge record.

I treat the code as proof that someone could read a message sent to that address at that moment. It is not proof of legal identity, permanent mailbox ownership, or a high-assurance authentication factor. NIST makes this boundary explicit: confirmation codes used to validate email addresses are not authentication processes.

A six-digit code has a measurable guessing budget

Six decimal digits give you 1,000,000 possible values, including codes with leading zeroes. If the generator is uniform and the server permits five distinct guesses, the maximum chance of guessing one fresh challenge is:

5 guesses / 1,000,000 values = 0.000005 = 0.0005%

That figure is small, but it is not the whole threat model. The probability is per challenge. An attacker who can request unlimited new codes, retry across many endpoints, or keep old and new codes valid at once gets more opportunities. Expiry reduces time. Attempt limits reduce guesses. Issuance limits reduce the number of fresh challenges.

Eight digits expand the space to 100,000,000 values. That can be useful for higher-risk actions, but length does not replace server-side controls. A long code with unlimited attempts is still an unlimited online guessing problem.

Use a cryptographic generator. In Node.js, crypto.randomInt() returns an integer within a specified range and avoids modulo bias:

import { randomInt } from 'node:crypto';

export function generateEmailCode() {
  return randomInt(0, 1_000_000).toString().padStart(6, '0');
}

Do not build codes from timestamps, user IDs, Math.random(), or a hash of the email address. Those inputs can make the output predictable.

The challenge is the security boundary

A verification code should belong to one server-side challenge, not sit as a reusable field on the user record. I would store these fields:

challenge_id
normalized_email
purpose                 # signup, change_email, or another exact action
code_mac
expires_at
attempts_remaining
consumed_at
superseded_at
created_at

Binding the purpose matters. A code issued to confirm a newsletter address should not authorize an account email change. Binding the normalized address prevents a code from being moved to a different target. A random challenge ID lets the server identify the record without exposing the code itself.

Store a keyed digest such as HMAC-SHA-256 instead of the plaintext code. Include the challenge ID in the input and keep the HMAC key in a secret manager, separate from the database:

import { createHmac } from 'node:crypto';

function codeMac(challengeId, code, pepper) {
  return createHmac('sha256', pepper)
    .update(`${challengeId}:${code}`)
    .digest();
}

A plain hash is not much protection for a six-digit secret. A database attacker can try the entire million-value space quickly. A keyed digest prevents that database-only attack while the secret key remains unavailable. It does not help if the attacker also compromises the application secret.

The code must stay out of logs, analytics events, error reports, support tools, and URLs. The email delivery provider will necessarily process the message, so keep the message content limited to the code, purpose, expiry, and a warning not to share it.

Redeem it as one atomic state change

The redemption endpoint should lock the challenge row, check its state, compare the submitted code in constant time, and update the row in the same transaction. This is the reference flow:

BEGIN;

SELECT *
FROM email_verification_challenges
WHERE challenge_id = $1
FOR UPDATE;

-- Reject when expired, consumed, superseded, or out of attempts.
-- Compare HMAC(challenge_id || supplied_code) in constant time.
-- On mismatch: decrement attempts_remaining.
-- On match: set consumed_at and record the confirmed address/purpose.

COMMIT;

The row lock closes a common replay race. Without it, two requests can both read an unused challenge before either writes consumed_at. A conditional update can provide the same guarantee if your data store does not support row locks, but the condition must include the unused state.

I ran a small Node fixture for this article against eight behaviors: six-digit formatting, wrong-code rejection, a spent attempt after a wrong code, successful redemption, replay rejection, resend invalidation, a preserved attempt budget, and successful use of the replacement code. All eight checks passed. The fixture does not prove a production system secure, but it makes the intended state transitions reproducible.

Resend replaces the challenge

When a user requests another message, generate a new code and supersede the old challenge. Do not leave several valid codes in circulation. OWASP recommends generating a new OTP and overwriting the old record on resend.

There is a second trap: resend must not restore the full guess budget. If the first challenge has four attempts left, its replacement should inherit four attempts, or the attempt counter should live on a separate account-and-purpose record. NIST applies the same principle to short authentication secrets: generating a new secret must not reset the failed-attempt count.

Throttle both issuance and verification. Useful dimensions include the normalized address, account or signup session, IP or network, and device signal. The exact thresholds depend on your abuse model, but they should cover every endpoint that can issue or redeem the same purpose.

The request endpoint should return the same response whether the account exists or not. Something like “If that address can receive a code, we sent one” avoids turning the feature into an email enumeration oracle. Keep response timing reasonably consistent too.

Expiry is a product decision with a security cost

OWASP calls for a short time-to-live, single use, and strict attempt limits. NIST uses a ten-minute maximum for the out-of-band authentication secrets covered by its guidance. Email address confirmation is a different process, so ten minutes is not a universal mandate here. It is a useful upper reference point.

For a signup confirmation, I would start with ten minutes and measure legitimate completion failures before extending it. Slow corporate filtering, greylisting, and overloaded inboxes can delay delivery. If users regularly need more time, investigate delivery and provide a controlled resend path rather than silently accepting codes for hours.

Show the expiry in the email and interface. Once the deadline passes, return the same unavailable state used for consumed or superseded challenges. Detailed internal reason codes can remain in server logs without telling an attacker which part of the challenge state they discovered.

Verification quality and inbox confirmation solve different problems

Before sending a code, a technical email verification check can catch malformed addresses, non-mail domains, known disposable providers, and some rejected mailboxes. That can prevent wasted messages and let a user correct a typo while still on the form.

The emailverifier.dev API returns a technical status, a recommended action, and the signals behind it. An inconclusive mailbox check stays unknown. I would route that result to confirmation rather than treating it as a definite failure. The product documentation is clear that a domain result does not confirm a mailbox or message delivery.

Confirmation starts where technical verification stops. Entering the code shows that someone received this message and completed this challenge. It still does not guarantee future delivery, identify the human, or prove the address will remain under the same control. For the broader distinction, see email validation versus verification.

Test the failures, not just the happy path

Four integration tests catch most lifecycle mistakes:

  1. Concurrent replay: submit the correct code twice at the same time and assert that exactly one request succeeds.
  2. Resend collision: issue a replacement and assert that the previous code fails immediately, even if it has not expired.
  3. Budget preservation: spend attempts, resend, and assert that the remaining budget does not increase.
  4. Boundary expiry: test just before and exactly at expires_at using a server-controlled clock.

Add logging assertions too. The code itself should never appear in application logs, traces, metrics labels, or analytics payloads.

The strongest fair objection is that an email code cannot make a compromised inbox safe. That is correct. This pattern limits guessing, replay, and implementation mistakes in your application. It does not repair the mailbox. Use phishing-resistant authentication for high-risk account access, and reserve the email code for the narrower claim it can support: this challenge reached this address and was completed once.

Sources

Continue reading