Keep signup verification and second factor login in separate challenge records, and accept OTP input only through an atomic consume operation. Delivery reliability decides whether the user can reach that operation; it must never decide whether an expired or already consumed challenge becomes valid again.
TL;DR: For a Node.js application, make the server own the challenge purpose, expiry, attempt budget, and consumption decision. Preserve the OTP as a string. A developer tools signup link should activate an email verification challenge; it should not silently become evidence that a later 2FA login succeeded.
The concrete workflow here is a developer signing up, waiting for a verification email, and then entering a second factor during login. Treat the following as a proposed architecture decision record. The example limits are configuration choices, not measurements or requirements from an authentication standard.
The decision and its invariants
Give every challenge one purpose and one pending operation. For signup, that operation is confirming the submitted email address. For login, it is completing the specific pending authentication attempt. Bind the challenge to server state that identifies that operation; an account identifier submitted with an OTP is insufficient authority to choose it.
A useful invariant is: one accepted challenge authorizes one transition. Consuming a signup link changes the signup verification state. Consuming a login OTP completes its bound authentication attempt. Neither transition should confer the other's authority, even when both messages reach the same inbox. This keeps email delivery troubleshooting from turning into a reason to weaken the login boundary.
Keep the input contract narrow. For the illustrative six digit login challenge below, accept exactly six ASCII digits, including leading zeros. Reject spaces, signs, decimal notation, and other characters. Avoid converting the value to an integer or silently repairing pasted input on the server. The interface can explain the expected shape before submission.
Syntax isn't authorization.
The server must still check purpose, expiry, attempts, and prior consumption. An input that looks correct has passed only the cheapest check.
What should happen when the email arrives late?
Keep delivery state separate from challenge state. A message queued for delivery is a delivery event; the proposed application should require a successful challenge transition before marking the address verified. Likewise, a delivery notification should never complete a pending login.
For this design, choose a signup link lifetime of 10 minutes and a login OTP lifetime of 5 minutes as initial policy values. Validate those choices against actual delivery latency and the application's security requirements before deployment. Time starts at challenge issuance. Receiving a delayed email does not restart it. Explain expiration in the interface and offer a controlled way to request another challenge. Replacement needs an explicit rule. This record chooses invalidation: issuing a new challenge invalidates the previous challenge for that operation, while retaining a separate account or operation level attempt budget. Otherwise, repeatedly requesting replacements would replenish the guessing budget. A delayed first email can then contain an unusable link, so the email and waiting screen should tell the user to use the latest request. That is a deliberate usability cost.
Separate sender authentication from recipient verification, too. RFC 7208 defines SPF checks for whether a sending host is authorized to use a domain in the MAIL FROM or HELO identity. That addresses a different question from whether the signup recipient completed the application's challenge. Use SPF as evidence about sender authorization, not as evidence that an email reached the inbox or that a user owns the address.
Keep the boundaries visible.
Operationally, retain distinct states for issuance, delivery observations, expiration, replacement, and successful consumption. Investigating a missing signup email should not require logging its verification link or a user's OTP.
Options and the boundary each one buys
The decision turns on where the application spends its attempt budget and where it records success. These implementation choices carry different concurrency and delivery responsibilities.
| Choice | Benefit for this workflow | Failure boundary or trade-off |
|---|---|---|
| Client validates OTP shape | Immediate feedback for malformed input | Server still owns every authorization check |
| Server reads, compares, then writes separately | Straightforward sequential control flow | The design needs protection against overlapping requests before it can promise single consumption |
| Server checks and consumes in one transaction | One place to enforce expiry, attempts, and single use | Requires shared state and a clear transaction boundary |
| Replacement invalidates the old challenge | One current challenge per pending operation | Delayed older messages become invalid; the interface must explain this |
Choose the transactional path and replacement policy here. Keep delivery retries separate: retrying transport of an existing message must not create a fresh authentication challenge or reset its attempt counter. When the application deliberately issues a replacement, commit the new challenge and the intent to send its message together in durable state. A delivery worker can then process that recorded intent.
The maintenance cost is real. The team now owns a challenge state machine, delivery bookkeeping, and a reconciliation path for work interrupted between issuance and sending. Accept that cost because the alternative makes an authentication decision depend on the timing of independent request handlers.
How should an application handle OTP input during the 2FA login process?
Although the application uses Node.js, the following Python model makes the server contract explicit without tying it to a framework. It deliberately accepts a comparison function rather than prescribing secret storage. That function must verify the submitted value against the server's stored verifier. The lock illustrates a transaction boundary only within this model; production workers need the equivalent protection in shared durable storage.
from dataclasses import dataclass
from threading import Lock
from typing import Callable
@dataclass
class Challenge:
operation_id: str
purpose: str
expires_at: float
attempts_left: int = 5
consumed: bool = False
def consume_login_otp(
challenge: Challenge,
operation_id: str,
candidate: object,
now: float,
lock: Lock,
matches: Callable[[str], bool],
) -> bool:
# operation_id comes from the server's pending login state.
if not isinstance(candidate, str):
return False
if len(candidate) != 6:
return False
if any(char not in '0123456789' for char in candidate):
return False
with lock:
if challenge.operation_id != operation_id:
return False
if challenge.purpose != 'login_2fa':
return False
if challenge.consumed or now >= challenge.expires_at:
return False
if challenge.attempts_left <= 0:
return False
challenge.attempts_left -= 1
if not matches(candidate):
return False
challenge.consumed = True
return True
The limit of 5 attempts is another illustrative policy choice. The model spends one on every well formed candidate that reaches the comparison, including the successful candidate. Malformed submissions return before that budget is touched, so the surrounding request handler also needs request throttling.
An input format check alone is no abuse control.
In the deployed application, include completion of the pending login in the same durable decision as consumption, or persist a recoverable completion result keyed to that operation. Otherwise, a connection lost after consumption leaves the browser unsure whether to retry, while the server has already spent the challenge. A retry should retrieve the recorded outcome for that bound operation rather than consume the OTP again.
Do not copy the in-memory lock into a deployment with multiple workers and call the job finished. The property to preserve is a single serialized decision over the shared challenge state. Replacement, failed attempts, and successful consumption must all respect that boundary.
Rejected option and the evidence needed to revisit it
Reject accepting several replacement challenges simultaneously for this signup workflow. It would make a delayed email easier to use, but it would also leave several independently issued proofs eligible for consumption and complicate the attempt budget. Overlapping validity can be a defensible choice for a workflow that explicitly needs it, provided all versions share an operation level budget and accepting one invalidates the others atomically. Document that requirement before changing the policy.
Before release, exercise two simultaneous correct submissions, a correct value at the expiration boundary, a replacement request followed by the older link, a malformed numeric payload, and a response lost after successful consumption. For the concurrency case, require exactly one state transition. For the lost response case, require a recoverable result. These are acceptance criteria, not claimed test results.
Observe delivery delay separately from verification completion and OTP rejection reasons. Restrict diagnostic access and define retention for identifiers; keep raw proofs out of logs. Review those observations before adjusting lifetimes, because extending a login challenge to compensate for a slow signup email changes the wrong control.
Ship the decision as a state transition contract. The user needs a usable verification message, and the server needs an unambiguous record of what that message or OTP was allowed to authorize. Both belong in the release criteria.
References
- RFC 7208, Sender Policy Framework (SPF), for the scope of sender authorization checks: https://datatracker.ietf.org/doc/html/rfc7208
Top comments (0)