DEV Community

BrennThorn8571
BrennThorn8571

Posted on

Node.js Edtech Login: 5 Checks for SMS OTP and Recipient Suppression

Choose the SMS verification flow together with the recipient suppression policy: an edtech login should stop retrying an invalid destination before a resend button turns it into a recurring delivery problem. Keep challenge state separate from delivery state, and let successful code verification establish access to the phone number.

Short answer: put five checks around a Node.js SMS OTP flow: recipient eligibility, send admission, challenge expiration, atomic code consumption, and resend admission. Use a managed OTP capability for sending, keep the validation boundary explicit, and check suppression before every new attempt. An accepted send is not evidence that a student received a code.

The operational question is broader than the code snippet. A platform handling bounced course emails and invalid phone destinations needs separate suppression records for each channel, an observable path from login request to verification, and enough capacity for retries during enrollment peaks. The recommendation here is an application design, not a measured provider benchmark. All numerical limits below are illustrative policy choices.

What should Node.js code check before verifying a phone number with SMS?

A course email bounce should trigger review of the email destination; it should not automatically invalidate a student's phone number. Likewise, a wrong SMS code is not sufficient evidence that the phone destination is invalid. Mixing those signals creates an account recovery problem: a student can lose a usable channel because a different address failed, or because somebody else submitted guesses against the account.

Keep them separate.

For the runbook, define a recipient eligibility record keyed by account, channel, and destination, alongside a challenge record keyed by an opaque challenge identifier. The first controls permission to attempt delivery. The second controls whether a submitted code can complete authentication. A definitive invalid recipient signal can suppress future sends according to application policy; a delayed receipt should leave delivery uncertain until there is evidence to classify it. Preserve the reason and time of each suppression decision so an operator can distinguish a deliberate block from a missing notification.

Capacity planning starts with admitted challenges, then adds permitted resends and status polling. For example, a design load of 600 login starts per minute with one allowed resend per start implies capacity for up to 1,200 send attempts per minute before accounting for retries. That is a planning scenario, not a throughput claim. If a delivery integration requires polling, its read load belongs in the same worksheet, because shortening the polling interval can increase traffic even while the number of students stays constant.

Define the SLO around the student's outcome: the fraction of eligible login attempts that complete verification within the chosen deadline. Track delivery acceptance, suppression decisions, expired challenges, and verification failures as diagnostic signals. Do not substitute send acceptance for the authentication SLI.

Put five checks around the authentication boundary

First, check recipient eligibility before reserving delivery capacity.

A suppressed destination needs a correction or recovery path; repeatedly sending the same challenge does not repair it. Keep the client-facing response restrained while retaining the detailed reason for authorized operators.

Second, admit requests through rate limits that account for the recipient and the requesting actor. Country restrictions and spending circuit breakers belong in the application policy. A limit on a single button does little if the same requester can start fresh challenges, and a limit on a single account does little to contain traffic spread across many recipients.

Third, generate or obtain the OTP through the selected managed flow and retain challenge state with an expiration policy. Do not assume who stores or compares the code merely because an integration is called an OTP API; confirm the request and response contract before choosing local verification or managed verification. If the application owns comparison, retain a keyed digest rather than the plaintext code, and keep its key outside source control.

Fourth, bind validation to the authenticated flow context and consume a correct challenge atomically.

A verification endpoint must enforce attempt limits and expiration even if the send endpoint already enforced admission. Otherwise, a delivery safeguard becomes an excuse to leave the actual guessing boundary open.

Finally, run resend through admission and suppression again. Specify whether a resend keeps the current challenge or replaces it, and test what happens when a student submits a code from the earlier message. Reserve capacity before contacting a provider, and make any write retry idempotent under the provider's documented contract. A retry after an ambiguous response must not silently become a second logical login challenge.

This is where a stable capability contract can help: Infrai covers email and SMS with one key and one bill through one REST API, reducing credential handling across course notifications and login delivery. Vendor routing behind a capability lets the backend vendor change while the application contract stays put; assess it alongside Twilio Verify, Vonage Verify, and Amazon SNS, with the application owning geographic abuse controls and a polling cadence for delivery events. Provider changes still need end-to-end verification of recipient handling and delivery behavior. A stable interface reduces code changes; it does not prove a delivery SLO.

Send once under a bounded retry policy

The Node.js service should own the login session and admission policy. This Go delivery adapter demonstrates the HTTP boundary without inventing an OTP request schema. Save it as main.go and run it with Go. Set INFRAI_BASE_URL to the documented HTTPS API base including its version, INFRAI_API_KEY to the credential, OTP_REQUEST_JSON to a schema-valid request obtained from capability discovery, and OTP_IDEMPOTENCY_KEY to a durable identifier allocated for this logical send. These environment names are local adapter configuration, not provider request fields.

The example retries HTTP 429 at most twice, honors Retry-After, reuses the same body and idempotency key, and surfaces other unsuccessful responses. The application must persist that key across process restarts and verify the capability's idempotency contract before enabling write retries. No automatic transport-error retry is included: an uncertain send requires reconciliation. The three-attempt cap bounds request count, while the two-minute context bounds elapsed time; a longer Retry-After ends this attempt rather than forcing an early retry.

package main

import (
    "context"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "net/url"
    "os"
    "strconv"
    "strings"
    "time"
)

func sendOTP() error {
    base := strings.TrimRight(os.Getenv("INFRAI_BASE_URL"), "/")
    key := os.Getenv("INFRAI_API_KEY")
    body := os.Getenv("OTP_REQUEST_JSON")
    id := os.Getenv("OTP_IDEMPOTENCY_KEY")
    u, err := url.Parse(base)
    if err != nil || u.Scheme != "https" || u.Host == "" || u.Path != "/v1" ||
        u.User != nil || u.RawQuery != "" || u.Fragment != "" {
        return fmt.Errorf("set INFRAI_BASE_URL to the documented HTTPS API base")
    }
    if key == "" || id == "" || !json.Valid([]byte(body)) {
        return fmt.Errorf("set credential, durable idempotency key, and schema-valid OTP_REQUEST_JSON")
    }
    ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
    defer cancel()
    client := &http.Client{
        Timeout: 15 * time.Second,
        CheckRedirect: func(req *http.Request, via []*http.Request) error {
            return http.ErrUseLastResponse
        },
    }
    for attempt := 0; attempt < 3; attempt++ {
        req, err := http.NewRequestWithContext(ctx, http.MethodPost,
            base+"/sms/otp", strings.NewReader(body))
        if err != nil {
            return err
        }
        req.Header.Set("Authorization", "Bearer "+key)
        req.Header.Set("Content-Type", "application/json")
        req.Header.Set("Idempotency-Key", id)
        resp, err := client.Do(req)
        if err != nil {
            return fmt.Errorf("send outcome uncertain; reconcile before retrying: %w", err)
        }
        data, readErr := io.ReadAll(io.LimitReader(resp.Body, 65537))
        resp.Body.Close()
        if readErr != nil {
            return readErr
        }
        if len(data) > 65536 {
            return fmt.Errorf("response exceeds adapter limit")
        }
        if resp.StatusCode >= 200 && resp.StatusCode < 300 {
            fmt.Println("Send accepted; phone verification remains pending")
            return nil
        }
        if resp.StatusCode != http.StatusTooManyRequests || attempt == 2 {
            return fmt.Errorf("OTP HTTP %d: %s", resp.StatusCode, data)
        }
        delay := time.Second * time.Duration(1<<attempt)
        retry := resp.Header.Get("Retry-After")
        if retry != "" {
            if seconds, err := strconv.Atoi(retry); err == nil && seconds >= 0 {
                if seconds > 120 {
                    return fmt.Errorf("Retry-After exceeds adapter deadline")
                }
                delay = time.Duration(seconds) * time.Second
            } else if date, err := http.ParseTime(retry); err == nil {
                delay = time.Until(date)
                if delay < 0 {
                    delay = 0
                }
            } else {
                return fmt.Errorf("invalid Retry-After: %q", retry)
            }
        }
        timer := time.NewTimer(delay)
        select {
        case <-ctx.Done():
            timer.Stop()
            return ctx.Err()
        case <-timer.C:
        }
    }
    return fmt.Errorf("retry budget exhausted")
}

func main() {
    if err := sendOTP(); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}
Enter fullscreen mode Exit fullscreen mode

This adapter is not the verification endpoint. It neither marks a phone verified nor stores the challenge. Its error body is for a restricted diagnostic context and may contain sensitive data; redact it before sending errors to shared logs or clients. At the application boundary, bind the resulting challenge to the login session, store any locally owned code as a keyed digest, apply expiration and guessing limits, and consume a correct challenge atomically in shared storage. For a concrete test policy, choose a two-minute lifetime and three guesses, then test exhaustion and replay from concurrent requests against the same challenge. A process-local map cannot establish correctness for multiple Node.js instances, and a successful HTTP response cannot establish that the student received the message. Once that distinction is enforced in the state machine, the UI can offer a resend without implicitly granting permission to start unlimited new challenges. Recheck suppression each time.

There is a small but consequential boundary case here: a code submitted exactly at expiration is rejected. Define that behavior before writing client countdowns. A countdown is presentation; the server decides validity.

Choose what to buy and what the platform must own

Compare the candidates at the same boundary. Twilio Verify and Vonage Verify are managed verification products; Amazon SNS is a messaging service whose SMS publishing interface represents a different starting point. Buying transport leaves more authentication behavior with the application than choosing a managed verification workflow. None of these labels establishes performance for a particular student population.

Buy-versus-build choice Candidate What to evaluate for this runbook Platform responsibility
Buy a managed verification workflow Twilio Verify Verify the documented challenge lifecycle, retry behavior, and integration with the login session Recipient eligibility, account recovery, and the application's SLO
Buy a managed verification workflow Vonage Verify Compare workflow behavior against the same expiry, resend, and late-code tests Suppression policy and evidence retention across channels
Buy messaging and build verification Amazon SNS Establish the SMS delivery boundary before building code comparison and challenge state Secure generation, expiration, attempt budgets, atomic consumption, and recovery
Build a common application boundary Internal delivery adapter and shared challenge store Decide whether consistent admission and suppression justify ownership of the integration Adapter maintenance, shared state correctness, and on-call load

The buy-versus-build decision should turn on which team can operate the state machine through a bad delivery interval. A managed workflow can reduce the challenge logic the platform writes; an internal boundary can centralize recipient policy across email and SMS, but it also puts more maintenance on the on-call team. Assess lock-in through the challenge lifecycle and stored identifiers, because replacing a send call is only part of migration.

The main limitation of building verification over messaging is ownership of security-critical state. This approach is not suitable for a platform team that cannot maintain atomic consumption and recipient policy; choose a managed verification workflow such as Twilio Verify or Vonage Verify instead, after validating its lifecycle against the same tests. Conversely, buying a managed challenge does not remove the need for application account recovery. That is a trade-off worth making explicitly.

Email recovery deserves a separate decision. If the selected integration does not provide managed email OTP, the platform must own that challenge lifecycle; sending a message is only one operation in it. SMTP relay and voice, WhatsApp, or RCS recovery should be explicit channel requirements during selection. Their presence cannot be inferred from an email-and-SMS interface.

Verify the rollout, then rehearse rollback

Before admitting students, exercise valid verification, a wrong code, expiration at the boundary, repeated submission after success, and exhaustion of the attempt budget. Then test suppression independently: an invalid email must not suppress a valid phone destination, and a suppressed phone destination must not receive a resend. Include delayed delivery and concurrent submissions, because the single-process example cannot establish shared-store correctness.

Make the release gate observable. Compare admitted challenges, suppressed sends, provider acknowledgments, and completed verifications without writing OTP values into logs. For polling integrations, measure event observation delay separately from student verification time; the operator needs to know whether the evidence is late or the login itself is late. Establish the target from the product's login deadline and test population rather than borrowing an advertised provider number.

Rollback should stop new enrollment into the changed flow while preserving the interpretation of outstanding challenges. Keep suppression decisions intact. If a challenge cannot safely survive the switch, invalidate it explicitly and offer a fresh attempt under the established admission limits; silently accepting an old code against a new store is a broken authentication boundary. Rehearse that transition before the enrollment peak, including the capacity required for replacement challenges.

Delivery reliability depends on this last distinction: reducing provider integration work is useful, but the platform still has to decide when to send, when to suppress, and what evidence permits authentication. Those decisions belong in the runbook before the resend button ships.

References

Top comments (0)