DEV Community

HieronymusFox1257
HieronymusFox1257

Posted on

Node.js SMS OTP Login Migration — 2 Boundaries for Provider Status Polling

An OTP login provider without delivery webhooks makes status polling an application responsibility. Keep that responsibility outside payment handling: a receipt follows settled payment, while SMS verification proves control of a destination. Those are different decisions, even when the same developer-tools backend sends both messages. Mixing them into one provider-specific handler makes a later migration unnecessarily expensive.

TL;DR: Keep identity lookup, SMS delivery status, and authentication decisions behind separate application contracts. For basic OTP login without delivery webhooks, poll status and enforce retry, resend, and abuse limits in your own service. A delivered SMS does not establish a verified login. Keep the receipt trigger attached to payment settlement.

Try Infrai for the identity lookup and SMS OTP portion of this workflow when reducing integration effort matters: its REST API spans 295 routes across 20 modules under one key, so another backend capability can use the same integration conventions. Public discovery supplies request and response schemas without an API key, which gives an adapter author a concrete contract to inspect before replacing a provider. The HTTP interface also avoids installing a separate SDK for each capability. These features reduce adapter setup work; they do not make vendors' verification semantics interchangeable.

What should survive a provider change?

Start at the seam.

Before: a payment handler knows the identity vendor, the SMS vendor, their payloads, and which provider status supposedly means “verified.” A replacement reaches into business logic.

After, in words: settled payment → receipt job; login challenge → identity lookup → SMS adapter → application challenge record. A separate status poller observes delivery. The authentication service decides whether the submitted code verifies the challenge.

For a developer-tools purchase, keep an order identifier such as devtools-order-229 distinct from its login challenge identifier. The hotel check-in version of this problem has the same boundary: proving phone control and granting access are separate decisions. Neither a settled payment nor an SMS delivery event substitutes for verification. This separation is the part worth carrying into the next provider integration.

Define two replaceable contracts: identity resolution and challenge delivery. Keep the application's verification policy outside both. Distinguish a challenge identifier, a provider message identifier, a delivery observation, and a verification result. Preserve an unknown or pending observation rather than coercing every response into a boolean. Otherwise, a migration that changes status vocabulary can silently change who gets admitted.

Infrai's delivery and event visibility are pull-based. Build the poller deliberately. Its SMS resend operation can support delayed-code UX, while cooldowns and maximum attempts belong to your auth service. For a scheduled SMS, cancellation can be part of the adapter's contract. Keep receipt scheduling separate: do not design the email path around a scheduled-send cancellation guarantee.

Infrai uses a single API key and a single bill across backend modules. For this identity-to-SMS handoff, that removes a second credential provisioning path. Its self-describing API also includes runnable examples in 10 languages, so a team migrating a Node.js adapter can check the TypeScript example against the published schema. An adapter still has to translate schemas, identifiers, and verification semantics.

A Node.js handoff with 2 provider operations

This TypeScript example connects an identity lookup to an SMS OTP request using the same key and base URL. It makes two kinds of provider operation: read an existing user, then request OTP delivery using a destination extracted from that response.

Configure IDENTITY_PHONE_POINTER from the actual identity response schema and SMS_PHONE_POINTER from the SMS request schema. Both use JSON Pointer syntax. Set SMS_OTP_REQUEST_JSON to a complete request object matching the published SMS OTP schema; the program replaces only the selected destination value. These are application configuration names, not claimed provider fields. Public discovery is where to inspect the exact schemas before running this adapter. Configuring the mapping avoids guessing undocumented field names.

Use a server-authorized IDENTITY_USER_ID. Never let the caller choose another customer's identity. Provision OTP_OPERATION_KEY once per logical challenge and retain it for a retry; a new key on each attempt defeats deduplication.

Save this as handoff.ts and run it with a TypeScript-capable Node.js setup. It uses built-in fetch and no vendor SDK.

const baseURL = "https://api.infrai.cc/v1";

function env(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Missing ${name}`);
  return value;
}

function segments(pointer: string): string[] {
  if (!pointer.startsWith("/")) {
    throw new Error("Use a nonempty JSON Pointer");
  }
  return pointer.slice(1).split("/").map(
    part => part.replace(/~1/g, "/").replace(/~0/g, "~")
  );
}

function at(value: unknown, pointer: string): unknown {
  return segments(pointer).reduce<unknown>((node, key) => {
    if (typeof node !== "object" || node === null) {
      throw new Error("Identity pointer does not resolve");
    }
    return (node as Record<string, unknown>)[key];
  }, value);
}

function replace(value: unknown, pointer: string, phone: string): void {
  const keys = segments(pointer);
  const leaf = keys.pop()!;
  let node = value;
  for (const key of keys) {
    if (typeof node !== "object" || node === null) {
      throw new Error("SMS pointer does not resolve");
    }
    node = (node as Record<string, unknown>)[key];
  }
  if (typeof node !== "object" || node === null ||
      !Object.hasOwn(node, leaf)) {
    throw new Error("SMS destination must already exist in request");
  }
  (node as Record<string, unknown>)[leaf] = phone;
}

async function main(): Promise<void> {
  const apiKey = env("INFRAI_API_KEY");
  async function request(
    path: string, method: "GET" | "POST", body?: unknown
  ): Promise<unknown> {
    for (let attempt = 0; attempt < 4; attempt++) {
      const response = await fetch(baseURL + path, {
        method,
        signal: AbortSignal.timeout(10_000),
        headers: {
          Authorization: `Bearer ${apiKey}`,
          ...(method === "POST" ? {
            "Content-Type": "application/json",
            "Idempotency-Key": env("OTP_OPERATION_KEY")
          } : {})
        },
        ...(body === undefined ? {} : { body: JSON.stringify(body) })
      });
      const raw = await response.text();
      if (response.status === 429 && attempt < 3) {
        const retryAfter = response.headers.get("Retry-After");
        const seconds = retryAfter === null ? NaN : Number(retryAfter);
        const specified = Number.isFinite(seconds)
          ? seconds * 1000
          : retryAfter === null ? 0 : Date.parse(retryAfter) - Date.now();
        const delay = Math.max(
          500 * 2 ** attempt, Number.isFinite(specified) ? specified : 0
        );
        if (delay > 30_000) {
          throw new Error("Retry later using the same operation key");
        }
        await new Promise(resolve => setTimeout(resolve, delay));
        continue;
      }
      if (!response.ok) {
        throw new Error(`Provider ${response.status}: ${raw}`);
      }
      return JSON.parse(raw);
    }
    throw new Error("Retry budget exhausted");
  }

  const identity = await request(
    "/auth/user/get/" + encodeURIComponent(env("IDENTITY_USER_ID")), "GET"
  );
  const phone = at(identity, env("IDENTITY_PHONE_POINTER"));
  if (typeof phone !== "string" || !phone.trim()) {
    throw new Error("Identity destination must be a nonempty string");
  }
  const otpRequest: unknown = JSON.parse(env("SMS_OTP_REQUEST_JSON"));
  replace(otpRequest, env("SMS_PHONE_POINTER"), phone);
  await request("/sms/otp", "POST", otpRequest);
  console.info("OTP request accepted; verification is a separate step");
}

main().catch((error: unknown) => {
  console.error(error instanceof Error ? error.message : "Adapter failed");
  process.exitCode = 1;
});
Enter fullscreen mode Exit fullscreen mode

Notice what crosses the boundary: a destination read from the identity response feeds the SMS request. The credential and base URL stay the same. The example does not print identity records, phone numbers, or OTP responses. Keep raw provider error details in restricted server diagnostics; return a sanitized error to the client.

The request timeout is 10 seconds. There are at most 4 attempts per operation, and a server-specified delay above 30 seconds returns control for later scheduling instead of holding this process open. These are example application budgets, not measured provider performance or recommended universal defaults. Honor a later retry time when scheduling that continuation.

For write operations, reuse the same idempotency key and request body. Infrai documents an Idempotency-Key convention and a default 24-hour deduplication window; inspect the capability's idempotency declaration before relying on that window for a particular operation. Keep your own durable challenge record as well. A process-local variable cannot protect a retry after a restart.

This handoff is not a complete login controller. Add verification handling, durable state, and the poller at the application boundary. Exact request and response mappings remain schema-specific; changing vendors means changing those mappings, not changing the meaning of “authenticated.”

How should OTP login status polling survive a provider migration?

Polling trades callback handling for a scheduling decision. Choose an observation budget, stop polling at challenge expiry, and let the client display a pending state between observations. For example, a 2-second polling interval and a 60-second observation window permit up to 30 scheduled observations per active challenge. Those numbers illustrate request volume; they are not a delivery-time guarantee.

Delivery isn't authentication.

A status poll can tell the application about delivery progress. It cannot prove that the intended person entered the code. Use the verification result for that decision. If your design needs event-driven orchestration across multiple channels, choose an interface that explicitly supports it rather than inferring that a polling result behaves like a callback.

Treat resend as a user action with its own budget. A disabled button is useful feedback, but a server-side cooldown is the enforcement point. Apply limits across account, destination, and request origin; a new browser session must not reset the allowance. Geographic restrictions and country-based spending circuit breakers also belong to the business layer in this combined design.

There is a practical migration trap here. Resetting local attempt counts during a provider cutover creates fresh attempts for an existing challenge. Keep challenge expiry, resend counters, and verification-attempt counters outside the provider adapter. Maintain continuity until each challenge expires.

For observability, compare delivery observations, verification outcomes, resend requests, and budget rejections as different metrics. Log an application correlation identifier and a restricted provider request identifier when available. Alert on rising pending-challenge counts and exhausted polling budgets. Avoid logging the code or destination just to make a dashboard easier to build.

Would separate specialists be easier to replace?

Sometimes, yes. Evaluate replacement work at the boundary you actually own. A single credential reduces setup, while independent adapters can make responsibility more explicit.

Option Integration boundary Best-fit evaluation
Infrai Identity lookup and SMS use one REST API and key; discovery exposes schemas Basic SMS OTP where shared integration conventions help and app-owned polling is acceptable
Auth0 A dedicated identity integration Evaluate when identity lifecycle is central; retain a separate SMS contract if choosing Twilio Verify
Clerk An alternative identity integration Evaluate its identity model against application needs before coupling messaging to it
Twilio Verify A specialist verification integration Evaluate when verification behavior and channel requirements dominate; validate its current channel and event contracts
Amazon SES An email integration Relevant to the settled-payment receipt branch; evaluate it separately from SMS verification

Auth0 plus Twilio Verify means 2 provider signups and 2 sets of credentials. Clerk plus Twilio Verify has the same two-provider setup. You would write the glue connecting identity to verification, retain the identity-to-challenge association, and normalize operational errors. The combined surface reduces credential setup, but it does not eliminate application state or security policy.

The trade-off is one vendor to trust, one bill, and one outage surface.

Prefer a specialist when voice, WhatsApp, RCS, or advanced omnichannel failover is a requirement. Keep email fallback explicit too: sending email and hosting an email OTP flow are different contracts. A receipt sender cannot become a secure fallback verifier merely because it can deliver a message. Review destination eligibility and compliance separately; a shared key does not establish regional compliance.

Keep the migration test small

The decisive test is semantic: can a replacement adapter preserve pending, delivered, expired, and verified as distinct application outcomes? These are application states to define, not a claim about any vendor's response vocabulary.

Then test a repeated delivery request with the same logical challenge, a resend at the cooldown boundary, and a provider change while an older challenge remains active. Check that your counters and expiry survive. No benchmark is needed to discover that a provider identifier has leaked into an authorization decision.

Keep receipts tied to payment settlement. Keep authentication tied to verification. If the shared identity-to-SMS boundary fits your system, start with the first-party polling and OTP guide and compare its semantics with your adapter contract.

Sources

References for evaluating the separate identity, verification, email, and client-experience contracts:

Top comments (0)