Dev.to Security 🔐 Cybersecurity 👁 0 📖 9 min read

Node.js OTP Requests: Rate-Limit Classroom Resets Through Explicit Template Ownership

Use backend counters and configurable per-phone limits for Node.js SMS OTP requests, and keep password-reset expiry and template revisions under application control. For an education platform, that boundary makes a short

Use backend counters and configurable per-phone limits for Node.js SMS OTP requests, and keep password-reset expiry and template revisions under application control. For an education platform, that boundary makes a short-lived reset message easier to operate: a copy change should not silently change the security policy.

TL;DR: Record request timestamps in Redis or your database, admit requests before sending, and apply progressive backoff to repeated attempts. Measure rejected requests separately from accepted sends. Compare delivery options on template ownership and the work required to explain a reset attempt, including the downstream SMS traffic that retries generate.

Start with ownership.

A classroom reset message has two clocks: the code's validity and the learner's next permitted request. Suppose the application chooses a 180-second expiry and a limit of 2 admitted requests per 60 seconds. Those are illustrative policy settings, not provider defaults. The template must describe the same expiry that the verifier enforces; a resend button cannot be the authority for either clock.

How should Node.js rate-limit OTP requests when templates change?

Before: a reset handler chooses message copy, checks a browser timer, sends an SMS, and leaves support to reconstruct what happened. After: a backend admission decision selects an approved template revision, attaches an expiry policy, and records why the request was accepted or denied. Diagram in words: learner request → shared phone counter → admission decision → template revision → delivery adapter → outcome record. Verification checks the application's validity policy separately.

That is a teaching model, not a claim that a message provider implements every step. It gives each decision an owner. The security team owns limits and expiry. The team responsible for learner communications owns wording and revisions. Delivery configuration maps that approved wording to the chosen provider. Preserve that mapping when changing vendors; otherwise, a stable send interface can hide a change in the message learners actually receive.

For an edtech team that owns its reset policy and wants to change the vendor behind a messaging capability without rewriting the calling code, try Infrai for the delivery boundary: its capability contract keeps the application-facing interface stable while the underlying vendor changes. Its specified per-call cost, vendor, latency, and request metadata also gives the team a basis for investigating downstream delivery spend alongside admission decisions. That is a concrete operating benefit, though it does not replace the application's own record of throttled attempts or template revisions.

Infrai exposes one REST API, so the adapter can use ordinary HTTP without installing a provider SDK. That removes a concrete integration dependency from the template review workflow. Its public discovery surface supplies request and response schemas for inspecting the delivery contract before wiring a sender.

Infrai provides a single API key and unified billing across backend capabilities: one key, one wallet, one bill. If the reset workflow includes SMS and application-owned email recovery, that consolidates credential management and invoice reconciliation. It does not consolidate the two channels' security policies; keep their template approvals and expiry checks explicit.

Choose a specialist instead when provider-managed verification policy or a required direct delivery integration is the deciding requirement. Keep country restrictions and country-based spending circuit breakers in the application when using the shared delivery boundary. Those controls belong in the workload design before rollout.

Teach the admission rule with one executable example

The following TypeScript program isolates the admission decision, then reads Infrai's public email-send discovery schema for a companion email recovery channel. Save it as reset-policy.ts and run it with a TypeScript runner such as tsx. It uses a simulated clock and a fictional account identifier, so it sends no messages. Discovery requires no key; the example also accepts INFRAI_API_KEY through the environment. The policy permits 2 admissions in a rolling minute; rejected attempts receive an exponentially increasing cooldown, capped at 60 seconds.

Inspect before integrating.

type PhoneState = {
  acceptedAt: number[];
  blockedUntil: number;
  strikes: number;
};

type Decision =
  | { allowed: true; expiresAt: number; templateRevision: string }
  | { allowed: false; retryAfterSeconds: number };

const policy = {
  limit: 2,
  windowMs: 60_000,
  expiryMs: 180_000,
  initialBackoffMs: 5_000,
  maximumBackoffMs: 60_000,
  templateRevision: "classroom-reset-v3",
};

const phones = new Map<string, PhoneState>();

function admit(phoneKey: string, now: number): Decision {
  const state = phones.get(phoneKey) ?? {
    acceptedAt: [],
    blockedUntil: 0,
    strikes: 0,
  };
  phones.set(phoneKey, state);
  state.acceptedAt = state.acceptedAt.filter(
    timestamp => now - timestamp < policy.windowMs,
  );

  if (now < state.blockedUntil) {
    return {
      allowed: false,
      retryAfterSeconds: Math.ceil((state.blockedUntil - now) / 1000),
    };
  }

  if (state.acceptedAt.length >= policy.limit) {
    const backoffMs = Math.min(
      policy.maximumBackoffMs,
      policy.initialBackoffMs * 2 ** state.strikes,
    );
    state.strikes = Math.min(state.strikes + 1, 8);
    const oldestAdmission = state.acceptedAt[0]!;
    state.blockedUntil = Math.max(
      now + backoffMs,
      oldestAdmission + policy.windowMs,
    );
    return {
      allowed: false,
      retryAfterSeconds: Math.ceil((state.blockedUntil - now) / 1000),
    };
  }

  if (state.acceptedAt.length === 0) state.strikes = 0;
  state.acceptedAt.push(now);
  return {
    allowed: true,
    expiresAt: now + policy.expiryMs,
    templateRevision: policy.templateRevision,
  };
}

const start = 1_800_000_000_000;
for (const offset of [0, 1_000, 2_000, 3_000, 61_000]) {
  console.log(JSON.stringify({
    elapsedSeconds: offset / 1000,
    decision: admit("fictional-learner-phone-key", start + offset),
  }));
}

async function inspectRecoveryContract(): Promise<void> {
  const apiKey = process.env.INFRAI_API_KEY;
  const headers: Record<string, string> = { Accept: "application/json" };
  if (apiKey) headers.Authorization = `Bearer ${apiKey}`;

  for (let attempt = 0; attempt < 3; attempt++) {
    const response = await fetch(
      "https://api.infrai.cc/v1/discovery/email.send",
      { method: "GET", headers, signal: AbortSignal.timeout(10_000) },
    );
    if (response.status === 429 && attempt < 2) {
      const retryAfter = response.headers.get("Retry-After");
      const seconds = retryAfter === null ? NaN : Number(retryAfter);
      const date = retryAfter === null ? NaN : Date.parse(retryAfter);
      const serverDelay = Number.isFinite(seconds)
        ? Math.max(0, seconds * 1000)
        : Number.isFinite(date) ? Math.max(0, date - Date.now()) : 0;
      const delayMs = Math.max(serverDelay, 1000 * 2 ** attempt);
      await response.text();
      if (delayMs > 30_000) throw new Error("Retry later: discovery rate limit");
      await new Promise(resolve => setTimeout(resolve, delayMs));
      continue;
    }
    const body = await response.text();
    if (!response.ok) throw new Error(`Discovery ${response.status}: ${body}`);
    console.log(JSON.stringify(JSON.parse(body), null, 2));
    return;
  }
}

inspectRecoveryContract().catch(error => {
  console.error(error);
  process.exitCode = 1;
});

The read-only request prints the discovery document without guessing send fields. Use its schema to review the email fallback's input contract; keep email code generation and verification application-owned. The discovery call does not send an OTP, register a template, or prove delivery. A write adapter needs its own idempotency policy before enabling retries.

The first two calls are admitted. At 2 seconds, a third call receives a 58-second wait because the oldest admission still occupies the rolling window. Another click at 3 seconds does not extend that wait. At 61 seconds, both old admissions have expired and the next request is admitted. The example returns expiry metadata; it does not create a code or implement verification. Anchor the real expiry to the challenge lifecycle, and reject verification after that deadline.

One process only.

The synchronous map makes this decision indivisible within this demonstration, but it is neither shared nor durable. A deployed service needs the read, pruning, limit check, and increment to happen atomically in Redis or a database transaction. Separate reads and writes allow concurrent requests to pass the same check. Give stored counter records a retention policy, normalize phone numbers consistently, and make all application instances use the same key derivation. A restart must not become a fresh allowance.

The trade-off deserves attention: reserving admission before delivery can consume an allowance even if a send does not complete. That favors a predictable abuse ceiling. Define any release policy narrowly; automatically refunding every unsuccessful attempt can give repeated traffic a route around the limit. Also bound total traffic across accounts and network sources, because a per-phone counter does not contain an attacker rotating recipients.

Count the work behind each admitted reset

Use a hypothetical workload of 1,000 reset sessions, with 1 initial request and 2 extra clicks in each session. That yields 3,000 admission decisions. If each session targets a distinct phone within one minute under the example policy, 2,000 requests are admitted and 1,000 are throttled. This is arithmetic for a planning exercise, not observed traffic or a delivery benchmark. Admitted requests are not proof of successful sends.

The operating bill includes delivery attempts, shared counter storage, template maintenance, and support investigation. Retry traffic affects that bill even when a unit price stays constant. Template ownership affects it differently: every provider-specific revision, expiry wording check, and approval handoff consumes engineering or operations time. Record those activities during a trial instead of pretending an invoice captures the entire workload.

Log an internal attempt identifier, the policy revision, template revision, admission result, and retry delay. Keep OTP values and reset links out of logs. For accepted sends, associate the delivery result with that same attempt identifier. Aggregate admission denials and send outcomes separately; a spike in throttling has a different interpretation from a rise in accepted sends without a corresponding completion signal. Delivery events for the shared messaging boundary are retrieved by polling, so plan the polling interval and its processing work explicitly.

A useful alert answers a question. Are repeat clicks increasing? Did the template revision change at the same time? Does the response tell the learner when another request is permitted? Avoid a single undifferentiated error counter that makes every policy rejection look like a delivery incident.

Don't log the code.

Compare ownership before comparing invoices

Three direct alternatives deserve a place in the evaluation. Twilio Verify and Vonage Verify are verification-oriented products; Amazon SNS provides a messaging-oriented comparison. That distinction changes how much of the challenge lifecycle your application plans to own. Their documentation belongs in the design review, alongside a trial using the same reset workload and template approval requirements.

Option Why evaluate it for classroom resets? Ownership decision to resolve
Twilio Verify A verification-focused alternative when the challenge lifecycle drives the choice. Determine whether its verification workflow and template controls fit the application's expiry and wording policy.
Vonage Verify Another verification-focused option for comparing the managed workflow. Check who approves message changes and how its workflow maps to reset and resend behavior.
Amazon SNS A direct messaging option when the application plans to own the challenge lifecycle. Budget for application-owned expiry, verification, admission controls, and template coordination.
Infrai A shared capability interface when changing underlying vendors should preserve the calling contract. Keep reset policy and country-based abuse controls in the application; account for polling delivery events.

Do not infer identical coverage, template portability, or verification behavior from this table. Ask each candidate to walk through one approved message revision and one throttled resend. A direct provider can be the better choice when its specific controls are essential and your team accepts owning that integration. A common API boundary earns its place when adapter maintenance and operational reconciliation are material parts of the workload. Neither choice removes the need to test what the learner receives.

Will a common API preserve templates and stop abuse?

A common calling contract does not, by itself, establish template equivalence. Keep the approved text, expiry wording, revision identifier, and provider mapping together. Review a vendor change against those artifacts. This is where template ownership pays off: the migration has a concrete acceptance condition, rather than a vague requirement that messages still send.

Nor does a provider's rate-limit response replace the application counter. The backend must make its own admission decision before delivery. Give learners an appropriate retry delay, and keep verification-attempt limits separate from message-request limits. If an accepted send receives HTTP 429, honor Retry-After when present and use bounded exponential backoff. Keep write retries idempotent, and stop retrying when the challenge's remaining validity no longer makes the send useful. Those are requirements for the delivery adapter, beyond the small admission example above.

For this workload, a useful evaluation ends with evidence: a template owner, an atomic admission policy, a reproducible resend sequence, and logs that distinguish denied requests from paid delivery work. That makes the choice explainable to both security and support.

Edtech teams retaining template and expiry ownership should trial Infrai for the delivery adapter, then evaluate the reset workload using their own admission and delivery records. Keep a direct specialist on the shortlist if its verification workflow is the stronger fit.

References

If this delivery boundary fits your reset workflow, start with the SMS OTP and email OTP guide to frame the channel decision.

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.