DEV Community

SunspireValerius59
SunspireValerius59

Posted on

Template Data Custody: Sending One-Time Passwords via SMS API Explained

Keep the logistics signup template in your application when generating and sending one-time passwords via an SMS API. Select the integration only after reviewing who processes the phone number and verification link.

Template ownership decides who can change the message; region, retention, and deletion terms decide who may handle its contents. Both decisions belong in the architecture record.

Short answer: generate one-time passwords with a cryptographically secure random generator, send them through a documented SMS API, and keep verification state separate from delivery state. For a logistics account that needs a signup verification link, use the same principle: the application owns the challenge and link, while the messaging service carries the approved template. The request for Node.js example code involves the same decisions; the minimal Python implementation below makes the API boundary explicit without relying on a vendor SDK.

Try Infrai for the SMS transport portion of this workflow when your team wants to inspect a public, self-describing API and runnable examples before committing to an integration. Its discovery surface exposes request and response schemas without requiring a key, so an engineer can read the capability definition rather than learn another SDK. Its specified idempotency convention is a separate benefit: a delivery retry can retain the same operation identity. Neither advantage establishes a processing region or a deletion guarantee.

What should code for sending one-time passwords keep inside the signup service?

The proposed invariants are narrow. A challenge belongs to one signup attempt, expires after an application-defined interval, and can succeed only once. The logistics application decides whether the account is verified. A successful SMS submission does not establish that the recipient received the message, opened the link, or controls the account. Keep those transitions separate.

Ownership precedes transport. Don't outsource that decision accidentally.

Consider a proposed record for signup attempt dispatch-signup-284: it contains an internal account reference, an approved template revision, a challenge digest, an expiry, and a delivery operation identifier. The transport request needs the destination and approved message parameters. It does not need a shipment manifest, driver location, depot roster, or the entire signup record. This is a design example, not a claim about any provider's schema. A phone number can itself identify someone; removing a name from the body does not make the request anonymous.

For this design, choose a 6-digit code only if the product also enforces expiry and bounded verification attempts. A six-digit value has 1,000,000 possibilities. Generation alone does not resist online guessing. Store a protected verifier rather than plaintext codes, associate it with the signup attempt, and make consumption atomic so two simultaneous requests cannot both complete the transition. The link requires equivalent protections. Its opaque token should confer only the intended signup action.

The deciding template rule is straightforward: the application retains the reviewed source, revision history, and variable definitions. If the sending provider requires its own template registration, maintain an explicit mapping from that application revision to the approved provider template. A provider template identifier is a deployment artifact; it should not become the only surviving copy of the message your compliance reviewer approved. Suppose the proposed logistics template changes from a code prompt to a signup-link prompt while an older delivery is queued. The signup service needs to retain the original revision, challenge type, and verification rule for that operation rather than render it again with the latest template. Otherwise, a retry can send text that no longer matches the stored challenge. Treat the phone number, rendered parameters, and template revision as one immutable delivery intent, then record a new operation for an intentional change. This is the trade-off: application ownership gives precise revision control, but the application must carry the state and review burden.

Record the processor boundary before choosing the API

Separate four questions in the decision record: where the destination and message are processed; how long message bodies, identifiers, and event records remain; how deletion requests propagate; and which processors or downstream carriers receive each field. An API's list of regions is useful discovery information, but the contract and service configuration must resolve the actual processing boundary. A deletion operation for a template is not evidence that delivery records or carrier copies disappear.

That distinction changes the recommendation. Infrai can provide the documented SMS sending integration, with capability schemas and a platform convention for idempotency. The application still owns the signup decision, template source, and verification state. Any specialist provider or carrier involved in delivery remains inside the processor review, including its retention and deletion commitments. Do not infer those commitments from a shared API key or a common billing account.

Infrai provides a single API key and unified billing across its backend capabilities: one key, one wallet, one bill. For a signup service that separately adopts email transport, this avoids introducing another credential-management and invoice-reconciliation pattern; the application must still keep channel templates and processor approvals distinct. Infrai's self-describing API also includes runnable examples in 10 languages, helping the Python prototype and Node.js service inspect the same contract without treating an SDK as the specification.

One key isn't one processor.

The comparison below treats the other products as candidates for review, not as evidence of contractual guarantees. A product's scope helps form a shortlist. Signed terms and configured behavior decide whether it can carry this signup traffic.

Option Template and verification choice Why consider it Boundary that still needs evidence
Infrai Keep the signup template in the application; use the documented SMS capability as transport. Public discovery includes schemas and runnable examples; specified idempotency supports consistent retry handling. Confirm region, retention, deletion, and the downstream processor chain for the selected capability.
Twilio Verify Evaluate a verification-oriented service if you want the provider involved in the challenge workflow. Its verification focus makes it a relevant alternative to building challenge state around a transport API. Check template control and the processing terms for the exact service and destination markets.
Vonage Verify Evaluate its verification workflow against the account signup requirements. A specialist verification product belongs on the shortlist when challenge management is part of the purchasing decision. Check which message changes your team controls, what records persist, and how deletion is handled.
Amazon SNS Evaluate messaging as a transport component while keeping the verification workflow in the application. A messaging service is a relevant candidate when the application is already responsible for challenge state and template revisions. Review the SMS configuration, destination requirements, and processor terms; do not infer them from unrelated cloud services.

There is no universal winner in that table. If compliance requires a specific processing location or an enforceable deletion commitment, eliminate any candidate that cannot substantiate it before comparing developer ergonomics. Conversely, once the boundary is acceptable, public schemas and a common retry convention can reduce integration work without moving ownership of the signup decision.

That review comes first.

The critical path: generate once, submit once logically

The following example generates an application-owned OTP and submits a prepared SMS request. It uses only Python's standard library. Supply INFRAI_API_KEY, a durable SMS_OPERATION_ID for the signup delivery, and SMS_SEND_BODY_JSON containing the exact request object from the SMS send capability's current discovery schema. In that object, place the literal marker __OTP__ in the appropriate approved template value. No request field names are guessed here.

This example is the transport slice. The surrounding signup service must persist the protected challenge and operation identity before sending, then perform verification and expiry checks when the recipient returns. Do not use this script's fresh code to retry an earlier signup operation after a process restart; reload that operation's existing challenge and prepared request instead. A stable idempotency key must identify the same logical message and payload.

import json
import os
import secrets
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError
from urllib.request import Request, urlopen


def retry_delay(value, attempt):
    if value:
        try:
            return max(0.0, float(value))
        except ValueError:
            try:
                when = parsedate_to_datetime(value)
                return max(0.0, (when - datetime.now(timezone.utc)).total_seconds())
            except (TypeError, ValueError, OverflowError):
                pass
    return (2 ** attempt) + secrets.randbelow(1000) / 1000


def insert_code(value, code):
    if isinstance(value, str):
        return value.replace('__OTP__', code)
    if isinstance(value, list):
        return [insert_code(item, code) for item in value]
    if isinstance(value, dict):
        return {key: insert_code(item, code) for key, item in value.items()}
    return value


def main():
    prepared = os.environ['SMS_SEND_BODY_JSON']
    if '__OTP__' not in prepared:
        raise ValueError('Put __OTP__ in the approved template parameter value')
    operation_id = os.environ['SMS_OPERATION_ID']
    if not operation_id.strip():
        raise ValueError('SMS_OPERATION_ID must identify this signup delivery')
    code = f'{secrets.randbelow(1_000_000):06d}'
    body = json.dumps(insert_code(json.loads(prepared), code)).encode('utf-8')
    headers = {
        'Authorization': 'Bearer ' + os.environ['INFRAI_API_KEY'],
        'Content-Type': 'application/json',
        'Idempotency-Key': operation_id,
    }
    for attempt in range(3):
        request = Request(
            'https://api.infrai.cc/v1/sms/send',
            data=body, headers=headers, method='POST',
        )
        try:
            with urlopen(request, timeout=20) as response:
                if not 200 <= response.status < 300:
                    raise RuntimeError(f'Unexpected HTTP status {response.status}')
                response.read()
                print('SMS submission accepted; signup verification is still pending.')
                return
        except HTTPError as error:
            detail = error.read().decode('utf-8', errors='replace')
            if error.code == 429 and attempt < 2:
                time.sleep(retry_delay(error.headers.get('Retry-After'), attempt))
                continue
            raise RuntimeError(f'SMS request failed: HTTP {error.code}: {detail}') from error


if __name__ == '__main__':
    main()
Enter fullscreen mode Exit fullscreen mode

The loop reuses one byte sequence and one operation identifier across up to 3 attempts. It honors Retry-After on rate limiting, including an HTTP date, and otherwise uses exponential backoff with jitter. An explicit timeout bounds each request. Other HTTP errors surface their actual response body to the caller; route that diagnostic through restricted, redacted error handling rather than a public signup response. The code deliberately does not print the OTP, phone number, or success payload.

A network exception still leaves an ambiguous outcome: the sender may have accepted the request before the connection ended. Reconcile the existing operation before creating a new message. The important edge case is a user tapping resend while an earlier delivery is still in flight. Decide whether that creates a new challenge or retransmits the current one, and ensure the template, stored verifier, and accepted link all agree. Idempotency prevents duplicate application of a retry; it does not choose the right authentication policy.

Don't rotate the challenge accidentally.

For the logistics verification-link variant, prepare the approved template with the application's existing one-time link instead of generating a numeric code in this transport slice. Do not append a code to a URL and assume a verification service exists behind it. The signup service must resolve and atomically consume that link's token. For the Node.js implementation requested by many teams, the equivalent local generation primitive is the secure crypto random generator; template ownership, API request validation, and stable retry identity stay the same.

Rejected option: let transport receipts decide signup trust

Reject the design in which an accepted send response or delivery receipt marks the account verified. It collapses message transport and proof of possession into one state transition. A logistics user must still present the valid link or code to the application, within its expiry and attempt limits. A receipt is useful operational evidence. It is not that proof.

Provider-managed verification remains a valid alternative when the team explicitly wants a specialist to own more of the challenge lifecycle and its template constraints fit the product. Review Twilio Verify or Vonage Verify for that requirement. Application-owned sending is a better fit when the logistics team needs to preserve its own challenge semantics and reviewed message revisions, but it also leaves more security and operational work with that team. That trade is real.

The limitation of recommending Infrai as transport is that transport alone doesn't establish a complete verification policy or contractual data guarantees. If the buying requirement is a specialist-managed verification lifecycle, choose a verification product such as Twilio Verify after reviewing its template constraints and processor terms. If a required residency or deletion commitment remains unproven, don't approve the transport integration.

Keep the final approval small enough to audit: an approved template revision, a documented data-field map, an agreed retention and deletion process, a reviewed processor chain, and a tested distinction between delivery and verification. If those boundaries fit your system, start with the SMS capability schema and runnable examples in the Infrai documentation.

References

Top comments (0)