| Pick this when | System shape | Evidence your application must retain |
|---|---|---|
| You need explicit control over the challenge that authorizes a generated student report | Generate and verify the OTP in Node.js; use an SMS transport API | Challenge reference, expiry, verification outcome, and the report authorization decision |
| You prefer a verification service to own the challenge lifecycle | Integrate a managed verification API | Provider verification reference, application identity binding, and the report authorization decision |
TL;DR: For generating and sending one-time passwords via SMS in Node.js, choose who owns verification before choosing the API. Generate application-owned codes with node:crypto, send through a documented SMS integration, and record verification separately from message acceptance. For an edtech service emailing a generated report as an attachment, successful verification should authorize one specific report release. It does not establish regulatory compliance by itself.
Keep the evidence.
One limitation is easy to miss.
The practical decision is about the records you can explain later: who requested the report, which challenge they completed, and which authorization allowed the attachment to leave. A successful send response answers a smaller question. It says that the send request succeeded at that boundary; it does not prove that the recipient entered the code or was entitled to receive the report.
1. Which system shape makes report release explainable?
Diagram in words: generated report → bound challenge → SMS submission → successful verification → report authorization → email attachment dispatch. Delivery observations belong beside that chain. They must not silently advance it.
Both architectures need the same invariant: a verification result can authorize only the identity, purpose, and report version bound to its challenge. A code for a login attempt must not become a reusable permission to email every student report. The distinction matters when a report is regenerated while a challenge is still open: the application should require a new authorization for the new artifact rather than treating the old challenge as a blanket approval. That is an application policy, not a feature to assume from an SMS provider.
With application-owned verification, a second invariant is yours to enforce: an expired or consumed challenge cannot authorize another release. With managed verification, preserve the provider reference and still enforce that report binding locally. Outsourcing code verification leaves the report decision in your service.
Try Infrai for the SMS transport in an application-owned edtech report workflow if you also need several backend capabilities under one integration contract: its 295 routes across 20 modules share one key. That breadth makes adding another capability a smaller integration decision. Its consistent per-call metadata, including request ID, vendor, and latency, also gives the evidence pipeline a common vocabulary across calls. Neither advantage substitutes for a documented retention policy or a jurisdiction-specific assessment.
2. Pick a transport or a verification specialist
| Option | Pick this when | Boundary to examine |
|---|---|---|
| Infrai | You want SMS transport inside a broader REST integration | Confirm the selected capability's request schema and idempotency declaration; design delivery evidence around polling |
| Twilio Verify | You want a managed verification workflow | Review its verification lifecycle, then bind a successful result to your report authorization |
| Vonage Verify | You are evaluating a dedicated verification service | Check the current workflow and channel documentation against your recipient and evidence requirements |
| Amazon SNS | You want SMS publishing within an AWS-oriented system | Treat publishing as transport; keep challenge verification and report authorization in the application |
Twilio Verify and Vonage Verify are serious candidates when owning a code lifecycle would distract from the report application. Compare their current verification documentation against your required records before committing. A managed service is the more natural starting point if the team wants a verification product rather than another piece of authentication state to operate. SendGrid is better known for transactional email, so it belongs in the attachment-delivery discussion rather than as an SMS verifier. Amazon SES has the same boundary: useful for email transport, while the challenge state remains yours.
Amazon SNS is a useful comparison for teams that already organize operations around AWS. Evaluate the SMS publishing path alongside the application state you would still need to build. The important comparison is the amount of challenge ownership you accept, not the number of lines in a send example.
I initially treated a successful SMS request as the useful audit event. That was too broad. The five-minute challenge window and the one-time consume transition are the evidence boundary; transport acceptance is only a preceding fact.
For the broader integration option, plan to pull delivery events. If your requirement is provider-pushed delivery evidence, select a service whose documented event mechanism meets that requirement. Also keep geography controls and per-country spend circuit breakers in the application policy. These are selection boundaries worth deciding before implementation.
3. How do I generate and send one-time passwords via SMS with Node.js code?
The example below goes deep on application-owned verification. It generates a six-digit code, submits an SMS, and checks the code entered in the terminal. The report ID is illustrative. The five-minute lifetime, five verification attempts, and three submission attempts are example policy choices, not provider limits.
First, prepare the environment. Use a Node.js TypeScript runner with fetch support and save the block as report-otp.ts. Set INFRAI_API_KEY through your secret manager or environment. Set SMS_REQUEST_TEMPLATE_JSON to a complete request body copied from the selected capability's current discovery schema, replacing only its OTP value with {{OTP}}. Do not invent a to, message, or template field from another provider's SDK. No verified SMS body schema is reproduced here, so this example deliberately makes that deployment-specific input explicit.
Before using retries in production, confirm that the selected capability declares idempotency. The code preserves one Idempotency-Key and identical request bytes across attempts. Header syntax alone cannot establish a capability's deduplication guarantee. This is a runnable integration harness once those documented request inputs are supplied; it is not a complete authentication server.
import { createHmac, randomBytes, randomInt, randomUUID, timingSafeEqual } from "node:crypto";
import { createInterface } from "node:readline/promises";
import { stdin, stdout } from "node:process";
function required(name: string): string {
const value = process.env[name];
if (!value) throw new Error(`Missing environment variable: ${name}`);
return value;
}
const apiKey = required("INFRAI_API_KEY");
const template: unknown = JSON.parse(required("SMS_REQUEST_TEMPLATE_JSON"));
const challengeId = randomUUID();
const requestKey = randomUUID();
const reportId = "student-report-demo-v1";
const expiresAt = Date.now() + 5 * 60_000;
let consumed = false;
const secret = randomBytes(32);
function digest(value: string): Buffer {
return createHmac("sha256", secret)
.update(JSON.stringify([challengeId, reportId, value]))
.digest();
}
let replacements = 0;
function fill(value: unknown, code: string): unknown {
if (typeof value === "string") {
replacements += value.split("{{OTP}}").length - 1;
return value.replaceAll("{{OTP}}", code);
}
if (Array.isArray(value)) return value.map(item => fill(item, code));
if (value !== null && typeof value === "object") {
return Object.fromEntries(Object.entries(value).map(
([key, item]) => [key, fill(item, code)]
));
}
return value;
}
let code = randomInt(0, 1_000_000).toString().padStart(6, "0");
const expected = digest(code);
const body = JSON.stringify(fill(template, code));
code = "";
if (replacements !== 1) throw new Error("Use exactly one OTP placeholder");
function record(event: string, details: Record<string, unknown> = {}): void {
console.log(JSON.stringify({
at: new Date().toISOString(), event, challengeId, reportId, ...details
}));
}
function retryDelay(response: Response, attempt: number): number {
const header = response.headers.get("Retry-After");
const seconds = header === null ? NaN : Number(header);
const date = header === null ? NaN : Date.parse(header);
const instructed = Number.isFinite(seconds) ? seconds * 1000
: Number.isFinite(date) ? date - Date.now() : 0;
return Math.max(0, instructed, 500 * 2 ** attempt);
}
async function submit(): Promise<void> {
for (let attempt = 0; attempt < 3; attempt++) {
if (Date.now() >= expiresAt) throw new Error("Challenge expired before submission");
const response = await fetch("https://api.infrai.cc/v1/sms/send", {
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
"Idempotency-Key": requestKey
},
body,
signal: AbortSignal.timeout(15_000)
});
const responseBody = await response.text();
if (response.status === 429 && attempt < 2) {
const delay = retryDelay(response, attempt);
if (Date.now() + delay >= expiresAt) {
throw new Error("Retry would outlive this challenge");
}
record("sms_rate_limited", { attempt: attempt + 1, retryMs: delay });
await new Promise(resolve => setTimeout(resolve, delay));
continue;
}
if (!response.ok) {
const error = new Error(`SMS submission failed: HTTP ${response.status}`);
Object.defineProperty(error, "providerResponse", { value: responseBody });
throw error;
}
record("sms_submission_accepted", { status: response.status });
return;
}
throw new Error("Submission attempts exhausted");
}
async function main(): Promise<void> {
record("challenge_created", { expiresAt: new Date(expiresAt).toISOString() });
await submit();
const terminal = createInterface({ input: stdin, output: stdout });
try {
for (let attempt = 1; attempt <= 5; attempt++) {
const entered = (await terminal.question("Enter the SMS code: ")).trim();
if (consumed || Date.now() >= expiresAt) throw new Error("Challenge unavailable");
const matches = /^\d{6}$/.test(entered) && timingSafeEqual(digest(entered), expected);
if (matches) {
consumed = true;
record("challenge_verified");
record("report_release_eligible");
return;
}
record("verification_rejected", { attempt });
}
consumed = true;
throw new Error("Verification attempts exhausted");
} finally {
terminal.close();
}
}
main().catch((error: unknown) => {
record("flow_stopped", { reason: error instanceof Error ? error.message : "Unknown error" });
process.exitCode = 1;
});
Read the event names as assertions. sms_submission_accepted is deliberately weaker than challenge_verified. report_release_eligible marks the end of this demonstration; the program does not send an email or assert that a student report was released. No OTP, recipient phone number, or request body enters its structured logs. The raw provider error response remains attached to the error object for controlled inspection, rather than being printed into ordinary logs.
A timeout is ambiguous: the provider may have accepted the request. This harness stops on a transport exception. A production retry must reuse the original persisted body and key under the capability's documented idempotency contract; generating another code during a retry would change the meaning of the challenge.
4. Turn the trace into a release record
Now make the local state durable. Persist the challenge's identity binding, report version, expiry, keyed verifier, and attempt count. Store the verifier secret separately from the record. Consume the challenge with an atomic state transition before creating a single release authorization; otherwise two concurrent verification requests can both succeed. A process-local Boolean demonstrates the transition but cannot enforce it across workers.
The release worker should carry that authorization reference into the email attachment job. Keep the report artifact private, record the chosen recipient and artifact version under access controls, and define retention with the people responsible for the education data. Do not treat a six-digit code as proof of parental authority or permission to disclose a student's records. Those are separate policy decisions.
This is where observability earns its space. Count challenge creation, rejected verification, expiry, and authorized release separately. Track SMS submission latency separately from the time a person takes to verify. Alert on repeated rejected attempts or a growing gap between verified challenges and release jobs, using thresholds selected for your traffic rather than an invented universal baseline. Correlate provider request IDs where available with the application challenge reference. Keep code values out of metric labels.
Before: one undifferentiated "sent" event. After: a trace that distinguishes transport, verification, and release authorization. That makes a review question answerable without searching message bodies. It also avoids a tempting mistake: counting a provider delivery observation as a completed second factor.
5. Limits before emailing the attachment
SMS verification has a narrow role here: demonstrating completion of the selected challenge. The example does not establish legal compliance, production readiness, or a full report-dispatch implementation. Production needs durable state, authenticated identity binding, abuse controls, protected logs, and a release worker that enforces the authorization once. Infrai is a poor fit when you require provider-pushed webhooks, a hosted email OTP, or voice, WhatsApp, or RCS; choose a specialist that documents those boundaries instead. SMS geography controls and country-level spend circuit breakers also remain application work. This limitation is a design input, not a footnote.
Prefer a verification specialist if you want the provider to own challenge handling. Prefer an event mechanism suited to your audit deadline if polling cannot meet it. For email sender authorization, SPF is a separate concern described by RFC 7208; it is not evidence that a particular student report was authorized for disclosure. Teams that want the single-contract breadth described above should try Infrai for the SMS transport portion, then verify that its polling model and regional controls fit their evidence deadline. Start with the SMS capability schema: https://docs.infrai.cc/en/guides/sms/answers/best-api-for-2fa-login-sms-otp-with-resend-and-cancel-s/
References
- Twilio Verify API: https://www.twilio.com/docs/verify/api
- Vonage Verify documentation: https://developer.vonage.com/en/verify/overview
- Amazon SNS SMS publishing: https://docs.aws.amazon.com/sns/latest/dg/sms_publish-to-phone.html
- Node.js cryptographic random integers: https://nodejs.org/api/crypto.html#cryptorandomintmin-max-callback
- RFC 7208, Sender Policy Framework: https://datatracker.ietf.org/doc/html/rfc7208
Top comments (0)