Email Management
Flow Summary
The current email module has three flows:
Set Email Flow
Step 1. Send OTPPOST /api/v2/auth/set-email/otp
Step 2. Verify and savePOST /api/v2/auth/set-email/verification
Replace Email Flow
Step 1. Send OTP (current)POST /api/v2/auth/reset-email/current-email/otp
Step 2. Verify (current)POST /api/v2/auth/reset-email/current-email/verification
Step 3. Send OTP (new)POST /api/v2/auth/reset-email/new-email/otp
Step 4. Verify (new)POST /api/v2/auth/reset-email/new-email/verification
Client-Verified Email Change Flow (Backend Only)
Step 1. Register the changePOST /api/v2/auth/email-change/request
Step 2. Attest verification and applyPOST /api/v2/auth/email-change/verification
In development environments, OTP for the set-email and reset-email flows is currently hardcoded to 123456.
All routes below should be treated as protected routes and sent with:
Authorization: Bearer <access_token>
The client-verified flow additionally requires the agent signature headers.
Set Email (For Users Without A Verified Email)
Use this when the user registered without a verified email, or has a stored email that is still unverified.
1. Send OTP
POST /api/v2/auth/set-email/otp
Request
{
"email": "user@example.com"
}
Success response
{
"status_code": 200,
"message": "OTP sent successfully",
"data": {
"set_email_session_id": "9b7f1b4d-7c75-4d14-bec8-0d03b0f809d6",
"expires_at": 300
}
}
Current rules
- If the user already has a stored email value, the submitted email must match that stored value after lowercase/trim normalization.
- If the user has no email yet, the service checks that the new email is not already used by another user.
- The OTP session remains valid for 5 minutes.
- The handler reuses the email-reset OTP message key for this step.
2. Verify OTP And Save Email
POST /api/v2/auth/set-email/verification
Request
{
"set_email_session_id": "9b7f1b4d-7c75-4d14-bec8-0d03b0f809d6",
"otp_code": "123456"
}
Success response
{
"status_code": 200,
"message": "Email reset successfully",
"data": {
"success": true,
"message": "Email address set and verified successfully."
}
}
Notes
- The OTP session purpose must be
set_email. - On success, the service updates
emailand setsis_email_verified = true. - The OTP session is deleted after a successful verification.
- The handler reuses the email-reset success message key even though this is the set-email flow.
Reset Email (Replace An Existing Email)
This is a 4-step flow.
1. Send OTP To Current Email
POST /api/v2/auth/reset-email/current-email/otp
Request
{
"email": "current@example.com"
}
Success response
{
"status_code": 200,
"message": "Email reset initiated successfully",
"data": {
"current_email_session_id": "f2b4a8f8-0f5f-4a8d-9b20-8f2a1f4f34c2",
"email": "current@example.com",
"expires_at": 300
}
}
Notes
- The submitted current email must match the logged-in user’s registered email after lowercase/trim normalization.
- The OTP session remains valid for 5 minutes.
- This step sends OTP through the email service, not SMS.
2. Verify Current Email OTP
POST /api/v2/auth/reset-email/current-email/verification
Request
{
"current_email_session_id": "f2b4a8f8-0f5f-4a8d-9b20-8f2a1f4f34c2",
"otp_code": "123456"
}
Success response
{
"status_code": 200,
"message": "Current email verified successfully",
"data": {
"success": true,
"message": "Current email verified successfully. You can now proceed to change email address.",
"new_email_session_id": "12dc8cb8-cdf5-4f1a-b5ec-c0fd7184bfe2"
}
}
Notes
- This consumes the OTP session from step 1.
- The service creates a
new_email_session_idthat unlocks step 3. - That intermediate reset session remains valid for 10 minutes.
3. Send OTP To New Email
POST /api/v2/auth/reset-email/new-email/otp
Request
{
"new_email": "new@example.com",
"new_email_session_id": "12dc8cb8-cdf5-4f1a-b5ec-c0fd7184bfe2"
}
Success response
{
"status_code": 200,
"message": "OTP sent successfully",
"data": {
"new_email_session_id": "12dc8cb8-cdf5-4f1a-b5ec-c0fd7184bfe2",
"expires_at": 300
}
}
Notes
- The
new_email_session_idmust come from step 2 and must belong to the current user. - The new email must not already exist.
- The OTP for the new email uses the same
new_email_session_idvalue as the OTP session UUID. - Resending is limited to once per minute for the same
new_email_session_id. When blocked, the response includesretry_after. - This step sends OTP through the email service.
4. Verify New Email OTP And Update
POST /api/v2/auth/reset-email/new-email/verification
Request
{
"new_email_session_id": "12dc8cb8-cdf5-4f1a-b5ec-c0fd7184bfe2",
"otp_code": "123456"
}
Success response
{
"status_code": 200,
"message": "Email reset successfully",
"data": {
"success": true,
"message": "Email address updated successfully."
}
}
Notes
- The OTP session purpose must be
reset_email. - If the user has a
cardholder_id, the service updates the cardholder email with the payment provider before saving the local email. - The service updates
emailin the local database, then deletes the OTP session.
Client-Verified Email Change (Backend To Backend)
Use this flow when your backend already verifies the user's new email address (for example through your own OTP or magic-link system) and you want the mobile API to accept that verification instead of running the 4-step reset-email flow.
Both endpoints are API v2 only. They are not available under /api/v1, and they do not use the key_version / salt / data encrypted envelope.
Trust model
| Factor | Carried in | Proves |
|---|---|---|
| End-user session | Authorization: Bearer <access_token> | Who the user is, and which agent they belong to |
| Agent signature | X-Agent-ID, X-Timestamp, X-Nonce, X-Signature | The call came from that agent's backend and the body was not tampered with |
Both factors are required on every call. The signing agent must be the agent that owns the bearer's user.
- A stolen bearer token alone cannot call these routes.
- A stolen agent secret alone cannot identify or authorize a user.
- The request body never carries a user identifier; the user comes from the bearer session.
- The mobile API trusts your backend's attestation that the new email was verified. The signature proves origin and integrity of the request; it does not re-verify the email.
The agent secret must stay on your server. Never ship it to a web frontend or mobile app.
Required headers
| Header | Required | Rule |
|---|---|---|
Authorization | Yes | Bearer <access_token> of the mobile user whose email is changing. |
Content-Type | Yes | application/json |
X-Agent-ID | Yes | Your agent UUID. Must be the same agent whose secret signs the request. |
X-Timestamp | Yes | Unix time in seconds. Must be within ±60 seconds of server time. |
X-Nonce | Yes | 16–64 characters from [A-Za-z0-9._~-]. Single use per agent for 5 minutes. |
X-Signature | Yes | 64 lowercase hex characters. HMAC-SHA256 as described below. |
Additional request limits:
- Body must be at most 4096 bytes.
- Unknown JSON fields are rejected.
- Trailing content after the JSON object is rejected.
How the signature is generated
The signature covers the route, a timestamp, a nonce, and a hash of the exact bytes of the request body.
- Hash the raw request body:
body_hash = lowercase_hex( SHA-256( exact request body bytes ) )
- Build the canonical string. It has six lines joined with
\nand no trailing newline:
htp.email-change.v1
POST
<path>
<X-Timestamp>
<X-Nonce>
<body_hash>
<path> is exactly /api/v2/auth/email-change/request or /api/v2/auth/email-change/verification (no host, no query string).
- Sign it with the agent secret:
X-Signature = lowercase_hex( HMAC-SHA256( key = agent_secret, message = UTF-8(canonical) ) )
Important details:
- Sign the bytes you send. Serialize the JSON body once, hash that string, and send that same string. If your HTTP client re-serializes the object (re-indents, reorders keys, escapes differently), the server computes a different
body_hashand rejects the call withINVALID_SIGNATURE. - The
htp.email-change.v1prefix is fixed. It ensures a signature produced for another agent-secret protocol (for example/connect/token) can never be replayed against these routes. - The signature must be lowercase hex. Uppercase hex is rejected.
- Timestamp and nonce are part of the signed string, so a retry must be re-signed with a fresh timestamp and nonce.
The server verifies in this order: bearer → body size → header format → timestamp window → agent lookup → constant-time signature check → nonce registration (SET NX, 5 minutes) → agent/user binding → strict JSON decoding. A nonce is consumed only after the signature is valid, so a bad signature does not burn a nonce.
Signing examples
Each helper below takes the already-serialized body string and returns the value to place in X-Signature. Use the same string as the HTTP request body.
Node.js
const crypto = require("node:crypto");
function signEmailChange({ agentSecret, path, timestamp, nonce, rawBody }) {
const bodyHash = crypto.createHash("sha256").update(rawBody, "utf8").digest("hex");
const canonical = [
"htp.email-change.v1",
"POST",
path,
String(timestamp),
nonce,
bodyHash,
].join("\n");
return crypto.createHmac("sha256", agentSecret).update(canonical, "utf8").digest("hex");
}
async function requestEmailChange({ baseUrl, accessToken, agentId, agentSecret, newEmail }) {
const path = "/api/v2/auth/email-change/request";
const timestamp = Math.floor(Date.now() / 1000);
const nonce = crypto.randomBytes(16).toString("hex"); // 32 chars, [0-9a-f]
const rawBody = JSON.stringify({ new_email: newEmail }); // serialize once
const signature = signEmailChange({ agentSecret, path, timestamp, nonce, rawBody });
const res = await fetch(baseUrl + path, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
"X-Agent-ID": agentId,
"X-Timestamp": String(timestamp),
"X-Nonce": nonce,
"X-Signature": signature,
},
body: rawBody, // send the exact string that was hashed
});
return res.json();
}
PHP
<?php
function signEmailChange(string $agentSecret, string $path, int $timestamp, string $nonce, string $rawBody): string
{
$bodyHash = hash('sha256', $rawBody);
$canonical = implode("\n", [
'htp.email-change.v1',
'POST',
$path,
(string) $timestamp,
$nonce,
$bodyHash,
]);
// hash_hmac(algo, data, key)
return hash_hmac('sha256', $canonical, $agentSecret);
}
function requestEmailChange(string $baseUrl, string $accessToken, string $agentId, string $agentSecret, string $newEmail): array
{
$path = '/api/v2/auth/email-change/request';
$timestamp = time();
$nonce = bin2hex(random_bytes(16)); // 32 chars, [0-9a-f]
$rawBody = json_encode(['new_email' => $newEmail], JSON_UNESCAPED_SLASHES); // serialize once
$signature = signEmailChange($agentSecret, $path, $timestamp, $nonce, $rawBody);
$ch = curl_init($baseUrl . $path);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $rawBody, // send the exact string that was hashed
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Bearer ' . $accessToken,
'X-Agent-ID: ' . $agentId,
'X-Timestamp: ' . $timestamp,
'X-Nonce: ' . $nonce,
'X-Signature: ' . $signature,
],
]);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
Python
import hashlib
import hmac
import json
import secrets
import time
import requests
def sign_email_change(agent_secret: str, path: str, timestamp: int, nonce: str, raw_body: bytes) -> str:
body_hash = hashlib.sha256(raw_body).hexdigest()
canonical = "\n".join([
"htp.email-change.v1",
"POST",
path,
str(timestamp),
nonce,
body_hash,
])
return hmac.new(agent_secret.encode("utf-8"), canonical.encode("utf-8"), hashlib.sha256).hexdigest()
def request_email_change(base_url: str, access_token: str, agent_id: str, agent_secret: str, new_email: str) -> dict:
path = "/api/v2/auth/email-change/request"
timestamp = int(time.time())
nonce = secrets.token_hex(16) # 32 chars, [0-9a-f]
raw_body = json.dumps({"new_email": new_email}, separators=(",", ":")).encode("utf-8") # serialize once
signature = sign_email_change(agent_secret, path, timestamp, nonce, raw_body)
res = requests.post(
base_url + path,
data=raw_body, # send the exact bytes that were hashed (do not use json=...)
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {access_token}",
"X-Agent-ID": agent_id,
"X-Timestamp": str(timestamp),
"X-Nonce": nonce,
"X-Signature": signature,
},
)
return res.json()
Self-test vector
Use this vector to verify your signing helper before calling the API. The secret below is a test-only value; it is not a real agent secret.
agent_secret test-agent-secret-0123456789abcdef
path /api/v2/auth/email-change/request
body {"new_email":"New.User+tag@Example.com"}
X-Timestamp 1789410000
X-Nonce nonce-0123456789abcdef
body_hash 54c9f718b20c9b2e8c68132746430f21c3fd4a6bb4c1ac07ec70cb7717f516bc
X-Signature 90c66bb87cde7706623ad17384a3d99cbb2a41caaa6894e4292b396bf9823257
The same payload with different formatting, { "new_email": "New.User+tag@Example.com" }, must produce a different signature (9df005a9626583b242dc565185113a3bb8c20b8b70b13d6ddabbec1c2f2744d0). If your helper returns the same value for both bodies, it is hashing a re-serialized object rather than the transmitted bytes.
Response envelope and error codes
Both endpoints use the standard mobile-api envelope. On errors the envelope carries a stable error_code:
{
"trace_id": "…",
"status_code": 409,
"error_code": "EMAIL_ALREADY_EXISTS",
"message": "…",
"data": null
}
- On success, the HTTP status equals
status_code(201for/request,200for/verification). - On error, the HTTP transport status is
200. Read the class fromstatus_codeand branch onerror_code. Never branch onmessage; it is localized. - A missing, invalid, or expired bearer is rejected by the shared auth middleware with
status_code10201(invalid) or10200(expired) and noerror_code. Treat both as "re-authenticate the user".
1. Register The Email Change
POST /api/v2/auth/email-change/request
Registers the user's intent to move to a new email and reserves that email for 5 minutes.
Request
{
"new_email": "New.User+tag@Example.com"
}
Server-side normalization: trim → lowercase the whole address → syntax check → maximum 255 bytes. Plus tags and dots are preserved; no provider-specific rewriting is applied.
Success response
{
"status_code": 201,
"message": "Email change request created.",
"data": {
"request_id": "7ee352c2-6ac6-4ef2-a275-71686d9788de",
"expires_at": 1789410300
}
}
request_idis an opaque UUID. It conveys no authorization on its own.expires_atis an absolute Unix timestamp in seconds (created_at + 300). This differs from the set-email and reset-email responses, whereexpires_atis a relative duration.
Rules
- Only one pending request may exist per user. A new
/requestby the same user supersedes the previous one and releases its reservation. - Only one user may reserve a given normalized email at a time. Another user requesting a reserved email receives
EMAIL_CHANGE_IN_PROGRESS. - The new email must differ from the user's current email (
EMAIL_UNCHANGED) and must not belong to another active account, compared case-insensitively (EMAIL_ALREADY_EXISTS).
Errors
status_code | error_code | When | Action |
|---|---|---|---|
400 | INVALID_REQUEST | Malformed JSON, unknown field, invalid email, body over 4 KiB, bad header format | Fix the request |
401 | INVALID_SIGNATURE | Signature mismatch, unknown agent, timestamp outside ±60 s | Check clock and signing |
401 | REQUEST_REPLAYED | Nonce already used | Use a fresh nonce |
403 | AGENT_USER_MISMATCH | Signing agent does not own the bearer's user | Wrong agent credentials |
403 | USER_OR_AGENT_INACTIVE | User or agent is not active | Stop |
409 | EMAIL_UNCHANGED | Normalized new email equals the current email | Nothing to do |
409 | EMAIL_ALREADY_EXISTS | Another active account holds this email | Ask for a different email |
409 | EMAIL_CHANGE_IN_PROGRESS | Another user holds a live reservation on this email | Retry after up to 5 minutes, or pick another email |
503 | SERVICE_UNAVAILABLE | Redis unavailable; replay protection cannot be guaranteed | Retry with back-off |
500 | (none) | Unexpected failure | Retry later |
2. Attest Verification And Apply The Change
POST /api/v2/auth/email-change/verification
Call this only after your backend has successfully verified the new email address. The mobile API does not send, store, or validate your OTP.
Request
{
"request_id": "7ee352c2-6ac6-4ef2-a275-71686d9788de",
"verification_id": "client-verification-12345",
"verified_at": 1789410200
}
| Field | Rule |
|---|---|
request_id | UUID returned by /request. |
verification_id | 1–128 printable ASCII characters. Unique per agent. This is the business idempotency key. |
verified_at | Unix seconds. Must be after the request was created, no more than 5 minutes old, and no more than 60 seconds in the future. |
new_email is deliberately not accepted. The server applies the email that was reserved by /request.
Success response
{
"status_code": 200,
"message": "Email address updated successfully.",
"data": {
"request_id": "7ee352c2-6ac6-4ef2-a275-71686d9788de",
"status": "completed"
}
}
Neither the old nor the new email is returned. Refresh the user profile separately if you need it.
What happens on success
- If the user has an active cardholder, the payment provider's cardholder email is updated first.
- In one local transaction: the email is updated,
is_email_verifiedis set totrue, every other access/refresh token family for the user is revoked, and an audit record is written. - The calling bearer token (and its refresh token, if any) remains valid. All other sessions for the user are logged out.
- The completed response is cached for 24 hours for idempotent replay.
Idempotency and retries
- Resubmitting the same
request_idandverification_idwithin 24 hours of success returns the identical200 completedpayload without repeating any work. - For transport retries, reuse the same
request_idandverification_idbut generate a freshX-Timestamp,X-Nonce, andX-Signature. The nonce is a replay guard, not the idempotency key. - Any terminal failure (
PROVIDER_UPDATE_FAILED,500, orEMAIL_ALREADY_EXISTSat verification) removes the request. Call/requestagain and repeat your own email verification. There is no "failed but retryable" state.
Errors
status_code | error_code | When | Action |
|---|---|---|---|
400 | INVALID_REQUEST | Malformed body or fields; verified_at before request creation or too far in the future | Fix the request |
401 | INVALID_SIGNATURE / REQUEST_REPLAYED | As above | As above |
403 | AGENT_USER_MISMATCH | Bearer user or signing agent does not match the pending request | Wrong principal |
403 | USER_OR_AGENT_INACTIVE | User or agent is not active | Stop |
404 | REQUEST_NOT_FOUND | Unknown request_id, or a request that expired or failed terminally | Start over |
410 | REQUEST_EXPIRED | Request is past its 5-minute lifetime | Start over |
410 | REQUEST_SUPERSEDED | A newer /request by this user replaced it | Verify against the newer request_id |
409 | ACCOUNT_STATE_CHANGED | The user's current email changed after /request | Start over |
409 | VERIFICATION_TOO_OLD | verified_at is older than 5 minutes | Re-verify and start over |
409 | REQUEST_ALREADY_CLAIMED | The same verification_id is being processed right now | Retry the same IDs (fresh timestamp/nonce/signature) after about 1 second |
409 | VERIFICATION_ID_CONFLICT | Request already claimed or completed with a different verification_id | Do not retry; investigate |
409 | EMAIL_ALREADY_EXISTS | Target email was taken between request and verification (locally or at the provider) | Ask for a different email |
502 | PROVIDER_UPDATE_FAILED | Payment-provider email update failed | Start over |
503 | SERVICE_UNAVAILABLE | Redis or session store unavailable | Retry with back-off |
500 | (none) | Local update failed (possibly after the provider update succeeded) | Start over; a new request converges |
Decision table
error_code | Action |
|---|---|
REQUEST_ALREADY_CLAIMED, SERVICE_UNAVAILABLE, 500 on /request | Retry the same call with a fresh timestamp, nonce, and signature |
Success replay (status: completed) | Done |
REQUEST_NOT_FOUND, REQUEST_EXPIRED, REQUEST_SUPERSEDED, ACCOUNT_STATE_CHANGED, VERIFICATION_TOO_OLD, PROVIDER_UPDATE_FAILED, 500 on /verification | Start over: new /request, re-verify, new /verification |
VERIFICATION_ID_CONFLICT, AGENT_USER_MISMATCH, USER_OR_AGENT_INACTIVE | Do not retry; integration or configuration error |
EMAIL_ALREADY_EXISTS, EMAIL_UNCHANGED, EMAIL_CHANGE_IN_PROGRESS | Ask the user for a different email (or wait up to 5 minutes for EMAIL_CHANGE_IN_PROGRESS) |
INVALID_REQUEST, INVALID_SIGNATURE, REQUEST_REPLAYED | Fix the client: payload, clock, signing, or nonce generation |
Common Failure Cases
These apply to the set-email and reset-email flows. The client-verified flow uses the stable error_code values listed above.
400: invalid email format, invalid OTP, expired session, or wrong session purpose403: resend requested too quickly, or reset session does not belong to the current user404: user not found409: new email already exists
Integration Notes
- Use
set-emailonly for users who still need to verify or attach an email. - Use
reset-emailwhen replacing an already registered email. - The OTP steps here are route-specific and do not use
/connect/token. - Use the client-verified
email-changeflow only from a trusted backend that holds the agent secret and performs its own email verification. It requires both the user's bearer token and the agent signature headers.