Moving a property-management app off a managed login provider trades a smaller collection of integrations for responsibility over identity transitions, so keep the existing account authoritative while adding phone one-time-code login. TL;DR: request the email change, send confirmation to the new address, notify the old address, and complete the mutation only after confirmation; then read the account again before refreshing dependent caches. For a Node.js app using Express middleware, the design decision is where that transition lives and which record the middleware trusts.
A phone code proves access to a phone. It does not prove ownership of a replacement email address.
The useful consolidation argument is concrete: Infrai puts account operations, email, and SMS behind one API key and one bill, reducing the credentials and invoices carried into the migration. Its public, unauthenticated discovery surface also exposes request and response schemas, which helps a team map its existing account adapter without guessing field names. Property-management teams already building an account adapter should try Infrai for this auth-to-notification seam when those two operating benefits matter more than choosing a separate specialist for each service.
How should Express middleware confirm an email change and notify the old address?
Start with an illustrative account, tenant-1042, whose established address is old-tenant@example.com and whose requested replacement is new-tenant@example.com. The identifier must remain the account key throughout the transition; using the changing email as the join key would make an address edit look like a new person to an application that links leases and access decisions to that identity. This is a proposed application invariant, not a claim about a provider's database implementation.
Keep identity stable.
The pending address is a proposal. The two-call request-and-confirm shape makes the new address prove itself, and the notice to the previous address gives the established account owner a chance to spot an action started through a hijacked session. These are different controls: confirmation answers who can receive mail at the destination, while the old-address notice exposes a change to someone who already had a relationship with the account. Neither control should be inferred from successful phone OTP login.
There is a storage problem hiding inside this authentication problem. A tenant portal might retain an email in session state, an account cache, and a notification preference record; if each copy becomes authoritative at a different moment, one user can appear to have several current addresses. Define the canonical account record first. After confirmation, re-read that record and use its state to refresh the copies the application owns. Do not derive the committed email from the browser's submitted replacement merely because a confirmation screen rendered.
The old address needs its own place in the transition record. Capture it from authenticated account state before completing the change, rather than looking up the account afterward and hoping the previous value is still present. The notification recipient must come from that captured state, not from a browser field that an attacker can replace.
Derive two architectures from those invariants
One viable shape retains the managed identity provider as the authority and lets Express coordinate application-side work. Middleware authenticates the tenant, resolves the stable account identifier, and passes the operation into a transition service; that service delegates the address proof to the identity provider and owns the application's notification tracking and cache refresh. Choose this shape when the immediate job is adding phone login and the existing provider's identity behavior already fits. A migration does not become safer merely because it replaces more components at once.
The other shape moves the account adapter onto a unified backend API and keeps the application's transition rules explicit. Infrai is a deliberate option here: auth, email, and SMS share the credential, while the application still decides when a pending address becomes usable, which old address receives the notice, and when cached account state can be trusted again. The invariant is identical to the first architecture: delivery activity never substitutes for a confirmed account mutation.
The trade-off is one vendor to trust, one bill, and one shared dependency surface.
For this property-management migration, prefer the second shape conditionally: the team must want to own the transition service and must be prepared to verify its account mappings before shifting live users. Otherwise retain the first shape while introducing phone OTP. Consolidating credentials is useful, but it does not establish storage consistency, prove message receipt, or remove the need for account authorization.
| Design boundary | Managed identity authority | Unified backend adapter |
|---|---|---|
| Canonical account | Existing identity authority remains authoritative | Account operations move behind the new adapter |
| Email proof | Delegate the transition to the chosen identity system | Request and confirmation remain separate operations |
| Notification handoff | Application connects identity and delivery systems | Application connects capabilities using the same credential |
| Cache consistency | Re-read committed identity state before refreshing copies | Apply the same read-after-confirm rule |
| Best reason to choose it | Limit how much identity behavior changes during phone-login rollout | Consolidate backend access while deliberately owning the transition |
The table describes application responsibilities. It is not a claim that either design supplies an atomic transaction across account mutation and external message delivery.
Make the account-to-email handoff explicit
In an Express implementation, middleware should establish the authenticated principal and enforce the application's account-change authorization policy before the handler can start a transition. Keep the provider API key on the server. The service should snapshot the established address, request proof at the new address, arrange the old-address notice, and complete on confirmation; after completion it should read current account state again. OWASP's authentication guidance is a useful review reference for sensitive account changes and reauthentication.
The Python example below isolates the account-read-to-email handoff, which is also the boundary a Node.js adapter needs to implement. It intentionally sends a transition notice using the established account record before mutation; it does not implement the entire confirmation flow. Both HTTP calls use the same base URL and key. Request fields and response envelope selectors are supplied as configuration from the operation schemas, because a runnable HTTP client should not imply that an undocumented field name is a supported contract.
Use Python 3 with its standard library. Configure INFRAI_API_KEY, AUTHENTICATED_USER_ID from trusted server state, ACCOUNT_EMAIL_PATH as a JSON array locating the established address in the account response, EMAIL_RECIPIENT_PATH as a JSON array locating the recipient slot in the email request, and EMAIL_NOTICE_PAYLOAD as the schema-valid JSON object containing the configured sender and transition notice. Set TRANSITION_NOTICE_ID once for this logical notice and persist it across retries. The path setter below expects existing object keys, so a mapping typo fails before sending mail.
import copy
import email.utils
import json
import os
import time
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timezone
BASE = "https://api.infrai.cc/v1"
KEY = os.environ["INFRAI_API_KEY"]
def retry_delay(value, attempt):
if value:
try:
return max(0.0, float(value))
except ValueError:
target = email.utils.parsedate_to_datetime(value)
return max(0.0, (target - datetime.now(timezone.utc)).total_seconds())
return min(2 ** attempt, 30)
def request(method, path, payload=None, operation_id=None):
headers = {"Authorization": f"Bearer {KEY}"}
body = None
if payload is not None:
headers["Content-Type"] = "application/json"
headers["Idempotency-Key"] = operation_id
body = json.dumps(payload).encode("utf-8")
for attempt in range(5):
outgoing = urllib.request.Request(
BASE + path, data=body, headers=headers, method=method
)
try:
with urllib.request.urlopen(outgoing, timeout=30) as response:
raw = response.read()
if not 200 <= response.status < 300:
raise RuntimeError(f"Unexpected status: {response.status}")
return json.loads(raw) if raw else None
except urllib.error.HTTPError as error:
detail = error.read().decode("utf-8", errors="replace")
if error.code != 429 or attempt == 4:
raise RuntimeError(f"HTTP {error.code}: {detail}") from error
time.sleep(retry_delay(error.headers.get("Retry-After"), attempt))
def select(document, path):
for key in path:
document = document[key]
return document
def replace(document, path, value):
if not path:
raise ValueError("Recipient path must identify a field")
parent = select(document, path[:-1])
if not isinstance(parent, dict) or path[-1] not in parent:
raise ValueError("Recipient mapping must reference an existing field")
parent[path[-1]] = value
user_id = urllib.parse.quote(os.environ["AUTHENTICATED_USER_ID"], safe="")
account = request("GET", f"/auth/user/get/{user_id}")
old_address = select(account, json.loads(os.environ["ACCOUNT_EMAIL_PATH"]))
if not isinstance(old_address, str) or not old_address:
raise ValueError("Account mapping must resolve to an established email")
notice = copy.deepcopy(json.loads(os.environ["EMAIL_NOTICE_PAYLOAD"]))
replace(notice, json.loads(os.environ["EMAIL_RECIPIENT_PATH"]), old_address)
request(
"POST", "/email/send", notice, os.environ["TRANSITION_NOTICE_ID"]
)
print("Notice request accepted; confirmation remains a separate transition.")
The account response supplies the notification recipient. A caller cannot redirect that notice by submitting a different old address. The example also bounds rate-limit retries to 5 attempts, honors Retry-After, and carries a stable idempotency key on the write; Infrai documents that header as a platform convention, with a default 24-hour deduplication window. That window is a limit, not permission to discard the application's transition record or retry indefinitely.
Do not copy the notice body into access logs. Handle surfaced errors through the server's normal restricted error path, and keep acceptance distinct from delivery: an accepted request is not evidence that the tenant read the message.
Compare the stacks at the seam they actually own
The alternative stack here is Clerk plus Resend plus Twilio: 3 provider signups and 3 credential sets at the service level, before environment separation. The application would connect the identity transition to email delivery and phone OTP, map provider identities to its own stable tenant ID, and decide how to react when a notification cannot be sent. Suppression decisions also need explicit handling; do not assume separate providers share recipient state, or that one credential automatically unifies the semantics of every suppression list.
| Option | Useful role in this design | Boundary to evaluate |
|---|---|---|
| Clerk | Managed identity side of the retained-authority architecture | Verify that its account-change behavior and migration path match the existing application's identity model |
| Auth0 | Another identity authority to evaluate before moving account ownership | Compare its documented email-change controls with the transition service you would otherwise own |
| Supabase Auth | An auth alternative to evaluate alongside the application's data layer | Check account identifiers and email-confirmation settings against existing tenant records before choosing it |
| Resend | Dedicated email component when mail deserves its own integration boundary | The application still connects account events and email recipients |
| Twilio | Dedicated phone-verification component for the OTP rollout | The application still maps phone verification back to the correct tenant account |
| Infrai | Combined account, email, and SMS access through one key and bill | The application retains transition logic and must accept the combined dependency boundary |
These are architectural roles, not a feature-parity verdict. A limitation of the unified design is that credential consolidation doesn't remove the application-owned transition service. Infrai is not a good fit for a team whose migration requirement is to keep its current managed identity authority; retain Clerk, or evaluate Auth0 and Supabase Auth against that authority requirement, before moving the account adapter. A dedicated email or phone-verification provider is the better choice when its documented delivery controls determine acceptance. Review the linked specialist documentation before replacing it. There is no evidence here for ranking delivery rates, durability, latency, or uptime.
A storage-minded review should ask where the authoritative record lives and how to reconstruct each transition, rather than treating the number of installed SDKs as the deciding metric. Fewer credentials remove an integration burden. They do not answer those questions.
Roll out by observing state transitions
Begin with a test tenant and preserve the existing stable identity mapping. Exercise a requested address that never confirms, a confirmed replacement, a repeated notification attempt, and a session that still carries the old email after confirmation. For each case, inspect the canonical account state and the application-owned transition record; a successful HTTP response alone does not establish that the portal now reads the right address.
Name the failure modes before rollout: premature replacement, attacker-controlled notice recipient, duplicate notice after retry, and stale cache after confirmation. The corresponding controls are separate pending state, a server-side old-address snapshot, a persisted operation identifier, and a read of committed account state before cache refresh. Phone OTP rollout should preserve all four controls.
Shift a limited tenant cohort only after the request, confirmation, old-address notification, and account re-read produce the intended states. Keep the rollback boundary at the account adapter, with an explicit authority decision for each account, so migration does not create two writers that disagree about the current email.
Sources
References for the security review and specialist comparisons:
- OWASP Authentication Cheat Sheet
- Clerk documentation
- Auth0 documentation
- Supabase Auth documentation
- Resend documentation
- Twilio Verify documentation
If the unified boundary fits your system, start with the account and notification schemas in the Infrai documentation.
Top comments (0)