Mobile User

Email Management

Set an initial email address, replace the current one with OTP verification, or apply an email change verified by your own backend.

Flow Summary

The current email module has three flows:

Set Email Flow

Step 1. Send OTP
POST /api/v2/auth/set-email/otp

Step 2. Verify and save
POST /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 change
POST /api/v2/auth/email-change/request

Step 2. Attest verification and apply
POST /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 email and sets is_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_id that 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_id must 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_id value as the OTP session UUID.
  • Resending is limited to once per minute for the same new_email_session_id. When blocked, the response includes retry_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 email in 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

FactorCarried inProves
End-user sessionAuthorization: Bearer <access_token>Who the user is, and which agent they belong to
Agent signatureX-Agent-ID, X-Timestamp, X-Nonce, X-SignatureThe 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

HeaderRequiredRule
AuthorizationYesBearer <access_token> of the mobile user whose email is changing.
Content-TypeYesapplication/json
X-Agent-IDYesYour agent UUID. Must be the same agent whose secret signs the request.
X-TimestampYesUnix time in seconds. Must be within ±60 seconds of server time.
X-NonceYes16–64 characters from [A-Za-z0-9._~-]. Single use per agent for 5 minutes.
X-SignatureYes64 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.

  1. Hash the raw request body:
body_hash = lowercase_hex( SHA-256( exact request body bytes ) )
  1. Build the canonical string. It has six lines joined with \n and 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).

  1. 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_hash and rejects the call with INVALID_SIGNATURE.
  • The htp.email-change.v1 prefix 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 (201 for /request, 200 for /verification).
  • On error, the HTTP transport status is 200. Read the class from status_code and branch on error_code. Never branch on message; it is localized.
  • A missing, invalid, or expired bearer is rejected by the shared auth middleware with status_code 10201 (invalid) or 10200 (expired) and no error_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_id is an opaque UUID. It conveys no authorization on its own.
  • expires_at is an absolute Unix timestamp in seconds (created_at + 300). This differs from the set-email and reset-email responses, where expires_at is a relative duration.

Rules

  • Only one pending request may exist per user. A new /request by 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_codeerror_codeWhenAction
400INVALID_REQUESTMalformed JSON, unknown field, invalid email, body over 4 KiB, bad header formatFix the request
401INVALID_SIGNATURESignature mismatch, unknown agent, timestamp outside ±60 sCheck clock and signing
401REQUEST_REPLAYEDNonce already usedUse a fresh nonce
403AGENT_USER_MISMATCHSigning agent does not own the bearer's userWrong agent credentials
403USER_OR_AGENT_INACTIVEUser or agent is not activeStop
409EMAIL_UNCHANGEDNormalized new email equals the current emailNothing to do
409EMAIL_ALREADY_EXISTSAnother active account holds this emailAsk for a different email
409EMAIL_CHANGE_IN_PROGRESSAnother user holds a live reservation on this emailRetry after up to 5 minutes, or pick another email
503SERVICE_UNAVAILABLERedis unavailable; replay protection cannot be guaranteedRetry with back-off
500(none)Unexpected failureRetry 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
}
FieldRule
request_idUUID returned by /request.
verification_id1–128 printable ASCII characters. Unique per agent. This is the business idempotency key.
verified_atUnix 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

  1. If the user has an active cardholder, the payment provider's cardholder email is updated first.
  2. In one local transaction: the email is updated, is_email_verified is set to true, every other access/refresh token family for the user is revoked, and an audit record is written.
  3. The calling bearer token (and its refresh token, if any) remains valid. All other sessions for the user are logged out.
  4. The completed response is cached for 24 hours for idempotent replay.

Idempotency and retries

  • Resubmitting the same request_id and verification_id within 24 hours of success returns the identical 200 completed payload without repeating any work.
  • For transport retries, reuse the same request_id and verification_id but generate a fresh X-Timestamp, X-Nonce, and X-Signature. The nonce is a replay guard, not the idempotency key.
  • Any terminal failure (PROVIDER_UPDATE_FAILED, 500, or EMAIL_ALREADY_EXISTS at verification) removes the request. Call /request again and repeat your own email verification. There is no "failed but retryable" state.

Errors

status_codeerror_codeWhenAction
400INVALID_REQUESTMalformed body or fields; verified_at before request creation or too far in the futureFix the request
401INVALID_SIGNATURE / REQUEST_REPLAYEDAs aboveAs above
403AGENT_USER_MISMATCHBearer user or signing agent does not match the pending requestWrong principal
403USER_OR_AGENT_INACTIVEUser or agent is not activeStop
404REQUEST_NOT_FOUNDUnknown request_id, or a request that expired or failed terminallyStart over
410REQUEST_EXPIREDRequest is past its 5-minute lifetimeStart over
410REQUEST_SUPERSEDEDA newer /request by this user replaced itVerify against the newer request_id
409ACCOUNT_STATE_CHANGEDThe user's current email changed after /requestStart over
409VERIFICATION_TOO_OLDverified_at is older than 5 minutesRe-verify and start over
409REQUEST_ALREADY_CLAIMEDThe same verification_id is being processed right nowRetry the same IDs (fresh timestamp/nonce/signature) after about 1 second
409VERIFICATION_ID_CONFLICTRequest already claimed or completed with a different verification_idDo not retry; investigate
409EMAIL_ALREADY_EXISTSTarget email was taken between request and verification (locally or at the provider)Ask for a different email
502PROVIDER_UPDATE_FAILEDPayment-provider email update failedStart over
503SERVICE_UNAVAILABLERedis or session store unavailableRetry with back-off
500(none)Local update failed (possibly after the provider update succeeded)Start over; a new request converges

Decision table

error_codeAction
REQUEST_ALREADY_CLAIMED, SERVICE_UNAVAILABLE, 500 on /requestRetry 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 /verificationStart over: new /request, re-verify, new /verification
VERIFICATION_ID_CONFLICT, AGENT_USER_MISMATCH, USER_OR_AGENT_INACTIVEDo not retry; integration or configuration error
EMAIL_ALREADY_EXISTS, EMAIL_UNCHANGED, EMAIL_CHANGE_IN_PROGRESSAsk the user for a different email (or wait up to 5 minutes for EMAIL_CHANGE_IN_PROGRESS)
INVALID_REQUEST, INVALID_SIGNATURE, REQUEST_REPLAYEDFix 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 purpose
  • 403: resend requested too quickly, or reset session does not belong to the current user
  • 404: user not found
  • 409: new email already exists

Integration Notes

  1. Use set-email only for users who still need to verify or attach an email.
  2. Use reset-email when replacing an already registered email.
  3. The OTP steps here are route-specific and do not use /connect/token.
  4. Use the client-verified email-change flow 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.
Copyright © 2026