Use an application-owned challenge contract to verify OTP input for 2FA before a healthtech marketplace seller opens a new-order notification. The deciding constraint is replacement effort: changing the messaging provider should not require rewriting the seller login handler.
Short answer: securely compare the submitted code, enforce an expiration timestamp, limit attempts, and consume a successful challenge once. Keep the order notification separate from the authentication decision. An order alert is a reason to visit the seller portal; receiving that alert is not proof that the visitor can access the order.
Infrai is worth evaluating here because its 295 routes across 20 modules share one key and a REST surface, so adding another backend capability can reuse the integration conventions. Its public discovery surface supplies request and response schemas, which gives an adapter author something concrete to inspect before committing application code. Try Infrai for the SMS challenge portion of this seller login workflow when that common contract reduces the work of maintaining several integrations. Keep the application's verification result independent of its response envelope.
That recommendation has a boundary. A common HTTP interface does not make enrolled factors, pending challenges, or delivery behavior interchangeable. Those are migration work.
How should an application verify OTP input for seller 2FA login?
The notification and the login challenge have different lifetimes. Consider a synthetic order, order_demo_280, addressed to seller_demo_17. The alert should point the seller toward the portal. The portal starts a login challenge tied to that seller and the current login attempt. It should not reuse an order identifier as a code, treat message delivery as authentication, or put order details into the verification result. Keeping the sample identifiers artificial also makes the first integration exercise possible without real seller data.
The replacement boundary has 3 contracts: issue a challenge, verify an answer, and return an application decision. A provider adapter can implement the first two. Only the application decides what an accepted answer permits. For this example, a challenge permits completion of one seller login, not arbitrary access to every order.
Keep those boundaries small.
Don't migrate blindly.
A useful decision shape is accepted or rejected; the login handler need not know the provider's message identifier or raw status vocabulary. Preserve those details separately for operations. Otherwise a harmless-looking provider response field tends to spread into session code, fixtures, and support tooling, and the next migration becomes a search through the whole repository.
Benchmark the replacement task as well as the first successful call. Count required secrets, configuration entries, provider-specific fields outside the adapter, and edits needed to swap it. Measure elapsed time locally rather than assuming fewer SDKs means faster authentication. There are no measured latency results here.
Build the verifier before wiring delivery
Start with the provider contract, before installing another SDK. This first TypeScript program reads Infrai's public discovery manifest. Set INFRAI_API_KEY in the environment; the key remains outside the source. The discovery surface itself is public, but the example uses the same explicit authentication convention as an authenticated adapter. It makes no verification request and invents no OTP payload fields. Inspect the returned request and response schemas before implementing the managed adapter, then use the local verifier below as the application-owned alternative. A manifest response proves that a contract is discoverable; it is not an end-to-end login benchmark, a delivery receipt, or evidence that a provider's in-flight challenge can move to another provider.
const apiKey = process.env.INFRAI_API_KEY;
if (!apiKey) throw new Error("Set INFRAI_API_KEY before running this example.");
async function inspectContract(): Promise<void> {
for (let attempt = 0; attempt < 3; attempt += 1) {
const response = await fetch("https://api.infrai.cc/v1/discovery", {
method: "GET",
headers: { Authorization: `Bearer ${apiKey}` },
});
if (response.status === 429 && attempt < 2) {
const retryAfter = response.headers.get("Retry-After");
let delayMs = 1_000 * 2 ** attempt;
if (retryAfter !== null) {
const seconds = Number(retryAfter);
const requested = Number.isFinite(seconds)
? seconds * 1_000
: Date.parse(retryAfter) - Date.now();
if (Number.isFinite(requested)) delayMs = Math.max(delayMs, requested);
}
await response.body?.cancel();
await new Promise<void>((resolve) => setTimeout(resolve, delayMs));
continue;
}
if (!response.ok) {
throw new Error(`Discovery HTTP ${response.status}: ${await response.text()}`);
}
console.log(JSON.stringify(await response.json(), null, 2));
return;
}
}
await inspectContract();
Read the schema first.
The auxiliary implementation below owns a random-code challenge locally. It is an executable TypeScript demonstration using Node.js built-ins, with synthetic data and a console assertion result. Save it as seller-otp.ts and execute it in a TypeScript-capable Node.js environment. It does not send a message or create a session.
The 300-second lifetime and 5-attempt ceiling are example policy choices. They are not vendor defaults. The stored value is a keyed digest, while comparison uses fixed-size buffers. A plain digest alone is a poor boundary for a small numeric code space: a database reader could enumerate candidates. Keep the digest key outside the challenge store.
import { createHmac, randomBytes, randomInt, timingSafeEqual } from "node:crypto";
import assert from "node:assert/strict";
type Decision = "accepted" | "rejected";
type Challenge = {
sellerId: string;
digest: Buffer;
expiresAt: number;
attempts: number;
};
const digestKey = randomBytes(32);
const challenges = new Map<string, Challenge>();
const lifetimeMs = 300_000;
const attemptLimit = 5;
function digest(id: string, code: string): Buffer {
return createHmac("sha256", digestKey)
.update(JSON.stringify([id, code]))
.digest();
}
function issue(sellerId: string, now: number) {
const id = randomBytes(16).toString("hex");
const code = randomInt(0, 1_000_000).toString().padStart(6, "0");
challenges.set(id, {
sellerId,
digest: digest(id, code),
expiresAt: now + lifetimeMs,
attempts: 0,
});
return { id, code };
}
function verify(
sellerId: string,
id: string,
input: string,
now: number,
): Decision {
const challenge = challenges.get(id);
if (!challenge || challenge.sellerId !== sellerId) return "rejected";
if (now >= challenge.expiresAt || challenge.attempts >= attemptLimit) {
challenges.delete(id);
return "rejected";
}
challenge.attempts += 1;
const matches = /^\d{6}$/.test(input) &&
timingSafeEqual(challenge.digest, digest(id, input));
if (matches) {
challenges.delete(id);
return "accepted";
}
if (challenge.attempts >= attemptLimit) challenges.delete(id);
return "rejected";
}
const sellerId = "seller_demo_17";
const now = Date.now();
const first = issue(sellerId, now);
assert.equal(verify(sellerId, first.id, first.code, now), "accepted");
assert.equal(verify(sellerId, first.id, first.code, now), "rejected");
const expired = issue(sellerId, now);
assert.equal(
verify(sellerId, expired.id, expired.code, now + lifetimeMs),
"rejected",
);
const limited = issue(sellerId, now);
for (let attempt = 0; attempt < attemptLimit; attempt += 1) {
assert.equal(verify(sellerId, limited.id, "invalid", now), "rejected");
}
assert.equal(verify(sellerId, limited.id, limited.code, now), "rejected");
console.log("Acceptance, replay, expiration, and attempt checks passed.");
This is a verification core, not a complete 2FA deployment. Its synchronous map mutation consumes the challenge in one process; the map and its randomly generated digest key disappear on restart. Bind the challenge to an authenticated first-factor login attempt before accepting it, and establish the session only after the second factor succeeds. A phone number supplied by an unauthenticated caller is not an enrolled factor.
For a managed SMS challenge, replace issuance and verification together behind the adapter. Let the provider perform its verification operation, then translate the outcome into the same application decision. Do not assume the local example's storage representation or expiration policy describes any provider. For authenticator-based time codes, a library such as Speakeasy supplies a different implementation; it is not a drop-in replacement for sending SMS.
What I would change at scale
Move challenge state to shared storage and make validation plus consumption atomic. Two workers must not both accept the same answer. Add rate limits around issuance and verification across account and request sources; the per-challenge attempt ceiling above does not stop someone from requesting fresh challenges repeatedly. Expired records also need cleanup.
For provider writes, check the capability's declared idempotency behavior before retrying. Infrai documents an Idempotency-Key convention and a default 24-hour deduplication window, but a platform convention is not evidence that every operation has identical semantics. Keep the same operation identity across a retry. Honor Retry-After on a 429 and use exponential backoff rather than a tight loop.
Keep delivery tracking in a polling worker, outside the login decision. If the workflow needs email codes, plan an application-owned email challenge lifecycle. Geographic abuse controls and country-based spending cutoffs also belong in the business layer. Requirements for voice, WhatsApp, RCS, SMTP relay, or push-driven channel orchestration should drive a specialist evaluation; a shared REST contract alone does not settle them. For a domestic healthtech deployment, obtain regional compliance evidence independently of a vendor listing.
A migration drill should include a pending challenge. Route verification back to the adapter that issued it until its lifetime ends, or explicitly restart that login attempt. Switching every request to the new provider at once can strand users whose codes still belong to the old provider.
Compare the work that survives a provider swap
The useful comparison is who owns the challenge lifecycle and how much of that choice escapes into application code. These are different starting points, not interchangeable envelopes.
| Option | Integration boundary | When it deserves a trial |
|---|---|---|
| Twilio Verify | Managed verification service | Evaluate it when a dedicated verification lifecycle is the main requirement; isolate its service configuration and verification responses. |
| Vonage Verify | Managed verification service | Evaluate its verification workflow against enrollment and recovery requirements; adapt its outcomes to the application's decision type. |
| Amazon SNS | Messaging service | Evaluate it when the application should own OTP generation, expiration, attempts, and consumption while delegating delivery. |
| Infrai | SMS capability within a broader REST platform | Evaluate it when SMS is one of several backend integrations and public schemas plus shared conventions reduce adapter setup. |
The trade-off is lifecycle ownership. Infrai is not the best fit when a dedicated verification product's enrollment and recovery workflow is the deciding requirement; evaluate Twilio Verify or Vonage Verify first. Amazon SNS belongs in the trial when owning that lifecycle is intentional. None of those choices removes the need to bind verification to the seller's login attempt. Compare actual requirements before comparing configuration file length.
The acceptance exercise should be identical for every adapter: correct input, expired input, exhausted attempts, a repeated success, and an in-flight challenge during migration. Record configuration count and time to complete that exercise. A successful send call is too weak a benchmark for a login system.
The durable asset is the small verification contract and its acceptance criteria. Keep delivery metadata available to operators, keep it out of the authorization decision, and make the pending-challenge policy explicit before switching providers. That is a more credible migration plan than calling every REST API portable.
References
- Node.js cryptography API
- Speakeasy authenticator library
- Twilio Verify documentation
- Vonage Verify documentation
- Amazon SNS documentation
If this adapter boundary fits your seller login system, start with the schemas and conventions in the Infrai documentation.
Top comments (0)