| Integration choice | Pick this when | Work your application still owns |
|---|---|---|
| Verification API | You want a small integration surface for issuing and checking codes | Login binding, session creation, abuse controls, and audit events |
| Messaging API plus your own verifier | You need direct control over challenge state | Code generation, protected storage, expiry, atomic consumption, retries, and delivery correlation |
For an edtech portal, the least complex starting design is a verification API behind a small application interface, with separate records for login verification and compliance notice delivery. TL;DR: In Node.js, bind the SMS OTP challenge to a password-authenticated login attempt, let the verification service check the code, and atomically consume that attempt before creating a session. Correlate notice delivery afterward. A delivered text doesn't establish that someone authenticated or read a notice.
Keep evidence distinct.
This field guide focuses on integration effort and observability: what must be connected, which events make the connection inspectable, and where an apparently successful API call leaves the job unfinished. All identifiers, interfaces, and policy values below are illustrative application design choices. They aren't a commercial API contract.
How should an SMS 2FA API integration expose authentication decisions?
Pick a verification API when the team wants to integrate challenge creation and verification without implementing a code verifier. Before choosing this boundary, establish whether the service exposes the properties your application needs: challenge expiry, attempt controls, one-time acceptance, and identifiers that can be correlated with transport events. Treat missing guarantees as additional implementation work. The application still owns who may start a challenge and what a successful check authorizes.
For a compliance portal, start from a completed password check. Create a pending login attempt for the already enrolled account and phone number. Don't accept a replacement destination from the login form. Otherwise, the flow can demonstrate possession of a number selected by the requester while appearing to verify the account's enrolled factor. Enrollment and number changes need their own authenticated flow.
Pick a messaging API with an application-owned verifier when challenge semantics justify the extra work. That choice gives the team responsibility for the whole verification lifecycle, including concurrency and expired challenges. RFC 4226 describes HOTP, and RFC 6238 defines its time-based extension; neither should be treated as a complete specification for an arbitrary SMS challenge service. If you build a verifier, document its security model and review it separately.
The trade-off is concrete. A smaller adapter can reduce the amount of authentication code maintained locally, while moving some evidence and policy dependencies into an external service. A messaging-only adapter leaves more of those decisions in the application. Count the integration work around each option, including callback authentication and support investigations, before counting endpoint calls.
Audit logs distinguish authentication from notice acknowledgment
Diagram in words: password check → pending login attempt → SMS challenge → successful code check → atomic session creation → authorized notice access. A separate branch runs from notice dispatch → transport status events → delivery record. Both branches carry an internal account reference and a notice reference where appropriate. They represent different claims.
Consider an illustrative notice, notice-campus-policy-17, addressed to an enrolled account. Its audit record should identify the notice version, intended recipient, dispatch attempt, and subsequent delivery observations. A login record should identify the attempt and its verification outcome. An authenticated view of the notice is another event. Keeping these distinctions explicit lets a support engineer explain exactly what happened without converting a delivery receipt into a claim of acknowledgment. The institution must decide what evidence its compliance obligation requires.
Start with a small vocabulary: challenge.started, verification.accepted, notice.dispatched, and notice.delivery_observed. Store failures with bounded reason categories, such as expired or rejected, instead of copying entire upstream responses into logs. Keep raw codes, session credentials, and full phone numbers out of telemetry. Prefer an internal account reference for correlation.
Use event times carefully. A callback can have both a source timestamp and the time your application recorded it; preserving both helps explain delayed observations. Authenticate incoming callbacks using the sender's documented method, deduplicate them using its event identity where available, and apply explicit transition rules. An old observation mustn't silently overwrite a newer state just because it arrived later. These are adapter requirements to verify, not assumptions about every service.
Concurrency control makes the audit commit meaningful
Here's the useful part: make the security-sensitive commit visible in the application interface. The TypeScript example uses a hypothetical verification adapter and durable store. Supply those implementations through your existing server dependencies. No public API routes are implied.
import { randomUUID } from "node:crypto";
type PendingLogin = {
id: string;
accountId: string;
challengeId: string;
expiresAtMs: number;
};
interface VerificationApi {
check(input: {
challengeId: string;
code: string;
}): Promise<
{ status: "accepted" } | { status: "rejected" }
>;
}
interface LoginStore {
findBoundAttempt(
attemptId: string,
browserBinding: string,
): Promise<PendingLogin | null>;
consumeAndCreateSession(input: {
attemptId: string;
browserBinding: string;
accountId: string;
eventId: string;
}): Promise<{ sessionId: string } | null>;
}
export async function finishSmsFactor(
input: {
attemptId: string;
browserBinding: string;
code: string;
},
deps: { verification: VerificationApi; store: LoginStore },
): Promise<{ sessionId: string } | null> {
const attempt = await deps.store.findBoundAttempt(
input.attemptId,
input.browserBinding,
);
if (!attempt || attempt.expiresAtMs <= Date.now()) return null;
const result = await deps.verification.check({
challengeId: attempt.challengeId,
code: input.code,
});
if (result.status !== "accepted") return null;
// Recheck binding, expiry, and unused state inside one transaction.
// Commit consumption, session creation, and an audit outbox event together.
return deps.store.consumeAndCreateSession({
attemptId: attempt.id,
browserBinding: input.browserBinding,
accountId: attempt.accountId,
eventId: randomUUID(),
});
}
The transaction is the hinge.
consumeAndCreateSession must check that the attempt still exists, is bound to this browser, has not expired, and has not already been consumed. Its account must match the stored account. It then consumes the attempt and creates the session and audit outbox entry in the same database transaction. A conditional update or equivalent locking strategy must make simultaneous completions compete for one successful transition. An application-level read followed by an unconditional write doesn't meet this contract.
That second expiry check matters because the external check takes time. The first check prevents pointless requests; the transactional check decides whether authentication can still complete. The audit event records an accepted verification tied to a newly created session. An outbox worker can later publish it without making a logging service part of the authentication transaction.
Publish after committing.
The HTTP handler has additional jobs. Derive browserBinding from protected server-managed login state; never trust a caller's assertion that it owns an attempt. Apply account and request-source abuse controls before calling the adapter. Validate input size and the documented code format. Set a request deadline. Hand the result to the application's existing authentication middleware. The returned identifier is an internal handoff; cookie handling remains the handler's responsibility.
There is also a distributed boundary here. The verification service may accept and consume a code before the local transaction completes. If the application loses that result, it mustn't invent a success. Use documented idempotency or status reconciliation when available. Otherwise, expire the pending flow and require a fresh challenge. That costs the user another step, but preserves a clear authorization decision.
Monitoring follows the joins through deployment
Test 3 cases before enabling the flow: two simultaneous completions, a code check that finishes after local expiry, and a successful external check followed by a failed local commit. The expected outcomes are, respectively, at most one new session, no new session, and no assumed authentication success. Also replay a notice callback and reverse the order of two status observations. The notice history should retain what was observed without fabricating additional deliveries.
For integration tests, use adapter doubles for those timing cases and the service's documented test facilities for its actual request and response contract. A mock accepting your preferred payload proves nothing about the remote API. Keep test accounts and destinations isolated from real compliance recipients.
Make concurrency assertions exact: the race test expects 1 committed session, and the expiry test expects 0. Those are test invariants, not measured performance claims.
Observe conversion between stages. Count challenges started, verification outcomes, sessions committed, and notice delivery observations separately. Measure external verification latency independently of database commit latency. Keep attempt identifiers in access-controlled logs or traces; use bounded outcome labels for metrics so every login doesn't create a new time series.
Investigate one attempt end to end. Start with the internal attempt reference, find the external challenge reference, and compare the adapter outcome with the transaction outcome before looking at notice events. If verification was accepted but the commit failed, the operator should see that boundary explicitly. If authentication completed and dispatch occurred, inspect the notice delivery history separately. If an authenticated view exists, report it as a view. Don't silently upgrade it to acknowledgment. This diagnostic sequence is also a useful acceptance criterion for the integration: an engineer should be able to answer each question from recorded events without retrieving the OTP or inspecting a full phone number.
Alert on symptoms that indicate broken joins: verification successes without corresponding local commits, or dispatches that remain without a delivery observation beyond your chosen operational window. Define that window from the institution's requirements and the transport contract. During deployment, enable a limited cohort, inspect these joins, and expand only after the observed transitions match the intended state machine. Track SMS volume and support burden as operating costs without making a changing unit price the architecture's deciding fact.
Security limits of transport evidence
SMS possession isn't phishing resistance. NIST treats authentication over the public switched telephone network as restricted and calls out risks associated with it. The account recovery path and factor replacement process belong in the same security review as login. A correct OTP check cannot repair an account recovery flow that grants access too easily.
Recovery deserves scrutiny.
A compliance notice introduces another limit: delivery, authenticated access, and explicit acknowledgment are separate evidence categories. Decide which one the institution needs and define retention and access controls around it. DMARC concerns email domain authentication policy and reporting; it doesn't validate an SMS code or establish that a student read a notice. Keep the audit language that precise.
References
The authentication and cryptography references substantiate the boundaries above. The DMARC specification concerns the separate email channel.
Further reading
- NIST SP 800-63B, Authentication and Authenticator Management: https://pages.nist.gov/800-63-4/sp800-63b.html
- RFC 4226, HOTP: https://datatracker.ietf.org/doc/html/rfc4226
- RFC 6238, TOTP: https://datatracker.ietf.org/doc/html/rfc6238
- RFC 7489, DMARC: https://datatracker.ietf.org/doc/html/rfc7489
- Node.js cryptography API, including
randomUUID: https://nodejs.org/api/crypto.html
Top comments (0)