Build a custom Node.js service for secure OTP validation around a consumed login challenge, and keep order notifications on a separate authorization path. For a B2B marketplace, the useful compliance evidence is a record connecting the seller, the challenge, and the successful authentication decision. An SMS delivery receipt cannot establish that connection.
Short answer: build the custom Node.js service around cryptographically random OTP generation, server-side expiry and attempt limits, and an atomic consume operation. Send the code through an external SMS API, but let your own authentication state determine whether login succeeds. Treat SMS as a restricted authentication channel with documented risks, as described in the NIST guidance listed below.
The concrete job is to notify a marketplace seller about a new order. The notification can direct the seller to sign in; it must not itself become proof that the recipient controls the seller account. This runbook uses compliance evidence as the design axis: every transition should explain what the system decided without retaining the secret that enabled the decision.
How should a custom OTP service secure validation evidence?
Start with the claim you need to support. A successful SMS API request shows that the sending system accepted a request. A delivery report describes a messaging event. Neither establishes that the intended seller supplied the correct OTP to the login service. Record authentication success only after the verifier accepts an eligible challenge and consumes it.
Keep those events distinct. Delivery isn't authentication.
For an illustrative order order_4821 and seller seller_731, the order notification event can reference an order and an authorized recipient. A separate login challenge should reference the seller account, the pending login transaction, its purpose, its issuance time, expiry, attempt budget, and lifecycle state. Those identifiers are example data, not production observations. Bind the challenge to the pending login transaction so that possession of a challenge identifier alone cannot switch the account being authenticated. An evidence record should also identify the policy version that made the decision. That lets a reviewer distinguish a challenge rejected under an old expiry rule from one consumed under a later rule, without reconstructing application configuration from memory. This is an architectural recommendation, not a claim that a particular event schema satisfies a legal obligation. Retention and access requirements still need an accountable policy owner.
The boundary matters for 2FA, too. An SMS challenge is a second factor only when it supplements an independent first factor; a code-only login does not acquire a second factor merely because the code arrived on a phone. NIST also identifies risks associated with using the public telephone network for out-of-band authentication. Delivery convenience does not remove that decision from the security review.
Generate the secret, then persist the decision boundary
In Node.js, use the cryptographic random integer facility documented in the runtime's crypto module, with an exclusive upper bound of one million, and preserve leading zeroes when formatting a six-digit code. Do not use the general-purpose random number generator. The following Go helper expresses the same generation contract for a service boundary or implementation review; it is not Node.js source.
package otp
import (
"crypto/rand"
"fmt"
"math/big"
)
func Generate() (string, error) {
n, err := rand.Int(rand.Reader, big.NewInt(1_000_000))
if err != nil {
return "", err
}
return fmt.Sprintf("%06d", n.Int64()), nil
}
Generation is the small part. Preserve leading zeroes.
Before enqueueing the SMS, commit a challenge record and a durable sending intent together. Otherwise, a process can send a usable code and disappear before recording the state needed to validate it. A worker should claim the sending intent with a stable identifier, then record its submission outcome separately from the challenge's authentication outcome. These are proposed service invariants; the external API's documented behavior determines which sending guarantees you can actually obtain.
Keep a keyed verifier for the code, scoped to the challenge identifier and purpose, with the key held separately from the challenge store. A plain digest of a six-digit secret permits a small offline search if the database leaks. Restrict the verifier key to the authentication service, and compare equal-length computed values with a timing-safe comparison. Key rotation needs a version reference so that an unexpired challenge is checked with the intended key. The sending worker does need access to the plaintext long enough to submit the message. If a durable queue carries that value, encrypt the payload, restrict worker access, and delete it according to a short, explicit retention policy. A protected verifier in the database achieves little if the same OTP remains readable in a queue inspection screen or request log.
For a concrete starting policy, consider a five-minute expiry and five failed attempts per challenge. These are example configuration choices, not measured results or universal compliance thresholds. NIST's out-of-band guidance supplies the standard-level constraints; the application must also limit attempts across challenge reissuance. Otherwise, a requester can obtain a new budget by repeatedly asking for another code.
Consume once, even when requests race
Validation must make the eligibility check, attempt accounting, and successful consumption one atomic state transition. A read followed by an unrelated update leaves room for two concurrent requests to accept the same code. Use a transaction with appropriate locking or an equivalent conditional operation in the chosen store.
Check the account and pending login binding, purpose, expiry, remaining attempts, and unconsumed state before accepting the verifier match. A failed guess consumes an attempt within the same concurrency boundary. A match changes the challenge to consumed and creates the durable authentication decision. Only then should the service issue the authenticated session through its normal session-management mechanism.
Test the race directly: submit two correct validations concurrently and require exactly one consumption. One must lose.
A client may retry after losing the response to the successful request. That retry must not create a second authentication success or mint a fresh session merely because the code still matches. Define how the same pending login transaction recovers its committed result, with the original transaction binding intact. This is where an idempotency key needs a scope and an owner; a caller-supplied string alone is insufficient. Resends need an equally explicit rule. One defensible policy replaces the previous challenge and invalidates its code before scheduling the replacement. It makes acceptance easier to explain, but delayed messages can leave the seller holding an obsolete code. Show a clear expired-or-replaced response and offer a controlled retry. Do not silently extend expiry on every queue retry: the authentication window belongs to the challenge policy, not the worker's retry schedule.
Operate the SMS boundary without confusing its signals
Use authenticated HTTPS requests to the external SMS API and keep its credentials outside application logs and message bodies. Choose the integration by its documented authentication, request correlation, retry semantics, and callback verification method. No universal callback signature or idempotency header exists across arbitrary APIs, so the adapter must implement the selected interface's actual contract.
A timeout leaves an uncomfortable state: the sender may have accepted the message even though the worker has no response. Record that uncertainty. If the API supports documented idempotent submission, reuse the same sending-intent identifier for the retry. Without that facility, acknowledge the possibility of duplicate messages and ensure they cannot create multiple valid authentication decisions. The local queue cannot prove what happened beyond the network boundary.
For callbacks, verify authenticity before updating delivery state, handle repeated events idempotently, and keep delivery events out of the login-success transition. Apply request limits to issuance as well as validation. The limits should account for the seller account and destination, with broader abuse controls, so changing a challenge identifier does not reset the defense. Operational dashboards should separate issuance rejection, send uncertainty, expired challenges, invalid guesses, successful consumption, and notification delivery. Avoid account identifiers as metric labels; keep restricted correlation details in the event store. Alerting on a delivery symptom alone can send an operator toward the messaging adapter while the actual rejection is an authentication policy decision.
The trade-off is control versus operational ownership: queue ownership, credential rotation, abuse response, and evidence retention all need an operator. A custom verifier is not suitable for a team that cannot maintain those controls. SMS also has a security limitation: it is not phishing-resistant, so a requirement for phishing resistance calls for a different authentication method. Count those responsibilities when deciding whether to own the verifier. Message unit pricing does not answer who can explain a disputed seller login.
Verify the controls and make rollback preserve them
Don't reset the evidence.
Before rollout, verify four cases: concurrent correct submissions consume once; expiry remains effective while sending is delayed; issuing a replacement invalidates the previous code; and exhausting the attempt budget stays effective after reissuance. Also inspect telemetry and queue tooling for plaintext OTP exposure. These checks target decisions that an audit record must later support.
Deploy the policy behind a controlled rollout, retaining the policy version on each challenge. Compare authentication outcomes and sending uncertainty against the team's established baseline; do not invent an acceptable failure rate during an incident. Capture enough correlation to trace an example order notification through a separate seller login without copying phone numbers or codes into a ticket. Rollback should stop issuing challenges under the new policy while preserving consumption and attempt records for challenges already in flight. Never restore an earlier challenge-store snapshot as a routine application rollback: that can resurrect a consumed secret or erase failed attempts. If the old service cannot interpret the new state, reject those challenges and require fresh issuance after the rollback is stable. Availability has a cost here, but reaccepting a consumed code breaks the control you are trying to evidence.
The completion criterion is narrow and useful: the service can explain why one seller login was accepted, demonstrate that its challenge could not be accepted twice, and distinguish that decision from the new-order notification's delivery history. Keep that distinction intact through retries, deployments, and incident response.
References
- NIST SP 800-63B-4, Authentication and Authenticator Management: https://pages.nist.gov/800-63-4/sp800-63b.html
- OWASP Multifactor Authentication Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Multifactor_Authentication_Cheat_Sheet.html
- OWASP Authentication Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html
- Node.js crypto module, including randomInt and timingSafeEqual: https://nodejs.org/api/crypto.html
- Go cryptographic random number generation: https://pkg.go.dev/crypto/rand
- OWASP Logging Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html
Top comments (0)