A fast order notification is useful only if the seller can safely reach the order behind it. For a property-management marketplace, resolve that trade-off by keeping notification delivery separate from authentication: an SMS delivery receipt must never authorize access to a new order. TL;DR: build the custom Node.js service around a short-lived, purpose-bound OTP challenge, generate its code with cryptographic randomness, send it through an external SMS API, and validate and consume it atomically before creating a session. Treat delayed delivery as a recovery problem with an explicit state transition.
The concrete flow is a marketplace seller receiving a new order for a property maintenance job. The notification points to the marketplace; the seller signs in before viewing tenant contact details or entering the property workflow. This note concentrates on challenge state and authorization boundaries. Delivery reliability remains the operational decision axis: a fallback that gets a message through but weakens the login boundary is a poor recovery path.
What does a delivered SMS actually prove?
It proves too little to grant access. Keep separate records for the order event, the notification attempt, the authentication challenge, and the resulting session. A delivery callback concerns transport; successful OTP validation concerns an authentication attempt. Neither establishes that the account may view a particular order. Check seller ownership again when serving the order.
Receipts aren't authentication.
NIST SP 800-63B-4 treats public telephone network authentication as restricted and identifies risks such as SIM changes and number porting. SMS can establish a limited possession signal, but it is not phishing-resistant. In this design, a code sent after a password check can serve as an additional factor. A code used alone is a passwordless login mechanism, not automatically two-factor authentication. If the application needs phishing resistance, evaluate a different authenticator rather than describing a stronger random number generator as a solution to that threat.
An order notification must not contain an OTP. Notifications may be retried as business events and may remain useful long after a login challenge should expire. Combining them creates an awkward lifecycle: replaying the order event could accidentally issue another authentication secret. Keep the message purpose narrow, and avoid putting tenant details, access instructions, or login codes into delivery telemetry.
How should a custom service secure OTP generation and validation?
Require a pending login transaction before issuing a challenge. Bind the challenge to that transaction, the account, its previously enrolled phone destination, and the purpose of login. Do not accept a client-supplied replacement phone number during verification. Changing an enrolled destination needs a separate, authenticated recovery process; otherwise the OTP endpoint becomes a way to redirect possession checks.
Use the runtime's cryptographic random generator.
In Node.js, crypto.randomInt(0, 1_000_000) supplies an integer for a six-digit decimal code; format it with leading zeroes. Generate an independent, unpredictable challenge identifier with crypto.randomBytes. Do not derive either value from an order number, timestamp, or ordinary random function. Six digits provide only 1,000,000 possibilities, so online guessing controls are part of verification, not an optional abuse feature. NIST requires rate limiting for short authentication secrets and requires accepting a secret only once while it is valid.
For a concrete proposed policy, expire a challenge after 300 seconds, allow at most 5 failed checks, and permit a replacement request after 30 seconds. These are design choices, not measured delivery targets or universal standards. They fit within NIST's ten-minute maximum completion window for out-of-band authentication, but they still need review against the application's threat model and observed delivery delays. Apply issuance limits across the account, destination, and network signals.
A new challenge must not reset the account's accumulated guessing budget.
Store a keyed digest instead of a plaintext code. An ordinary unsalted hash of six digits is cheap to enumerate after a database leak. An HMAC with a key held separately from the challenge store changes that exposure, although compromise of both the key and records still permits enumeration. Bind the digest input to the challenge identifier and login context so that a copied digest cannot become a valid verifier in a different transaction. Redact the plaintext from request logs, tracing, and error reports; it still necessarily crosses the SMS delivery boundary.
The provider's message identifier belongs on a delivery-attempt record. It is not the challenge identifier and must not be accepted as a login credential.
Make verification one state transition
The Python example below specifies the security-sensitive generation and digest operations independently of the transport adapter. It is a focused reference for the Node.js implementation, not a complete authentication server. The corresponding Node.js primitives are randomInt, createHmac, and timingSafeEqual; compare equal-length digest buffers. Use a server-held HMAC key from the application's secret store.
import hashlib
import hmac
import json
import secrets
def code_digest(key: bytes, challenge_id: str, account_id: str,
login_id: str, code: str) -> bytes:
context = json.dumps(
["seller-login", challenge_id, account_id, login_id, code],
ensure_ascii=True, separators=(",", ":"),
).encode("utf-8")
return hmac.new(key, context, hashlib.sha256).digest()
def issue_material(key: bytes, account_id: str, login_id: str):
challenge_id = secrets.token_urlsafe(24)
code = f"{secrets.randbelow(1_000_000):06d}"
digest = code_digest(key, challenge_id, account_id, login_id, code)
return challenge_id, code, digest
def matches(key: bytes, stored_digest: bytes, challenge_id: str,
account_id: str, login_id: str, supplied: str) -> bool:
if len(supplied) != 6 or any(c not in "0123456789" for c in supplied):
return False
candidate = code_digest(
key, challenge_id, account_id, login_id, supplied
)
return hmac.compare_digest(stored_digest, candidate)
The missing transaction is deliberate: digest comparison alone cannot enforce single use. In the application, acquire the challenge row under a database lock, then check the bound login transaction, account, expiration, remaining attempts, and current status before calling the comparison. Count malformed submissions against the applicable abuse budget too. On failure, update the attempt count; on success, mark the challenge consumed and create the session grant in the same transaction. Commit before reporting success. A second concurrent verifier must observe the consumed state.
That final ordering matters. If two requests read an unconsumed challenge before either writes, both can accept the same code despite using a constant-time comparison. If consumption commits but session creation fails independently, the seller loses a valid code without receiving a session. A transactional session-grant record avoids that split; an opaque session cookie can then represent the committed grant. Set appropriate secure cookie attributes and enforce expiration on the server. OTP verification does not replace session security.
The synthetic example identifies account seller_42, pending login login_17, and order order_731. Bind the challenge to seller_42 and login_17. After login, authorize order_731 against the current seller account. Do not treat knowing the order identifier as permission.
Compare recovery paths after fixing the state model
Persist the challenge before dispatching its SMS, and do not hold a database transaction open while waiting on the external network. Represent submission and delivery as separate states. Authenticate callbacks using the external API's documented mechanism, reject replays where that mechanism supports replay protection, and process duplicate events idempotently. Callback processing must never move a consumed challenge back into a verifiable state.
A timeout is ambiguous.
The external API may have accepted the message even though the client did not receive its response. Record that uncertainty and reconcile using the provider's documented status or idempotency facilities where available. Don't assume every API offers them. The transport adapter should expose the difference between rejection and an unknown outcome so the login policy can make an explicit decision.
| Recovery choice | Reliability benefit | Authentication trade-off |
|---|---|---|
| Repeat the current message | A delayed original and a later copy carry the same code | Requires protected access to the existing code; never extend its original expiry |
| Replace the challenge | Creates a fresh bounded attempt after the cooldown | Atomically supersede the old challenge; delayed messages may contain invalid codes |
| Use a previously enrolled alternative | Offers a path when SMS cannot complete | Requires prior enrollment and an assurance policy; notification addresses alone are insufficient |
For the digest-only storage design above, choose replacement on an explicit request for a new code. It avoids retaining a recoverable OTP, at the cost of making delayed messages more confusing. Atomically invalidate the old challenge before activating its successor, retain the account-level attempt budget, and explain in the message that only the latest code works. A delivery callback arriving late cannot undo supersession.
Do not automatically switch to email because an order notification used email successfully. SPF, defined by RFC 7208, checks whether a sending host is authorized for a domain; it does not prove mailbox possession or authorize a login fallback. If email is an approved recovery mechanism, enroll and protect it as such. Keep transactional order notices free of promotional material, establish the applicable messaging consent requirements, and define what support should do when a seller cannot receive authentication messages. Jurisdiction-specific compliance needs its own review.
Roll out with races and delayed messages in the test plan
Start with synthetic accounts and simulated delivery outcomes. Exercise simultaneous correct submissions, expiry at the boundary, wrong-login challenges, replacement followed by late delivery, duplicate callbacks, and an API timeout after possible acceptance. Assert that exactly one session grant can result from one challenge and that no delivery event can create one. Use a controllable clock in tests rather than waiting for real expiration.
Deploy behind a controlled rollout, then observe the whole login funnel: issuance, API acceptance, reported delivery, successful verification, expiration, and recovery. Report latency distributions and replacement-request rates without storing codes or raw phone numbers. A receipt can help locate a delivery problem; only completed verification tells you that the seller completed this authentication step. Budget for repeat-message volume and support work, but judge the change by successful, correctly authorized order access.
Preserve key identifiers on challenge records during HMAC-key rotation and retain old keys only for the validity window required by outstanding challenges. Keep the external API credential separate from the digest key. Expand rollout only after the concurrency tests pass and observed recovery behavior matches the intended policy.
References
NIST SP 800-63B-4 supplies the authentication requirements and telephone-network limitations. The runtime documentation supports the random-generation and comparison primitives. RFC 7208 defines the narrower SPF boundary; the session guidance covers the post-verification step. The timeout handling, schema boundaries, and rollout policy above are proposed engineering choices.
Sources
- NIST SP 800-63B-4, Authentication and Authenticator Management: https://pages.nist.gov/800-63-4/sp800-63b.html
- Node.js cryptography API: https://nodejs.org/api/crypto.html
- Python cryptographically strong random numbers: https://docs.python.org/3/library/secrets.html
- Python HMAC operations: https://docs.python.org/3/library/hmac.html
- RFC 7208, Sender Policy Framework: https://datatracker.ietf.org/doc/html/rfc7208
- OWASP Session Management Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html
Top comments (0)