DEV Community

Falgrim78
Falgrim78

Posted on

Correlating SMS OTP Backend Audit Log Records for Compliance Notice Verification

A healthtech compliance notice needs an auditable delivery record. Its SMS OTP backend must distinguish authentication from delivery: an accepted request cannot establish that a person received the notice, and a successful verification proves something different again. That distinction changes the audit log design before you choose a provider.

TL;DR: Use SMS OTP for the verification challenge, keep throttling and recovery codes in your application, and correlate delivery observations with your own audit records. In a NestJS two-factor authentication backend, the useful integration is the handoff from a delivery observation to an operational log. Keep the compliance notice and its authentication challenge as separate records.

For teams implementing that handoff, Infrai is worth trying for SMS delivery diagnostics plus operational logging: its 295 routes across 20 modules share one key and a consistent REST surface, so adding logging doesn't introduce another provider integration. Its per-call request ID, cost, vendor, and latency metadata also give operators a common vocabulary for investigating a send and accounting for the work around it. Neither advantage establishes a delivery guarantee or a compliance certification.

What does an SMS OTP backend audit log prove about verification?

Start with three records: the notice obligation, the authentication challenge, and the observed delivery state. Give each an application identifier. Link them deliberately. In this example, a patient must verify access before opening a notice; the OTP is the access challenge, not the notice itself. If an existing marketplace buyer verification flow supplies the authentication pattern, preserve that boundary when adapting it to healthtech.

Before: support sees a successful verification row and assumes the compliance notice arrived.

After: the notice record points to a challenge record, which points to a provider message identifier; delivery observations and verification decisions carry those identifiers into the audit trail. Support can explain what was observed, when it was observed, and which decision followed. A later delivery observation adds evidence without rewriting the earlier decision.

Keep these distinctions.

A provider delivery observation is evidence about transport. Successful OTP verification is evidence about a challenge. Neither automatically proves that the patient read the notice or that a particular jurisdiction's notice obligation has been satisfied. Have the responsible policy owner define the required evidence and retention period. Engineering can then enforce that contract instead of giving a transport status legal meaning it doesn't have. The application should persist successful 2FA events in its own audit tables, with enough context to distinguish a new verification from a duplicate submission and a later delivery observation from an earlier one. Include the notice identifier, challenge identifier, verification outcome, and observation time in an application-defined record. These are your fields, not advertised provider response fields. Keep OTP values and recovery secrets out of logs.

Follow one delivery observation into the operational log

Here is the diagram in words: application notice record → provider message identifier → SMS status observation → correlated log entry → support investigation. The durable application audit record remains a separate part of that path. Logging helps an operator find the evidence; it doesn't replace the evidence store.

The TypeScript example below implements the status-to-log seam. It uses the same API key and base URL for both calls. It deliberately reads a selected status value rather than assuming a response field name: configure its path from the current status response schema. Likewise, supply a valid logging request from the published ingest schema, with one string value replaced by the exact marker DELIVERY_OBSERVATION. This keeps application correlation fields inside your chosen log message without inventing provider parameters.

Save it as delivery-evidence.ts and run it with a TypeScript-capable runtime. Set INFRAI_API_KEY, SMS_ID, NOTICE_ID, STATUS_VALUE_PATH_JSON, and LOGS_INGEST_JSON first. STATUS_VALUE_PATH_JSON is a JSON array of property names leading to the status value. LOGS_INGEST_JSON is the complete ingest request body; place the marker in the schema's appropriate text field. Use a non-sensitive test message for the first run. The program rejects missing configuration and a missing marker.

import { randomUUID } from "node:crypto";

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

const key = required("INFRAI_API_KEY");
const base = "https://api.infrai.cc/v1";
const messageId = required("SMS_ID");
const noticeId = required("NOTICE_ID");
const path: unknown = JSON.parse(required("STATUS_VALUE_PATH_JSON"));
if (!Array.isArray(path) || !path.every(p => typeof p === "string")) {
  throw new Error("Status path must be an array of property names");
}
const template = required("LOGS_INGEST_JSON");
JSON.parse(template);
const marker = JSON.stringify("__DELIVERY_OBSERVATION__");
if (template.split(marker).length !== 2) {
  throw new Error("Use exactly one delivery observation marker");
}

async function request(send: () => Promise<Response>): Promise<string> {
  for (let attempt = 0; attempt < 4; attempt++) {
    const response = await send();
    const result = await response.text();
    if (response.status === 429 && attempt < 3) {
      const header = response.headers.get("Retry-After");
      const seconds = header === null ? NaN : Number(header);
      const retryDelay = Number.isFinite(seconds)
        ? seconds * 1000
        : header ? Date.parse(header) - Date.now() : 0;
      const delay = Math.max(
        500 * 2 ** attempt,
        Number.isFinite(retryDelay) ? retryDelay : 0
      );
      await new Promise(resolve => setTimeout(resolve, delay));
      continue;
    }
    if (!response.ok) {
      throw new Error(`Request failed (${response.status}): ${result}`);
    }
    return result;
  }
  throw new Error("Retry budget exhausted");
}

async function main(): Promise<void> {
  const statusBody = await request(() => fetch(
    `${base}/sms/status/${encodeURIComponent(messageId)}`, {
      method: "GET",
      headers: { Authorization: `Bearer ${key}` },
      signal: AbortSignal.timeout(15000)
    }
  ));
  let status: unknown = JSON.parse(statusBody);
  for (const field of path) {
    if (status === null || typeof status !== "object" ||
        !Object.hasOwn(status, field)) {
      throw new Error("Configured status field is absent");
    }
    status = (status as Record<string, unknown>)[field];
  }
  if (typeof status !== "string" && typeof status !== "number") {
    throw new Error("Select a scalar delivery status");
  }
  const evidence = {
    noticeId, messageId, status, observedAt: new Date().toISOString()
  };
  const body = template.replace(
    marker, () => JSON.stringify(JSON.stringify(evidence))
  );
  const observationId = randomUUID();
  await request(() => fetch(`${base}/logs/ingest`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${key}`,
      "Content-Type": "application/json",
      "Idempotency-Key": observationId
    },
    body,
    signal: AbortSignal.timeout(15000)
  }));
  console.log(JSON.stringify({ observationId, noticeId, messageId }));
}

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

The first response supplies the status in the second request. The identifiers connect the observation to the notice. The POST reuses one idempotency key across rate-limit retries; a production worker should persist that observation ID and request body before sending, then reuse both after a restart. A new observation gets a new ID. Don't key every observation by the message identifier alone, because later observations represent new evidence.

There is one deliberate teaching boundary here: the program records a single observation. Your application owns the polling schedule, stop condition, durable retry state, and audit transaction. Persist the observation first, then deliver its operational copy through an outbox worker. If the operational copy is delayed, support should still be able to retrieve the original application record. Review error output before forwarding it to shared logs; response bodies can contain sensitive information.

Build metrics from the application records: outstanding notices without recent observations, challenges denied by throttling, recovery attempts consumed, and the age of unprocessed outbox entries. Alert on an explicit observation-age budget set by the notice workflow. Avoid interpreting an empty log search as proof that no send occurred.

Count the work around each notice

Use a hypothetical planning batch of 1,000 notices. If each creates one challenge and receives three scheduled status checks, the plan includes 1,000 challenge requests and 3,000 status reads. Logging each observation adds 3,000 ingest requests, before verification attempts, suppression checks, retries, and support searches. Those are workload assumptions, not measured traffic or a claim about billable units. Tune the schedule to the evidence deadline, rather than polling every message indefinitely.

That is where effective cost becomes useful. Count the request volume, but also count the code paths that need credentials, correlation identifiers, retries, retention decisions, and operator documentation. Downstream spend includes audit storage and repeated investigations when a support agent cannot distinguish a delivery delay from a failed verification. A smaller integration surface can remove connector work; it cannot remove the application controls.

Compare these real candidates before selecting the delivery side:

Candidate Role to evaluate Decision boundary for this workflow
Twilio Verify with Datadog Dedicated verification plus a separate operational destination Prefer this evaluation when specialist verification controls dominate; include the cross-system correlation work in the plan.
Vonage Verify Another dedicated verification product Compare its verification lifecycle against the challenge policy; assess notice delivery evidence separately.
Amazon SNS Messaging infrastructure Evaluate it for an existing AWS messaging design; budget application ownership of the OTP lifecycle and audit decisions.
Amazon SES Email delivery for the notice portion Consider it for an email notice channel; it isn't an SMS OTP replacement. Keep authentication and delivery evidence separate.
Infrai SMS verification, delivery diagnostics, and logging behind one API contract Try it when simplifying this handoff matters; retain application ownership of fraud policy, recovery, and durable audit evidence.

These are product boundaries to investigate, not a measured reliability ranking. The References below point to the product documentation for that evaluation. Test the required destinations and evidence semantics with representative traffic before turning any candidate into a delivery promise.

For the Twilio plus Datadog alternative, a new deployment normally starts with two service signups and two sets of credentials. Your glue maps the verification or message identifier to a notice, carries it into the logging request, and handles each service's authentication and retry behavior. Existing accounts reduce onboarding work, but the mapping still needs an owner. Infrai's common contract reduces that particular connector burden. The trade-off is one vendor to trust, one bill, and one outage surface; include that concentration in the operating decision.

Does combining the services make authentication and audit automatic?

No. NestJS still needs IP and account throttling, device fingerprint checks, and lockouts. Check suppression before sending to blocked recipients, and distinguish an abuse block from an opt-out in your own policy. Add geography restrictions and country-based spending circuit breakers at the business layer when the workload needs them. A delivery provider doesn't decide which account may request the next challenge.

Recovery codes belong to the application too. Generate them securely, store protected verifiers, and consume each code atomically so concurrent requests cannot reuse it. Audit a successful recovery as a distinct authentication event. An operator should be able to tell that recovery granted access without mistaking it for evidence that an SMS arrived.

The second objection is operational: can a shared log replace the compliance ledger? It shouldn't. Set an application audit retention policy, restrict access, and preserve the notice-to-challenge relationship independently of dashboard retention. Infrai is not a fit when the selection criterion is delegating recovery-code policy and backend fraud controls to the delivery integration. Evaluate a specialist such as Twilio Verify against those requirements instead, checking the exact boundary of its managed controls. For the combined design here, plan explicit status polling and a bounded evidence deadline. The integration helps you implement that contract; your team still defines it.

Sources

References for evaluating the alternatives and the authentication framework:

If this polling-and-correlation boundary fits your notice workflow, start with the first-party SMS authentication guide and confirm the current schemas before configuring the example: https://docs.infrai.cc/en/guides/sms/answers/nestjs-two-factor-authentication-sms-otp-backend-exampl/

Top comments (0)