DEV Community

SyltharWave2946
SyltharWave2946

Posted on

Node.js SMS OTP Login Backend: Stateful Beats Stateless for Code Retry

Choose an atomic challenge record over a stateless token when SMS OTP login protects access to order receipts in a customer support backend. TL;DR: the extra storage adapter buys one place to enforce code consumption, failed attempts, and retry cooldown; a signed token alone cannot coordinate those decisions across concurrent requests. For a Node.js integration, make that persistence contract explicit before wiring up message delivery.

The receipt itself should follow the payment settlement event. Logging in to retrieve it is a separate operation. That distinction also matters for airline disruption alerts: an authentication retry must not become a command to repeat an operational alert, and an alert delivery receipt must not become evidence that someone authenticated. This decision record concentrates on recovery semantics and the integration effort required to preserve those boundaries.

How should a backend verify an SMS OTP code after a login retry?

The proposed invariant is one successful consumption per challenge, with failed guesses counted across every worker that can verify it.

A successful verification must create only the intended authentication result. It must not mark an order paid, change a passenger's itinerary, or trigger a second order receipt. Those are separate business transitions with their own authorization and deduplication rules.

State comes first.

NIST SP 800-63B requires a verifier to accept a given out-of-band authentication secret only once during its validity period, complete authentication within ten minutes, and rate-limit failed attempts for short secrets. It also says that generating a new authentication secret must not reset the failed authentication count. Its treatment of the public switched telephone network is restricted, with risk considerations including SIM changes and number porting. These are meaningful limits on SMS as an authentication channel, not delivery tuning suggestions.

The example policy uses a six-digit code valid for 300 seconds, a cooldown of 30 seconds between repeated sends, and a five-failure challenge limit. These are illustrative policy choices, not measured optimal settings or a complete compliance profile. The account-level attempt budget survives challenge replacement; the challenge limit is an additional restriction. Apply issuance limits to the account and destination as well as a source-level abuse budget, because rotating challenges or network addresses must not manufacture unlimited guesses.

The difficult boundary is the transition between a durable decision and an external send. A database commit cannot, by itself, prove that a handset received an SMS. Treat an ambiguous send result as an unresolved delivery attempt, preserve its identity, and reconcile it through the transport adapter's documented behavior. Starting a fresh challenge after every timeout makes the integration appear simpler while moving the ambiguity into customer support.

The decision: persist the consumption boundary

The comparison is between two application designs, not messaging products. Integration effort includes the code and operational work required after a request times out, a worker restarts, or two verification requests arrive together.

Concern Atomic challenge record Stateless signed token alone
Initial integration Requires a transaction adapter and expiry policy Avoids a challenge lookup on the basic verification path
Single consumption Conditional state change inside the transaction Needs shared consumption state to reject replay
Failed guesses Shared account budget and challenge counter Needs a separate shared limiter
Retry cooldown Stored with the active challenge Needs shared issuance state across workers
Recovery after send ambiguity Durable dispatch identity can be reconciled Needs a separate dispatch record for reconciliation
Retention Must expire secret material and bound retained metadata Still needs retention rules for any added limiter or replay store

Choose the record when those shared controls are already requirements. The integration cost is concentrated in a small storage contract instead of spread across a token validator, replay cache, limiter, and delivery reconciliation path that must agree on the same identity. A signed token can carry context, but signing does not consume it.

There is a trade-off.

Verification now depends on the availability and consistency of the state store. For this design, a store outage means no successful verification; accepting a code without consuming its record would abandon the invariant precisely when recovery is least predictable. Keep receipt delivery and operational alert delivery independent so that an authentication dependency does not acquire authority over those workflows.

Put the critical path inside one transaction

The following Python sketch defines the application contract for a backend adapter; it is not a Node.js SDK example. All repository and transaction methods are deliberately abstract. Their implementation must lock the relevant account and challenge state together, commit on normal exit, roll back on exceptions, and enforce uniqueness for the stable dispatch identifier. This is where an adapter review earns its time.

The send operation reserves a dispatch; a separate worker performs transport I/O after commit. The challenge object contains its immutable ID, account ID, expiry, consumed flag, failed-attempt count, next-send deadline, and keyed code digest. The account object owns the failure budget that survives new challenges.

import hashlib
import hmac
import secrets

VALID_FOR = 300
COOLDOWN = 30
MAX_FAILURES = 5

def digest(key, challenge_id, code):
    value = f"{challenge_id}:{code}".encode("utf-8")
    return hmac.new(key, value, hashlib.sha256).digest()

def reserve_send(repo, account_id, challenge_id, key, now):
    with repo.transaction(account_id, challenge_id) as tx:
        account = tx.account
        if not account.may_issue(now):
            return {"status": "rate_limited"}
        challenge = tx.challenge
        if challenge is not None and challenge.is_active(now):
            return {"status": "pending", "id": challenge.id}
        code = f"{secrets.randbelow(1_000_000):06d}"
        tx.create_challenge(
            expires_at=now + VALID_FOR,
            next_send_at=now + COOLDOWN,
            code_digest=digest(key, challenge_id, code),
        )
        account.record_issuance(now)
        tx.enqueue_encrypted_dispatch(
            dispatch_id=challenge_id, code=code
        )
    return {"status": "pending", "id": challenge_id}

def verify(repo, account_id, challenge_id, candidate, key, now):
    with repo.transaction(account_id, challenge_id) as tx:
        challenge = tx.challenge
        account = tx.account
        if challenge is None or not challenge.is_active(now):
            return False
        if not account.may_verify(now):
            return False
        if challenge.failures >= MAX_FAILURES:
            return False
        valid_shape = (
            isinstance(candidate, str) and len(candidate) == 6
            and candidate.isascii() and candidate.isdecimal()
        )
        valid = valid_shape and hmac.compare_digest(
            challenge.code_digest, digest(key, challenge_id, candidate)
        )
        if not valid:
            challenge.failures += 1
            account.record_failure(now)
            return False
        challenge.consumed = True
        tx.record_authentication_result()
    return True
Enter fullscreen mode Exit fullscreen mode

The deliberately conservative send behavior returns the existing active challenge instead of issuing another code on an HTTP retry. A distinct operation may schedule another dispatch for that same challenge only after its stored deadline; checking and advancing that deadline must happen in the same transaction as the dispatch reservation. It also consumes an issuance budget. A genuinely new challenge receives a new ID without clearing account failures. None of those decisions belongs in a process-local timer.

Several adapter details are security requirements of this proposal. The server chooses the challenge ID and binds it to the requesting account; callers cannot supply arbitrary account bindings. The adapter must also resolve repeated issuance requests to the account's single active challenge, even if they arrive with different request IDs. The transaction uses authoritative server time and reads current state. An active challenge is unconsumed and unexpired. The keyed digest secret stays outside the challenge store, while the queued code needs encryption and restricted access because the delivery worker must recover it. Delete that recoverable secret when its delivery and expiry policy permits. Hashing the verification field does not protect a plaintext copy left in a queue. That is the storage trap: the row reviewed for authentication can have careful secret handling while a dispatch payload quietly retains the same sensitive value under a different retention policy, so reviewing only the challenge table leaves the actual recoverable copy outside the security boundary.

Finally, the recorded authentication result must support recovery of the same logical result after a lost response.

Otherwise the code is consumed, the client retries, and the user sees a failure even though the transaction succeeded. Binding that recovery to the initiating login session is part of the adapter contract; blindly returning a prior success to anyone who knows a challenge ID would defeat it.

Test recovery before expanding delivery

Start with two concurrent submissions of the correct code: exactly one consumes the challenge, while recovery follows the bound login session. Then submit an incorrect code concurrently from separate workers and check that both failures persist. Exercise a repeated send at the cooldown boundary, replacement after expiry, a transaction rollback, and a transport timeout after acceptance. These are proposed acceptance tests, not reported benchmark results.

One especially revealing test replaces a challenge after several failed guesses and verifies that the account budget still blocks further attempts when exhausted. Another crashes the worker after the transport accepts a dispatch but before the worker records its outcome. The latter exposes duplicate-delivery risk: an outbox preserves the local send intent, but cannot promise exactly one external SMS without an appropriate transport guarantee. State the adapter's actual boundary.

Deploy the state schema and transaction adapter before directing login traffic to them. Define how mixed application versions interpret active challenges and key identifiers. Observe challenge issuance, failed verification, cooldown rejection, expiry, dispatch age, and authentication-result recovery using internal correlation IDs; exclude codes, full destinations, and receipt contents from ordinary logs. Retention should preserve enough event metadata to investigate a disputed login without keeping a recoverable secret indefinitely.

Customer support needs a distinction between a receipt awaiting dispatch, a receipt dispatched, and an authenticated customer requesting access. For email receipts, RFC 7489 defines DMARC policy and reporting around authenticated identifier alignment. It does not establish that a customer read a receipt or authenticated through SMS. A delivery dashboard must not collapse those meanings into one reassuring green status.

Integration effort also has an operating dimension: storage availability, queue retention, key rotation, abuse handling, and support diagnosis require ownership.

Message volume affects operating cost, but a unit price cannot settle whether concurrent retries preserve the authentication boundary.

Rejected option and its valid boundary

Reject the stateless-token-only design for this login path because one-time consumption and shared attempt limits already require coordination. Its valid use case is carrying signed, expiring context where replay within the validity window is acceptable, or carrying context alongside a separate consumption store. The latter is a hybrid design and should be assessed with its shared-state dependencies visible.

For settled-payment receipts, choose atomic challenge state when support login requires one-time SMS verification across workers. Keep the payment event responsible for the receipt and the challenge record responsible for authentication. The same separation lets airline disruption alerts proceed under their own delivery policy while login retries remain bounded and explainable.

References

Top comments (0)