Keeping enough evidence to explain a receipt-access decision conflicts with keeping authentication secrets out of durable records. Resolve that conflict by separating the challenge store from the audit ledger: retain the decision and its order context, while giving the OTP verifier a short, explicitly bounded life. TL;DR: build the custom Node.js service around an atomic validation transition, bind each SMS challenge to one tenant and purpose, and treat the external SMS API's acceptance as transport evidence. It cannot establish that the tenant authenticated or that payment settled.
Consider a property-management service that sends an order receipt after payment settles, with OTP / 2FA login protecting subsequent receipt access. The receipt workflow and authentication workflow need a shared correlation model, but neither should manufacture the other's evidence. A successful code entry does not settle a payment. A settlement event does not identify whoever holds a phone.
Keep those distinctions durable.
How should a custom service secure OTP validation evidence?
Start with the question an auditor or support engineer should be able to answer: why did this tenant gain access to this settled order's receipt? For this proposed design, the answer requires an authenticated account, an authorization decision linking that account to the order, a successful challenge if policy requires one, and a separately recorded settlement transition. These are design requirements, not a claim that SMS satisfies a particular jurisdiction's compliance obligations. Retention periods and acceptable authentication methods need an explicit policy owner.
Use an illustrative order identifier such as order-281, a tenant identifier such as tenant-17, and an independent challenge identifier. Bind the challenge to the account and the purpose receipt_access; retain the order association in the access workflow, where authorization can be checked again when the receipt is requested. Do not accept a caller-supplied tenant identifier as proof of tenancy. The authenticated session supplies that context.
This is where a storage-oriented review should become skeptical. A log line saying “SMS sent” cannot answer which authorization policy ran, whether the payment ledger had settled the order, or whether another worker had already consumed the challenge. Store explicit event types and correlation identifiers instead of asking investigators to infer state from timestamps and message text. A hash of an OTP is not a useful business event either.
Define the boundary.
The resulting evidence is evidence of the service's decisions and observed transport events. It is not proof that a named human read a message, and it does not turn possession of a telephone number into ownership of a property account. NIST's digital identity guidance treats authentication over the public switched telephone network as restricted; that boundary belongs in the authentication policy, alongside recovery and alternative methods.
Generate a secret, then design its storage lifetime
In Node.js, use the platform's cryptographic random-number facilities for code generation; its crypto documentation describes randomInt, including avoidance of modulo bias. Keep the public challenge identifier separate from the secret code. A predictable database row identifier must never become the verifier.
For an illustrative policy, choose a six-digit decimal code, a five-minute lifetime, and at most five submitted guesses per challenge. These numbers are example settings, not measured results or a compliance guarantee. Six decimal digits provide 1,000,000 possible values, including leading zeros, so account-level and destination-level issuance limits matter alongside the per-challenge attempt budget. Creating another challenge must not reset the broader abuse controls. RFC 4226 discusses throttling for a different, counter-based OTP construction; do not label this randomly generated SMS design as HOTP.
The following Python is a reference for the secret-generation and verifier boundary, not a complete authentication server. It deliberately excludes persistence, network calls, and validation transitions so that its guarantees are visible. The Node.js implementation should preserve the same separation using its own cryptographic APIs.
import hashlib
import hmac
import secrets
def verifier(key: bytes, challenge_id: str, code: str) -> bytes:
message = challenge_id.encode("ascii") + b"\x00" + code.encode("ascii")
return hmac.new(key, message, hashlib.sha256).digest()
def issue_material(key: bytes) -> tuple[str, str, bytes]:
challenge_id = secrets.token_hex(16)
code = f"{secrets.randbelow(1_000_000):06d}"
return challenge_id, code, verifier(key, challenge_id, code)
Persist the keyed verifier, its key version, the binding, expiry, attempt count, and state. Keep the key outside the challenge database. An ordinary unkeyed digest leaves a small code space available for offline enumeration after a database disclosure; a keyed construction adds a separate secret boundary, although compromise of both the key and database defeats that separation. Never describe hashing as making a six-digit secret strong.
Plaintext still has a lifecycle. The SMS adapter needs the code to compose the message, so redact request bodies from logs and tracing, bound any queued plaintext lifetime, and remove transient material after dispatch processing. If durable queueing requires retaining the message, its access controls and deletion policy belong in the security design. Encryption at rest does not eliminate those decisions.
Make validation a single state transition
The difficult failure mode is double consumption: two requests read a pending challenge, both compare successfully, and both return success before either records consumption. A constant-time comparison does not fix that race.
Route verification to a store capable of serializing the decision for a challenge. Within that boundary, load the tenant and purpose binding, reject expired or consumed records, enforce the attempt budget, compare the expected verifier, and commit either a failed attempt or consumption. Validate the input as exactly six ASCII digits before building its verifier. Use the runtime's constant-time comparison facility with equal-length digest buffers.
For the proposed policy, count each well-formed candidate that reaches the comparison, including the successful candidate. A malformed request still counts against request-level abuse controls. These details should be explicit because separate implementations can otherwise disagree about what “five attempts” means, and a shared store cannot repair inconsistent application semantics.
Commit the success event with consumption, or persist an event for later publication in that same transaction. An audit event emitted before commit can describe a success that never became durable; one emitted afterward without a durable publication record can disappear if the process stops between those operations. The same reasoning applies to sending the receipt after settlement: record a dispatch intent alongside the settlement transition, then let a worker perform delivery and record its result.
Delivery is separate work.
An SMS acceptance followed by a worker crash creates an ambiguous retry: the service may not know whether the external system accepted the first attempt. Use a documented idempotency contract where available, preserve a stable dispatch identifier, and define what happens when the outcome remains unknown. Do not promise exactly-once delivery across an unspecified external API. A delivery callback must also pass the sender's documented authentication checks before it changes transport state; it must never consume the OTP.
Compare evidence boundaries before storage mechanisms
Only after defining those transitions does a comparison become useful. The choice here is about the assertions a record can support, rather than the attractiveness of a messaging dashboard.
| Design choice | Evidence it can support | Boundary and trade-off |
|---|---|---|
| Challenge state and audit intent in one transaction | A durable validation decision has a durable event awaiting publication | More transactional coupling; still requires an event publisher |
| Independent request logs | Operational request history if logs were retained | Cannot by themselves establish atomic consumption or complete publication |
| SMS acceptance and callback records | What the service observed at the transport boundary | Neither observation establishes receipt access or payment settlement |
| Receipt dispatch intent tied to settlement | Why the system scheduled a particular receipt | External delivery remains a separately observed outcome |
Choose the first pattern when the primary requirement is explaining successful validation after a process failure. Keep observability logs too, but give them a different job. An audit record should carry the event identifier, challenge reference, tenant reference, purpose, decision, policy version, and relevant correlation identifiers; exclude the code and avoid copying full phone numbers into every record. Define who can read these records, how deletion works, and how long each class of record survives.
A mutable audit table is not automatically tamper-evident. If the evidence requirement includes detecting alteration, specify additional controls and verify them independently; a field named audit supplies no integrity guarantee. This is also a team-cost decision: maintaining transactional publication, retention jobs, access reviews, and recovery procedures creates ongoing work even when the SMS integration itself is small.
There is an email boundary as well. If the settled order receipt goes by email, SPF concerns authorization of sending hosts for an email domain, as specified in RFC 7208. It does not authenticate an SMS challenge or establish that a receipt's recipient accessed it. Keep channel-specific evidence attached to its own event type.
Roll out with evidence checks
First define the state model and retention policy, then exercise the service with a controlled SMS adapter. Test simultaneous valid submissions, expired codes, exhausted attempts, repeated issuance, cross-tenant requests, duplicated callbacks, and a process stop after external acceptance. Assert the resulting durable state and audit events, including the absence of secrets. A test that merely observes an HTTP success misses the storage question.
Deploy to a bounded tenant cohort with a rollback plan that preserves consumption state and outstanding settlement dispatch intents. Track validation rejections by reason, dispatch ambiguity, and unpublished-event age; keep identifiers available for authorized investigation without making the monitoring stream a second personal-data database. Before expanding, reconcile settled orders against receipt dispatch intents and successful receipt access against authorization and challenge evidence.
The release decision should turn on whether another engineer can reconstruct why access was granted and why a receipt was scheduled. That is a testable evidence requirement. SMS acceptance alone cannot answer it.
References
The Node.js crypto reference documents the cryptographic primitives mentioned above. Python's secrets and hmac references describe the primitives used in the illustrative code. NIST SP 800-63B supplies the authentication-policy boundary for PSTN delivery; RFC 4226 provides the narrower throttling discussion for HOTP. RFC 7208 addresses SPF's email scope. None of these sources certifies this proposed property-management workflow as compliant.
Top comments (0)