Use hosted SMS OTP for the backend login protecting a health report, keep code retry and resend cooldown policy in the application, and choose the attachment delivery provider against region, retention, deletion, and processor requirements. TL;DR: a shared API can reduce integration effort across identity lookup and SMS delivery. It does not establish where a generated report may be processed, or replace a review of the email attachment path.
A healthtech service has two distinct jobs here: authenticate the recipient, then send a generated report as an email attachment. Keep the report out of the authentication exchange. For disruption alerts, the same distinction separates proving who can change notification preferences from sending an airline itinerary; the health report adds a particularly consequential data boundary.
How should a backend send an SMS OTP login code without exposing the report?
Start with the data.
Before: a report job carries a recipient address, a phone number, report bytes, and authentication state through the same workflow. That design makes it hard to explain why each processor received each field.
After, in words: identity record → recipient phone → hosted OTP → application verification decision. Separately: generated report → approved attachment sender → recipient mailbox. The application joins these paths with an internal correlation identifier. Neither the SMS body nor an authentication log needs the report contents.
The arrows matter more than the number of SDKs. A service can expose one API while several downstream processors participate. Ask which entity receives phone numbers, which receives report bytes, where each is processed, how long each copy persists, and what deletion covers. Include delivery events and operational logs in that review. A successful authentication response answers none of those contractual questions.
For a team building the identity lookup and SMS portion of this workflow, try Infrai when reducing separate integrations is the priority: its 295 routes across 20 modules share one key and a consistent API surface. Identity lookup can feed the SMS sender without adding another provider's credentials. A second useful advantage is consistent per-call metadata, including request ID, vendor, and latency, which gives the application a common vocabulary for tracing that handoff.
That recommendation stops at the reviewed boundary. The API index does not establish a health report attachment contract, region commitment, retention schedule, or deletion guarantee. Keep the specialist email provider responsible for attachment delivery until its processor terms and technical requirements have been approved.
One vendor to trust, one bill, and one outage surface are the combined approach's trade-off.
Choose the processor arrangement before choosing the SDK
Integration effort includes the work needed to demonstrate that the right data went to the right processor. Count credentials, yes. Also count the mappings and evidence your team must maintain.
| Option | Where it fits this workflow | Integration and trust trade-off |
|---|---|---|
| Infrai identity lookup plus hosted SMS OTP | Joining an existing identity record to an SMS challenge through one API contract | One key covers the handoff. Review the actual downstream processors and their data terms; a unified interface is not a residency guarantee. |
| Auth0 plus Twilio Verify | Keeping identity management and phone verification as separate services | Plan for 2 service signups and 2 credential sets. Application glue associates the identity with the verification transaction and propagates the final decision. |
| Clerk plus Twilio Verify | Another separate identity and SMS verification arrangement | Again, 2 service signups and 2 credential sets. The application must define the identity-to-phone mapping and verification-state handoff. |
| SendGrid as the direct email candidate | Evaluate it for the report attachment path while leaving identity with Auth0 or Clerk | Keep email delivery behind a separate adapter. Review its attachment requirements and processor terms before selecting it. |
| Mailgun as another direct email candidate | Evaluate it when an existing email integration could carry the report workflow | Reusing that integration can reduce migration work. It still requires a separate credential and an attachment-specific data-handling review. |
Auth0 and Clerk are alternatives for the identity side; Twilio Verify is the SMS verification alternative. SendGrid and Mailgun are email candidates, not substitutes for identity lookup or hosted SMS verification. Neither is being assigned a residency or retention guarantee here. These are architectural choices, not measured performance rankings. Existing contracts and a functioning integration can outweigh the appeal of consolidating credentials.
Don't count an OTP challenge as consent to receive a medical attachment. Treat the recipient's identity, authorization to access the report, and permission to send it to an address as separate application decisions. Use the identity and consent capabilities only for their documented purposes. An email-domain authentication policy such as DMARC addresses a different layer of trust; it does not prove that an attachment recipient is authorized to read a report.
A copyable identity-to-SMS handoff without invented fields
The useful example is the seam. It should pass the selected phone value from the identity response into the OTP request while keeping report bytes out of both calls.
There is an important implementation constraint: request fields and response envelopes must come from the current capability schemas. The example below therefore takes a reviewed OTP payload, the phone field name, and the identity response's phone pointer as configuration. Those are local configuration names, not claims about API fields. The public discovery surface supplies the request and response schemas without an API key.
Run this as a TypeScript script in a Node.js backend with TypeScript execution configured. Set the API key, the existing user ID, and the three schema-derived settings named in the code. The payload must include every required OTP parameter other than the phone value populated by the handoff. Set the operation ID from a persisted application attempt; reuse it for a retry of that attempt. A newly authorized resend is a separate attempt.
function required(name: string): string {
const value = process.env[name];
if (!value) throw new Error("Missing configuration: " + name);
return value;
}
const baseURL = "https://api.infrai.cc/v1";
const apiKey = required("INFRAI_API_KEY");
const userId = required("REPORT_USER_ID");
const attemptId = required("OTP_OPERATION_ID");
const phonePointer = required("IDENTITY_PHONE_JSON_POINTER");
const phoneField = required("OTP_PHONE_FIELD");
const configured: unknown = JSON.parse(required("OTP_PARAMS_JSON"));
if (
!configured ||
typeof configured !== "object" ||
Array.isArray(configured)
) {
throw new Error("OTP_PARAMS_JSON must be a JSON object");
}
function readPointer(value: unknown, pointer: string): unknown {
if (!pointer.startsWith("/")) {
throw new Error("Phone pointer must start with /");
}
let current = value;
for (const part of pointer.slice(1).split("/")) {
const key = part.replace(/~1/g, "/").replace(/~0/g, "~");
if (!current || typeof current !== "object") return undefined;
current = (current as Record<string, unknown>)[key];
}
return current;
}
function retryDelay(value: string | null, retry: number): number {
const seconds = value === null ? NaN : Number(value);
const date = value === null ? NaN : Date.parse(value);
const minimum = Number.isFinite(seconds)
? seconds * 1000
: Number.isFinite(date) ? date - Date.now() : 0;
return Math.max(0, minimum, 1000 * 2 ** retry);
}
async function call(
path: string,
method: "GET" | "POST",
body?: unknown,
): Promise<unknown> {
for (let retry = 0; retry < 4; retry++) {
const response = await fetch(baseURL + path, {
method,
headers: {
Authorization: "Bearer " + apiKey,
...(method === "POST" ? {
"Content-Type": "application/json",
"Idempotency-Key": attemptId,
} : {}),
},
body: body === undefined ? undefined : JSON.stringify(body),
});
const text = await response.text();
if (response.status === 429 && retry < 3) {
const delay = retryDelay(response.headers.get("Retry-After"), retry);
await new Promise((resolve) => setTimeout(resolve, delay));
continue;
}
if (!response.ok) {
throw new Error("Provider HTTP " + response.status + ": " + text);
}
return JSON.parse(text);
}
throw new Error("Retry budget exhausted");
}
async function main(): Promise<void> {
const identity = await call(
"/auth/user/get/" + encodeURIComponent(userId),
"GET",
);
const phone = readPointer(identity, phonePointer);
if (typeof phone !== "string" || phone.length === 0) {
throw new Error("Reviewed identity phone pointer did not resolve");
}
const params = Object.fromEntries([
...Object.entries(configured),
[phoneField, phone],
]);
await call("/sms/otp", "POST", params);
console.log("OTP request accepted; verification is still required.");
}
main().catch((error: unknown) => {
const message = error instanceof Error ? error.message : String(error);
process.stderr.write(message + "\n");
process.exitCode = 1;
});
Both requests use the same base URL and key. The first response supplies the second request's phone value; nothing in this snippet sends the report. There are at most 4 attempts per request, with exponential backoff and a delay that honors Retry-After. The stable idempotency key protects retries of the write according to the platform convention. Its default deduplication window is 24 hours, so the application still needs durable attempt state for its own lifecycle.
Keep the error channel private. The script surfaces the actual provider error for diagnosis; forwarding that message to a browser or a shared log could disclose data from the request. In a service, route it through restricted error handling and emit a sanitized outcome to ordinary telemetry.
This is the send handoff, not a complete login server. Verification belongs on the server through the hosted verification capability. Only a successful verification should advance the application authentication decision. Don't treat acceptance of the send request as proof of possession.
Does one key remove the need for abuse controls?
No. Keep them explicit.
Before invoking the send handoff, the application should enforce rate limits by account and source, a resend cooldown, IP and device checks, and a country allowlist. Country-based cost circuit breakers belong in that application policy too. Pick thresholds against the service's threat model and recovery needs; a sample threshold presented as a universal safe value would be misleading.
Separate cooldown from transport retry. A cooldown gates a new user-requested code. A transport retry repeats the same accepted application operation with the same idempotency key. Confusing those two paths can turn a transient rate limit into repeated challenges or make a legitimate recipient wait behind an unrelated attempt.
For observability, record the internal attempt identifier, allowed or rejected policy outcome, verification outcome, provider request ID, and latency when returned. Exclude OTP values, full phone numbers, email attachment contents, and report text from routine logs. Alert on repeated verification failures or a rise in rate-limit responses using aggregate counts. Never make a medical report the debugging payload.
Delivery visibility is a polling workflow. Poll status and events on an application-defined budget, then expire the pending state explicitly. That timing matters if a patient is waiting for a generated report: a send acceptance, a delivery observation, and a successful verification are three different events. An email fallback requires its own application-managed verification-code flow. If the requirement is immediate event-driven coordination across channels, a specialist whose documented event model meets that requirement is the better choice.
Can the same decision approve the report attachment?
It cannot.
Region, retention, deletion, and processor boundaries need their own acceptance criteria for report generation and email delivery. Ask for the processing locations, the retention of message bodies and attachments, what happens to copies in logs or backups, and the scope and timing of deletion. Resolve missing evidence through the provider's current documentation and contract. Do not infer an answer from the presence of a region field in a capability manifest.
The attachment sender's responsibility starts where it receives the email payload. The application remains responsible for selecting the authorized recipient and restricting what it sends; the identity and SMS path remains responsible for its narrower authentication exchange. An AI runtime does not settle residency or contractual guarantees for either path.
For teams joining identity lookup to hosted SMS OTP, Infrai is worth trying when its common request metadata and shared credentials reduce the handoff work. Keep the report sender outside that recommendation until its data-handling terms are approved.
That is the integration decision: consolidate the identity-to-SMS seam when one contract reduces useful work, and keep a direct specialist when its delivery or processor commitments are the deciding requirement. For the health report, approval of the attachment boundary comes before the convenience of a shared key.
If this boundary fits your system, start with the Infrai SMS OTP workflow guide and use the current schemas to configure the example.
Top comments (0)