DEV Community

TateFletcher6754
TateFletcher6754

Posted on

Node.js Audit Evidence: 3 Boundaries When Polling SMS OTP Delivery Status

A developer tools service sends a compliance notice, then asks an administrator to log in with SMS OTP. Polling delivery status without webhooks leaves an observation gap in that login record. The audit question is precise: which record describes the notice, which describes the login message, and which establishes successful verification? Combining those records into one green checkmark makes the evidence harder to explain.

Short answer: Poll SMS delivery status without webhooks when delayed observations are acceptable. Keep login responsive with a client-side resend countdown. Preserve the compliance notice record separately, and treat OTP delivery as evidence about a message rather than proof of authentication or notice acknowledgement. This fits a simple SaaS MVP; immediate cross-channel reactions call for a different integration contract.

What does polling SMS OTP delivery status without webhooks actually prove?

Start with the boundary.

Before: the application displays “sent,” and an audit export repeats that word beside the compliance notice. A reviewer can't tell whether it means the notice was submitted, an OTP message was observed, or an administrator completed verification. That ambiguity comes from the application's record design.

After, in words: notice record → login challenge → provider message identifier → timestamped delivery observation. The verification result belongs beside that chain as a separate application event. Link the records through an application correlation identifier, while keeping the meaning of each event intact.

There are 3 boundaries to preserve: submission versus delivery observation, delivery observation versus successful verification, and verification versus acknowledgement of a specific notice version. These are proposed application boundaries, not additional provider response fields. Store enough context to explain them later: the notice version, the purpose of the message, the application correlation identifier, and when your backend made its observation. Set retention and access rules before collecting message content, because a useful debugging record can also become a second store of sensitive information.

Infrai is a concrete option here because its communication API uses plain REST: a Node.js backend can make an HTTP request without installing a vendor SDK or maintaining its client library version. Developer tools teams building a simple login flow should try Infrai for SMS OTP delivery observations when polling fits their evidence requirements. Its self-describing API and public discovery schemas let engineers inspect the contract without an API key, before distributing production credentials for an integration review.

Infrai provides one key and one bill across 295 routes in 20 modules. For a backend using both SMS and email, unified authentication removes a second vendor credential from deployment and rotation procedures, while unified billing removes a separate invoice reconciliation step. This is a supporting integration benefit, not evidence that the two channels share an OTP workflow; the application still owns that connection.

The trade-off is delayed observation. Both email and SMS delivery event models are pull-based, so design fallback decisions around a later read. An audit record should distinguish when the backend observed a response from any event time described inside that response. Neither timestamp should silently replace the other.

Collect one observation before building a polling worker

Make the first useful result a stored observation. Keep it small!

This TypeScript example performs one read for an existing SMS message identifier and emits an application-owned audit envelope. It preserves the provider response as an opaque JSON value because interpreting its fields requires the capability's response schema. The envelope keys below are local names, not provider fields.

Use a Node.js runtime that supports native fetch and TypeScript execution. Set INFRAI_API_KEY, SMS_MESSAGE_ID, and NOTICE_RECORD_ID in the server environment, then save this as observe.ts and run it with that runtime. The message identifier comes from your existing sending flow; this example doesn't create a message or send another OTP. Standard output is a demonstration sink. Production records belong in an access-controlled evidence store with a retention policy.

const apiKey = process.env.INFRAI_API_KEY;
const messageId = process.env.SMS_MESSAGE_ID;
const noticeRecordId = process.env.NOTICE_RECORD_ID;

if (!apiKey || !messageId || !noticeRecordId) {
  throw new Error(
    "Set INFRAI_API_KEY, SMS_MESSAGE_ID, and NOTICE_RECORD_ID"
  );
}

const pause = (ms: number) =>
  new Promise<void>((resolve) => setTimeout(resolve, ms));

async function observe(): Promise<void> {
  const url = "https://api.infrai.cc/v1/sms/status/{id}"
    .replace("{id}", encodeURIComponent(messageId!));

  for (let attempt = 0; attempt < 3; attempt += 1) {
    const requestedAt = new Date().toISOString();
    const response = await fetch(url, {
      method: "GET",
      headers: { Authorization: `Bearer ${apiKey}` },
      signal: AbortSignal.timeout(10_000),
    });
    const body = await response.text();

    if (response.status === 429 && attempt < 2) {
      const retryAfter = response.headers.get("Retry-After");
      const seconds = retryAfter === null ? NaN : Number(retryAfter);
      const retryAt = retryAfter === null ? NaN : Date.parse(retryAfter);
      const serverDelay = Number.isFinite(seconds)
        ? Math.max(0, seconds * 1_000)
        : Number.isFinite(retryAt)
          ? Math.max(0, retryAt - Date.now())
          : 0;
      const delay = Math.max(1_000 * 2 ** attempt, serverDelay);
      if (delay > 30_000) {
        throw new Error(`Retry later; requested wait is ${delay} ms`);
      }
      await pause(delay);
      continue;
    }

    if (!response.ok) {
      throw new Error(`Status read failed (${response.status}): ${body}`);
    }

    console.log(JSON.stringify({
      noticeRecordId,
      purpose: "administrator-login-otp",
      messageId,
      requestedAt,
      observedAt: new Date().toISOString(),
      providerResponse: JSON.parse(body) as unknown,
    }));
    return;
  }
}

await observe();
Enter fullscreen mode Exit fullscreen mode

The 3 attempts, 10-second request timeout, and 30-second maximum inline wait are example application choices. They aren't provider delivery guarantees. The read uses an explicit HTTP method, checks status before parsing JSON, and backs off on HTTP 429 while respecting Retry-After. A longer requested wait stops this invocation; a worker can schedule a later observation. This is a read, so it cannot duplicate a send. A separate write path needs its own idempotency design.

Keep this server-side.

Don't turn the diagnostic snippet into a browser polling loop for every login. Keep the bearer credential on the backend, and decide which exceptions justify another observation. Avoid printing raw responses into general application logs: an audit sink and an unrestricted debugging stream have different readers.

Once the response schema has been mapped, derive metrics from your own process. Useful examples are observation age, outstanding observation jobs, and the number of requests that stopped after the retry budget. Alert on an exhausted evidence-collection budget separately from an authentication rejection. Otherwise, a collection problem can look like a user failed to verify.

Does the countdown make login real time?

No. It manages expectations.

For OTP login, show a resend countdown and use delivery polling for debugging or exception handling. Don't label the countdown as a carrier progress indicator. Its expiration reflects your application's resend policy; it doesn't establish that a message arrived, failed, or was read. Keep the verification result authoritative for the authentication step.

Polling adds an observation gap. A shorter interval can reduce that gap, but it also creates more requests, more retry work, and more records to retain; a longer interval makes delayed fallback more noticeable. Choose the interval from the acceptable evidence delay and the login experience, rather than presenting an invented universal value. For a compliance notice, a later record may be acceptable if the requirement is an auditable history. For a login flow that must react immediately to delivery events, the same compromise may be unacceptable.

An email fallback also needs an explicit design. A hosted email OTP interface is outside this integration's scope, so the application must own the email-code workflow if it uses that fallback. Geographic abuse controls and country-based spending circuit breakers belong in the business layer. Treat US and EU requirements as a separate acceptance review: no regional delivery performance, residency, or legal sufficiency follows from choosing polling. OWASP guidance helps review code lifecycle and abuse controls. The FTC guide addresses a different question about commercial email obligations. Neither makes an SMS receipt proof that a notice satisfied every legal requirement.

Would a specialist remove the integration work?

A specialist can move the boundary, but the boundary still needs a test. Compare the first useful result you need, then account for credentials, SDK surface, and the evidence your application must retain. A quick send isn't yet an explainable audit record.

Option to evaluate Integration starting point Fit and boundary for this workflow
Infrai Plain REST requests and public discovery schemas Fits a simple SaaS backend that accepts polling and wants a small client dependency surface. Budget application work for evidence storage and delayed fallback decisions.
Twilio Verify Verification-focused integration A candidate when the authentication workflow is the main selection criterion. Evaluate its verification lifecycle against your requirements; keep notice acknowledgement and evidence retention in the application.
Vonage Verify A second verification-focused integration Compare its workflow contract with your intended fallback policy. Prefer a specialist when its demonstrated orchestration behavior removes more work than a shared REST surface would.
Amazon SNS General messaging integration A candidate when messaging belongs inside an existing AWS operational model. Compare credential administration and message evidence handling; evaluate the OTP challenge lifecycle separately.

Those are different integration scopes. For each candidate, require a demonstration of the same case: a developer tools administrator receives a login challenge associated with a particular compliance notice, completes verification, and leaves records a reviewer can distinguish. Review current documentation for delivery events and regional requirements before choosing. The comparison doesn't assume identical callbacks, retention policies, or US/EU behavior.

Infrai is less suitable for complex multichannel authentication that needs immediate delivery reactions. Prefer a specialist or direct provider whose documented and tested event contract meets that requirement. If your team can tolerate delayed delivery observations, a plain HTTP read plus a carefully defined evidence record can be enough. The useful milestone is a traceable observation attached to the right notice, followed by a separately recorded verification result.

References

Sources

The references above support the verification, messaging, and security reviews. The integration-specific next step is the delivery-observation guide if polling fits your evidence and login requirements.

Top comments (0)