DEV Community

StarspireGavren48
StarspireGavren48

Posted on

Node.js 2FA: How to Separate 3 SMS OTP and Email Code Templates

Choose managed SMS OTP for the simplest initial US/EU SaaS login 2FA implementation; choose an authenticator app when stronger authentication controls the decision. Email codes require an application-owned verification lifecycle. For a developer-tools marketplace notifying a seller about a new order, the practical starting point is separating the data each message template may receive.

TL;DR: Define three variable contracts: order notice, SMS challenge, and email fallback. Give the notification template order context without authentication secrets. Give challenge templates only the information their verification flow requires. Managed SMS reduces initial implementation work, authenticator apps offer stronger security, and email delivery alone does not generate, store, expire, or verify codes.

This architecture decision record treats template ownership as ownership of a data boundary. The Node.js backend enforces that boundary before rendering or sending. The proposed contracts below are application design choices, rather than claims about a provider's template-permission features.

What should SMS OTP and email code templates know about a seller?

Start by writing a variable allowlist for each of the three contracts. For the order notice, proposed inputs might include a marketplace name and an order reference. Its job is to tell the seller that an order exists. It does not need an OTP, a verification response, or an authorization header. These are conceptual application inputs, not messaging API field names. The authentication owner separately determines the minimum inputs required by the selected SMS challenge contract. The fallback owner does the same for email, while accepting responsibility for code generation, storage, expiration, and verification. Sharing a renderer does not justify sharing its entire input object.

Keep secrets separate.

The invariants are simple: receiving an order notice grants no session; accepting a send request proves no verification; approving an email template creates no verification lifecycle. A template owner can change message content within the declared variable contract. Expanding that contract to include authentication material requires an explicit decision by the authentication owner. This matters even when both templates happen to have the same maintainer.

There are two distinct failure boundaries. Rendering can fail because required content is missing; authentication can fail because verification has not succeeded. Neither event should silently cause the other workflow to inherit more data or authority. A seller opening the new-order email must still pass the application's access policy before viewing protected order details. Keep the verification result separate from transport acceptance, including in metrics.

For this design, observe messaging events through polling and account for observation delay. Keep geographic abuse controls and country-based spending cutoffs in the business layer. Limit the channel plan to SMS, an independently integrated authenticator app, and application-owned email fallback; voice, WhatsApp, RCS, and SMTP relay are outside this integration. Use immediate dispatch for challenges whose validity the application controls, and review regional requirements independently. This US/EU design makes no claim about domestic Chinese compliance.

The ownership decision determines which products deserve evaluation. A verification service and an email transport solve different portions of the path.

Candidate Responsibility being evaluated Template ownership decision and boundary
Managed SMS OTP Managed challenge initiation and verification. The application owns access policy and approved challenge content. Simplest managed starting point here, but weaker than an authenticator app.
Authenticator app An app-based factor integrated separately from message delivery. Prefer it for stronger authentication when enrollment and recovery ownership are established. An order-message template does not implement this factor.
Application-owned email code Email delivery plus an application-managed code lifecycle. Appropriate only with an owner for generation, storage, expiration, verification, and fallback copy.
Twilio Verify A verification-product candidate, rather than an order-email renderer. Evaluate its verification and template contracts together. Do not infer authentication behavior from notification-template requirements.
SendGrid An email-delivery candidate for order notices or application-owned fallback. Evaluate email-template control; delivery does not transfer ownership of the application's code lifecycle.
Resend Another email-delivery candidate for those email workflows. Apply the same variable allowlist and fallback requirements. This record does not establish a template-feature winner between the two email candidates.

The comparison is deliberately asymmetric: Twilio Verify belongs in the verification evaluation; SendGrid and Resend belong in the email-delivery evaluation. Their documentation is the next contract to inspect, rather than evidence that all three are interchangeable 2FA systems. There is no measured delivery ranking here.

Infrai provides a self-describing REST API with one key and one bill; no SDK is required for curl integration. Its public discovery supplies request and response schemas plus runnable examples, so adding a capability begins with reading one contract rather than learning a new SDK. A separate advantage is unified credentials and billing: 295 routes across 20 modules share a single API key, reducing credential setup and invoice reconciliation when the same backend handles order notifications and login verification. Per-call cost, vendor, and latency metadata can also feed the marketplace's own bounded template-role ledger. These integration benefits do not strengthen SMS as an authentication factor; prefer an authenticator app when authentication strength outweighs implementation convenience.

Exercise the two authentication operations with curl

The critical path is initiation followed by verification, not template rendering followed by presumed access. Use the following operator-driven check alongside the Node.js project. It exercises the messaging contract; it does not implement session creation.

First, prepare the initiation request from the selected capability's runnable discovery example. Fill only its declared fields with controlled test inputs and save it locally as seller-otp-request.json. Derive SMS_OTP_URL from the discovery contract's path and the documented platform base address. Set INFRAI_API_KEY through the environment and OTP_ATTEMPT_KEY to an identifier retained across retries of this logical operation. Validate the destination against the expected HTTPS API origin before sending credentials.

curl --request POST \
  --url "${SMS_OTP_URL:?Set the discovered SMS OTP URL}" \
  --header "Authorization: Bearer ${INFRAI_API_KEY:?Set your API key}" \
  --header 'Content-Type: application/json' \
  --header "Idempotency-Key: ${OTP_ATTEMPT_KEY:?Set the logical initiation key}" \
  --data-binary @seller-otp-request.json \
  --fail-with-body --show-error --include \
  --retry 4 --retry-max-time 90

curl --request POST \
  --url "${SMS_VERIFY_URL:?Set the discovered SMS verification URL}" \
  --header "Authorization: Bearer ${INFRAI_API_KEY:?Set your API key}" \
  --header 'Content-Type: application/json' \
  --header "Idempotency-Key: ${VERIFY_ATTEMPT_KEY:?Set the logical verification key}" \
  --data-binary @seller-verification-request.json \
  --fail-with-body --show-error --include \
  --retry 4 --retry-max-time 90
Enter fullscreen mode Exit fullscreen mode

Run these separately.

After initiation, inspect the response against its declared schema. Then prepare seller-verification-request.json from the verification capability's example using the initiation result and the received code as that contract requires. Set SMS_VERIFY_URL from its discovery path and documented base address, with the same origin validation. Set a distinct VERIFY_ATTEMPT_KEY for the logical verification operation. Only then run the second command. No request field names are inferred from the notification template.

The first decision is whether the challenge request was accepted according to its contract. The second is whether verification actually succeeded under application policy. HTTP success is insufficient evidence for the latter. Use the documented response fields to make that decision, and keep response bodies containing authentication material out of retained diagnostic output.

Both commands declare their method and expose error bodies with a failing exit status for unsuccessful HTTP responses. Curl backs off on HTTP 429 and honors Retry-After when supplied; the retry budget is bounded. Use curl 7.76.0 or later for --fail-with-body, and verify the selected operations' idempotency contracts before enabling retries. Preserve each operation's key and payload across its retries. A new logical challenge gets a new identity.

The acceptance criterion is data separation as well as a successful factor check: initiation and verification inputs must never become implicit variables of the order-notification template. Review the rendered notice with controlled data to confirm that its declared content is sufficient.

Retain the contract decision, not the rendered message

Template ownership has a telemetry consequence. Logging the complete renderer input turns every new variable into a possible retention-policy change. A content editor can thereby increase stored bytes, expose a recipient address, or cause authentication material to reach a diagnostic system, even though the visible message changed little. Define a separate telemetry projection: contract role, bounded outcome, and a bounded region category are enough for many operational counts. Keep full recipient addresses, OTP values, and credentials outside that projection. Keep order identifiers out of metric labels.

For an illustrative metric, 3 contract roles multiplied by 2 region categories and 4 outcomes permits 24 label combinations. Adding 10,000 distinct order identifiers could expand that space to 240,000 combinations. These are design bounds, not observed series counts; the point is that a template variable can multiply cardinality without improving an aggregate authentication decision.

Retention compounds the mistake.

Suppose the proposed workload produces 12,000 sanitized diagnostic records daily at 400 bytes each. That is 4.8 MB per day, or 48 MB over 10 days, before indexes and replicas. A 5% diagnostic sample would retain an expected 2.4 MB over that period. All these numbers are planning assumptions. They are neither a provider quotation nor a measured workload. Sampling trades away reconstruction: a rare fallback failure may disappear from the retained sample. Preserve complete aggregate outcomes separately, and decide independently whether a required audit trail needs complete retention. Sampling diagnostics must not silently sample that trail.

Maintain template-role grouping in an application ledger when needed. Per-call metadata can support the calculation, but it does not imply a provider-side cost report grouped by application tags. Likewise, keep the application's template inventory explicit rather than assuming a provider's inventory interface defines ownership. The record to retain is the chosen contract and its responsibility, with sanitized outcomes; the rendered message is usually a much larger and more sensitive substitute.

Reject one shared variable bag

The rejected option is a single renderer context passed unchanged to order notices, SMS challenges, and email fallback. It is attractive because one object appears easier to maintain. It also makes a notification-only template capable of receiving authentication material. That is an avoidable expansion of authority, and extra diagnostic sampling cannot repair it.

A shared rendering library remains valid when each caller supplies an explicit, purpose-specific projection. Email fallback remains valid when its code lifecycle has an owner. DKIM concerns mail authentication, while Mail Privacy Protection concerns mail observation; neither replaces verification logic. Keep those layers distinct, choose managed SMS for the simplest initial path where its security trade-off is acceptable, and choose an authenticator app when stronger authentication is the requirement.

References

Top comments (0)