A customer support team needs to send a marketplace buyer a compliance notice and later explain what happened. Its SMS OTP backend needs an audit log that separates buyer authentication from notice delivery. Successful verification answers one question. Whether that notice reached its destination is a separate question, and collapsing those answers into a single success flag makes the record difficult to defend.
TL;DR: Build the SMS OTP backend around separate authentication and notice records. Apply throttling before issuing or checking a challenge, consume OTPs and recovery codes atomically, and preserve the evidence for each transition. For two-factor authentication, require the existing first-factor session as well. Treat a delivery receipt as its own event, with its own meaning.
This is a proposed implementation for a one-person SaaS, with compliance evidence as the deciding constraint. The goal is to ship weekly without creating a second job maintaining message transport.
Outsource the undifferentiated.
Keep the decisions that explain who could access the notice and what evidence exists. Revenue per hour matters here: support investigations consume the same scarce hours as feature work.
How should SMS OTP authentication and recovery codes affect buyer verification?
Keep the claims narrow. In this design, an accepted SMS code establishes that the authenticated account supplied the expected challenge response. It does not establish that the buyer read a separate compliance notice. A recovery code authorizes a different authentication path. It supplies no fresh evidence about access to the phone.
Separate the records.
For an illustrative support case, use case ID support-case-17, notice revision notice-r3, and an opaque buyer ID. These are example identifiers, not production observations. Associate the challenge with that buyer, its purpose, and the existing authenticated session. Associate a notice attempt with the case, the exact notice revision, its destination reference, and a transport correlation ID. An investigator should be able to connect these records without treating them as interchangeable.
The constraint that changes the choice is the question support must answer later: which notice revision was sent, under whose authorization, and what evidence supports the claimed delivery state? A generic audit entry saying success cannot answer that. The proposed record keeps authorization, dispatch, receipt, and acknowledgment distinct. Whether any combination satisfies a particular compliance obligation needs a policy decision; the code should preserve the distinctions that decision depends on.
This also limits the authentication claim. A backend that accepts only a phone number and a code should not label its result two-factor authentication in this design. Require the first-factor session before starting the second-factor flow, and bind the challenge to that session.
The smallest useful backend boundary
The example below is TypeScript application logic suitable for a NestJS service. It deliberately leaves persistence, session validation, and secret verification behind explicit interfaces. It is a boundary example, not a runnable authentication package. The storage implementation must fulfill the atomicity contract described after the code.
The sample throttle policy allows 3 checks in 300 seconds. Those numbers are illustrative configuration, not a security standard or a measured recommendation. Choose production limits through abuse testing and the needs of legitimate buyers. Issuance needs its own limit, applied before sending an SMS, so repeatedly asking for a fresh challenge cannot bypass the checking limit.
type Method = "sms_otp" | "recovery_code"; type Session = { buyerId: string; sessionId: string; firstFactorVerified: true; }; type CheckInput = { challengeId: string; secret: string; method: Method; }; type CheckResult = | "accepted" | "rejected" | "expired" | "already_used"; interface AttemptBudget { take(input: { buyerId: string; purpose: "notice_access"; limit: number; windowSeconds: number; }): Promise<boolean>; } interface VerificationStore { // Verify, consume, and append the audit event in one transaction. // Reject mismatched buyer, session, purpose, or method bindings. // Enforce expiry and single use for both supported methods. checkAndRecord(input: { buyerId: string; sessionId: string; challengeId: string; secret: string; method: Method; purpose: "notice_access"; occurredAt: Date; }): Promise<CheckResult>; recordThrottle(input: { buyerId: string; sessionId: string; purpose: "notice_access"; occurredAt: Date; }): Promise<void>; } export class NoticeAccessService { constructor( private readonly budget: AttemptBudget, private readonly store: VerificationStore, ) {} async verify(session: Session, input: CheckInput) { const allowed = await this.budget.take({ buyerId: session.buyerId, purpose: "notice_access", limit: 3, windowSeconds: 300, }); if (!allowed) { await this.store.recordThrottle({ buyerId: session.buyerId, sessionId: session.sessionId, purpose: "notice_access", occurredAt: new Date(), }); return { verified: false }; } const result = await this.store.checkAndRecord({ ...input, buyerId: session.buyerId, sessionId: session.sessionId, purpose: "notice_access", occurredAt: new Date(), }); return { verified: result === "accepted" }; } } The trusted session must come from server-side authentication, never from request JSON. Validate the request shape and size before calling this service. Keep the submitted secret out of logs, traces, and audit payloads. Persist protected verification material rather than plaintext codes, and choose a reviewed verification implementation instead of inventing one inside a controller. The interfaces above do not implement those protections for you.
The transaction boundary is the difficult part.
Two simultaneous checks must not both accept the same code. The store should condition consumption on an unused, unexpired record bound to the correct buyer, session, method, and purpose, and commit its audit event with the state change. If that transaction cannot commit, the service must not return a successful verification. Likewise, the shared attempt budget must enforce its allowance across concurrent workers; an in-memory counter in each process does not satisfy this design. Consider an illustrative race: two workers read the same unused challenge, both verify the supplied secret, and each prepares an acceptance event. A separate read followed by an unconditional write lets both workers believe they won. The storage contract must make the second consumption fail even when both requests began with a valid secret. Test the resulting event count too, because rejecting a second response while persisting two acceptance events still leaves support with contradictory evidence.
Recovery codes belong inside that same boundary. In this proposal, issue them only through an authenticated enrollment flow, display them through the approved account experience, store protected verification material, and consume each once. Record recovery_code as the method. Require a separate authenticated process for replacing a phone number; accepting a recovery code should not silently replace the notice destination.
Make the notice evidence explainable
After authorization, create a durable notice intent and an outbox item in one transaction. A worker can then dispatch the exact notice revision and record the resulting attempt. This is a proposed application contract: every retry carries the same notice identity while each transport attempt gets its own identity. An uncertain transport result stays uncertain until additional evidence resolves it. Do not turn a timeout into a claim that nothing was sent.
Use event names that state what the application observed: notice_requested, dispatch_attempted, transport_accepted, delivery_reported, and buyer_acknowledged. Store the event source and its correlation ID. Define the meaning of any delivery status against the selected transport's documented contract before exposing it to support. In particular, keep an explicit buyer acknowledgment separate from a transport report.
Duplicate callbacks are a useful test case.
The proposed handler verifies callback authenticity using the transport's documented mechanism, deduplicates the external event identifier, and preserves the original occurrence time alongside local receipt time. If an event cannot be correlated, retain it for investigation without attaching it to a guessed buyer. Keep failed dispatch attempts visible even if a later attempt succeeds.
Notice content needs similar care. The Mustache manual documents that ordinary variable tags HTML-escape values, while triple-brace tags insert unescaped values. For an HTML notice, ordinary substitutions are a useful default; an unescaped buyer-controlled field would undermine that choice. For SMS, choose rendering rules appropriate to plain text rather than assuming HTML escaping produces the intended message. Save the template revision and the approved rendered artifact under a defined access and retention policy, so a later template edit cannot rewrite the evidence for an earlier dispatch.
A tool-driven support workflow needs a separate boundary too. The tool-use guide describes tools through names, descriptions, and input schemas. If such a workflow requests a notice, expose a narrow operation with a case identifier and an approved notice revision, then enforce authorization in the backend. A well-shaped tool input is not the application's authorization decision. Never let generated text decide that a notice was delivered or that a recovery code was accepted.
Test the record before the happy path
Start with the race that would make the evidence contradictory. Submit the same valid challenge twice concurrently and require exactly one accepted consumption. Then repeat with a recovery code. Add checks for an expired challenge, a different session, a different buyer, and an exhausted attempt budget. Assert that secrets never enter the persisted audit events. These are acceptance criteria for the proposed implementation, not claims about an existing deployment.
Test uncertainty separately.
Interrupt dispatch after a request leaves the worker but before its result is stored. Deliver the same callback twice. Deliver a later callback before an earlier one. The expected support view should preserve what happened and what remains unknown, without treating arrival order as proof of event order.
For deployment, introduce explicit event types and their readers before switching the writer. Track throttled checks, rejected challenges, pending outbox age, and uncorrelated receipts. Give support a case timeline with restricted access, not a raw payload dump. Define retention and deletion rules with the owner of the compliance requirement before collecting additional personal data. More logs do not automatically produce better evidence.
What I would change at scale
At higher volume, I would move dispatch into separately managed workers and enforce the same shared attempt budget across all service instances. I would also test whether support can reconstruct a case from exported evidence, because a record that exists but cannot be interpreted still consumes investigation time. These are design choices, not a report of personal production experience.
The trade-off is operational work.
A durable outbox, protected audit access, and recovery enrollment add implementation effort; keeping their contracts small makes weekly shipping more plausible. Start with the evidence the compliance owner actually requires. Expand when a concrete investigation or obligation demands it.
The decision rule is simple: a buyer verification record explains authentication, and a notice timeline explains dispatch and the delivery evidence received. Keep both precise enough that support can state the result without guessing.
Sources
References:
- Mustache template syntax manual: https://mustache.github.io/mustache.5.html
- Tool use and tool definitions: https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview
