TrackMe API Docs
Flow guides

Authentication & Tokens

How to obtain, send, refresh, and revoke the Bearer access token that authorizes every TrackMe API call.

This guide is for Flutter engineers building the customer (and owner) apps. It covers every way to get a token, how to send it, the secondary flows (OTP, password reset, email verification, social link/unlink), and the lifecycle of the account and tokens behind them.

Every authenticated call uses an opaque Bearer access token (prefix oat_) in the Authorization header. SMS-flow password registration creates a pending_verification account; phone verification activates it. Existing sign-in methods reject pending accounts. Send Accept-Language: ar for Arabic error copy.

SMS-flow register returns no tokens. Complete POST /api/v1/auth/verify-otp to receive a 15-minute access token and a 30-day refresh token. Rotate through /auth/token/refresh; refresh tokens cannot authorize ordinary API calls. Existing password login, social sign-in, generic OTP sign-in and temporary legacy registration continue to return a 30-day access token.

The flow at a glance

Step 1 — Get a token (pick one entry point)

Register with /auth/register, then verify the SMS using /auth/verify-otp. Existing accounts can use /auth/login, social sign-in (/auth/social/google or /auth/social/apple), or passwordless OTP (/auth/otp/send then /auth/otp/verify with purpose: "sign_in").

Step 2 — Store the token and send it on every call

Save accessToken to the keychain. Send Authorization: Bearer <oat_...> on every /api/v1/* authenticated request.

Step 3 — (Optional) Verify the email

Authenticated: POST /api/v1/auth/verify-email/start (server reads the email from your token) then /auth/verify-email/confirm with the 6-digit code. Email verification is optional. Registration phone verification must finish before signing in.

Step 4 — Manage the account over its life

Change password (/auth/password/change), link/unlink a social identity (/auth/social/unlink), or recover a lost password via the 3-step reset flow.

Step 5 — Sign out

POST /api/v1/auth/logout revokes only the calling token. Other devices stay signed in.

All responses use the standard envelope:

{ "data": { "...": "..." }, "meta": { "requestId": "req_..." } }
{ "error": { "code": "INVALID_CREDENTIALS", "message": "..." }, "meta": { "requestId": "req_..." } }

Step detail

Password register

Creates a pending_verification account and dispatches a six-digit SMS code. No session token is returned. Owner memberships become usable when phone verification activates the account; KYC is separate.

POST /api/v1/auth/register
Content-Type: application/json
Accept-Language: en
X-Auth-Flow: sms-otp

{
  "fullName": "Khalid Al-Saud",
  "email": "[email protected]",
  "password": "StrongPass123!",
  "phone": "+966555012345",
  "requestedTypes": ["customer"],
  "acceptedTermsVersion": "2026-04",
  "city": "Riyadh",
  "country": "SA"
}
{
  "data": {
    "user": { "id": "usr_...", "email": "[email protected]", "status": "pending_verification", "isVerified": false, "types": ["customer"] },
    "ownerBusinessProfile": null,
    "verification": { "channel": "sms", "destination": "+966555012345", "expiresAt": "2026-10-15T12:10:00Z", "resendAvailableAt": "2026-10-15T12:01:00Z" }
  },
  "meta": { "requestId": "req_..." }
}

Notes:

  • Updated clients send X-Auth-Flow: sms-otp when registering. X-App-Version: 1.1.9 or newer also selects this flow. While AUTH_LEGACY_REGISTRATION_ENABLED=true, unversioned clients and versions up to 1.1.8+24 retain optional phone/city/country, receive data.accessToken, and create an active account without claiming phone verification. Production temporarily enables this switch for the released store build; disable it after the replacement ships. The explicit SMS-flow header always requires verification, even during compatibility mode.

  • password must be >= 8 chars with at least one uppercase and one digit. email is normalized (lowercased/trimmed) and must be unique.

  • requestedTypes is any of customer | owner | hiring (admin types are stripped). ownerProfile is required when requestedTypes includes owner.

  • fullName is required (3–100 characters); phone is unique E.164. country and canonical city are required and must be active in the catalog.

  • Load GET /api/v1/locations/countries and GET /api/v1/locations/countries/{code}/cities; both return data arrays in display order. Admin country/city edits are immediately visible.

  • Errors: 409 on duplicate email, 422 validation, 429 rate-limited (per IP).

Registration SMS verification

Send POST /api/v1/auth/verify-otp with { "emailOrPhone": "+966555012345", "code": "123456", "channel": "sms" }. An email identifier resolves to the account's registered phone; the code always travels by SMS. Success returns data.user, data.token (alias of accessToken), data.accessToken, data.refreshToken and expiry timestamps. Invalid, expired, or already-used codes return 422; codes expire after ten minutes and lock after five incorrect attempts.

Resend through POST /api/v1/auth/resend-otp with { "emailOrPhone": "+966555012345", "channel": "sms" }. Wait at least 60 seconds between successful sends (429 with retryAfterSeconds during cooldown). Only the latest code works. Delivery failures leave the account pending so resending can recover without creating another account.

ACCOUNT_INACTIVE means pending registration phone verification only. Suspended and banned accounts return ACCOUNT_SUSPENDED and ACCOUNT_BANNED; other unavailable lifecycle states return ACCOUNT_UNAVAILABLE. Do not open the phone-verification screen for those moderation errors. Existing active accounts can still sign in without a verified phone, including store reviewer accounts; their phone verification flag is not fabricated.

Taqnyat accepts international E.164 destinations when the account permits the destination country and the sender is approved for it. Set TAQNYAT_INTERNATIONAL_SENDER when a different sender is approved for international delivery. node ace messaging:check --sms checks account/balance and sender approval without sending. Provider acceptance is distinct from handset receipt; IP/country restrictions can still reject a send. Never log or share OTPs or API credentials.

SMS uses the configured gateway: SMS_PROVIDER=taqnyat with TAQNYAT_API_TOKEN and TAQNYAT_SENDER for Saudi numbers, or SMS_PROVIDER=twilio with TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN and TWILIO_FROM for international delivery. Missing credentials fail explicitly. Twilio transport follows its Message resource API.

GET and PATCH /api/v1/user/profile expose the flat personal profile. Names, unique E.164 phone, country and canonical city can be edited; changing the phone clears its verification flag. /me retains its existing nested response for older clients. Apple sign-in stores missing names as null and preserves previously saved names.

Password login

POST /api/v1/auth/login
Content-Type: application/json

{ "email": "[email protected]", "password": "StrongPass123!" }
{
  "data": {
    "user": { "id": "usr_...", "status": "active", "types": ["customer"] },
    "accessToken": "oat_aBc123..."
  },
  "meta": { "requestId": "req_..." }
}

Unknown email and wrong password both return 401 with error.code=INVALID_CREDENTIALS (anti-enumeration). 5 failed attempts in 1 minute trigger a 20-minute IP+email block (429 RATE_LIMITED with retryAfterSeconds); only failures consume quota.

Social sign-in (Google / Apple)

Your app runs the native handshake, then POSTs the resulting JWT. The server verifies it against the provider JWKS (signature, issuer, audience, expiry) and returns the same {user, accessToken} shape (30-day).

POST /api/v1/auth/social/google
Content-Type: application/json

{
  "idToken": "eyJhbGciOiJSUzI1NiIsImtpZCI6...",
  "acceptedTermsVersion": "2026-04"
}
POST /api/v1/auth/social/apple
Content-Type: application/json

{
  "identityToken": "eyJraWQiOiJZdXlYb1kiLCJhbGciOiJSUzI1NiJ9...",
  "fullName": { "givenName": "Khalid", "familyName": "Al-Saud" },
  "acceptedTermsVersion": "2026-04"
}
  • Bad token -> 401 SOCIAL_TOKEN_INVALID. Throttle: 30/min/IP.
  • If the email already exists on a password account, the server links only when the provider asserts the email is verified — otherwise 409 (sign in with password, then link). A provider token with no email -> 401.
  • New users get a customer membership; emailVerifiedAt is stamped when the provider confirmed the email.
  • Apple: fullName is effectively required on the very first sign-in. Apple delivers the name only once, outside the JWT, and the server never gets a second chance. Capture it client-side and send it on the first call.

Passwordless OTP sign-in

POST /api/v1/auth/otp/send
Content-Type: application/json

{ "destination": "[email protected]", "purpose": "sign_in", "channel": "email" }
{ "data": { "sent": true, "destination": "[email protected]", "purpose": "sign_in" }, "meta": { "requestId": "req_..." } }

Then verify. For purpose: "sign_in" the response also carries user + accessToken — no separate login call:

POST /api/v1/auth/otp/verify
Content-Type: application/json

{ "destination": "[email protected]", "code": "482915", "purpose": "sign_in" }
{
  "data": {
    "verified": true, "destination": "[email protected]", "purpose": "sign_in",
    "user": { "id": "usr_...", "status": "active" },
    "accessToken": "oat_aBc123..."
  },
  "meta": { "requestId": "req_..." }
}
  • OTP is 6 digits, valid 10 minutes, single-use. purpose is sign_in | verify_email | verify_phone. If channel is omitted it is guessed (email if the destination contains @, else SMS then WhatsApp). 60s resend cooldown.
  • Email sign_in is find-or-create (a new account lands email-verified). Phone sign_in is login-only — an unknown number returns 409 OTP_NO_ACCOUNT (tell the user to register).
  • Failure codes are all 409 and specific: OTP_INVALID, OTP_EXPIRED, OTP_ALREADY_USED, OTP_LOCKED, OTP_NOT_FOUND (plus OTP_NO_ACCOUNT for phone sign-in). 5 wrong attempts lock the challenge (OTP_LOCKED) — get a fresh /auth/otp/send.

Verify email (authenticated)

The server pulls the email from your Bearer token — do not send a destination.

POST /api/v1/auth/verify-email/start
Authorization: Bearer oat_aBc123...
{ "data": { "sent": true, "alreadyVerified": false, "challengeId": "otp_...", "destination": "[email protected]", "channel": "email", "expiresAt": "2026-06-21T12:10:00.000Z", "resendAvailableAt": "2026-06-21T12:01:00.000Z" }, "meta": { "requestId": "req_..." } }

Idempotent: already verified -> { "sent": false, "alreadyVerified": true }; no email on file -> { "sent": false, "alreadyVerified": false }. /auth/verify-email/resend is functionally identical. Confirm with the code:

POST /api/v1/auth/verify-email/confirm
Authorization: Bearer oat_aBc123...
Content-Type: application/json

{ "code": "482915" }
{ "data": { "verified": true, "alreadyVerified": false, "emailVerifiedAt": "2026-06-21T12:05:00.000Z" }, "meta": { "requestId": "req_..." } }

Password reset (3-step, lost-access flow)

POST /api/v1/auth/password/reset/start
Content-Type: application/json

{ "destination": "[email protected]" }

Always returns 200 (anti-enumeration; no code is actually sent for unknown addresses). Then optionally pre-check the code — this does not consume it:

POST /api/v1/auth/password/reset/verify
Content-Type: application/json

{ "destination": "[email protected]", "code": "482915" }
{ "data": { "verified": true }, "meta": { "requestId": "req_..." } }

Finally complete with the (still valid) code + new password:

POST /api/v1/auth/password/reset/complete
Content-Type: application/json

{ "destination": "[email protected]", "code": "482915", "newPassword": "EvenStrongerPass456!" }

/complete consumes the OTP, rejects reuse of the last 5 passwords (409), saves the new password, and revokes ALL access tokens — the user is signed out on every device and must log in again everywhere. 404 if no user is found after a valid code.

Change password (authenticated)

POST /api/v1/auth/password/change
Authorization: Bearer oat_aBc123...
Content-Type: application/json

{ "currentPassword": "StrongPass123!", "newPassword": "EvenStrongerPass456!" }

Verifies currentPassword (per-user gate: 5 wrong/min -> 20-min block, 429), rejects reuse of the last 5 (409, field=newPassword), then revokes every other token but keeps the calling token alive — the current client stays signed in. Contrast with reset/complete, which logs out everywhere.

Refresh token rotation

POST /api/v1/auth/token/refresh
Content-Type: application/json

{ "refreshToken": "oat_rEfReSh..." }
{
  "data": {
    "accessToken": "oat_new...", "accessTokenExpiresAt": "2026-06-21T12:20:00.000Z",
    "refreshToken": "oat_newRefresh...", "refreshTokenExpiresAt": "2026-07-21T12:05:00.000Z"
  },
  "meta": { "requestId": "req_..." }
}

Single-use rotation: the supplied refresh token is revoked and a new pair minted. Overwrite both stored tokens. Access TTL = 15 min, refresh TTL = 30 days. Invalid/expired/reused -> 401 REFRESH_TOKEN_INVALID. Registration SMS verification issues the first pair.

POST /api/v1/auth/social/unlink
Authorization: Bearer oat_aBc123...
Content-Type: application/json

{ "provider": "google" }

200 { provider, unlinked: true }. Refuses with 409 LAST_AUTH_METHOD if the caller has neither a usable password nor any other oauth identity (would lock them out) — prompt them to set a password first. 404 if that provider is not linked.

Logout

POST /api/v1/auth/logout
Authorization: Bearer oat_aBc123...
{ "data": { "success": true }, "meta": { "requestId": "req_..." } }

Revokes only the current token. Other devices stay signed in.

Guest token (read-only hint, not a real token)

POST /api/v1/auth/guest
{ "data": { "anonymousToken": "guest_01J...", "capabilities": ["observe"] }, "meta": { "requestId": "req_..." } }

This is a plain generated string, never stored server-side. It will fail the Bearer guard. Use it only as a client-side read-only intent flag for public endpoints, which are anonymous. See Implementation notes.


Lifecycle

Password registration creates a pending_verification account. A valid registration SMS code sets status=active and phoneVerifiedAt. Social and generic OTP account creation retain their existing behavior; neither can sign in to a pending password account.

State table

StateMeaningHow you got hereWhat's allowed next
user.status=pending_verificationRegistration awaits SMS proofPassword registrationVerify or resend registration OTP; no session tokens
user.status=activeAccount is liveRegistration SMS verification, social or OTP account creationAll membership-appropriate API calls
email unverified (emailVerifiedAt=null)Email not confirmedDefault after password registerVerify via /auth/verify-email/* or OTP verify_email
email verified (emailVerifiedAt set)Email confirmedConfirm OTP, social link, or OTP email sign-inStays verified
phone unverified (phoneVerifiedAt=null)Phone not confirmedDefaultVerify implicitly via OTP phone sign_in
phone verified (phoneVerifiedAt set)Phone confirmedOTP phone sign-inStays verified
membership active per typeType access grantedGranted at creationListed in user.types (active only)
owner verificationStatus=not_required_for_mvpOwner access live, no KYCRegister with owner typeFull owner surface
access token validUsable BearerIssued by a sign-in flowAuthenticated calls until revoked
access token revokedDead tokenLogout, password change, password resetRe-login required
refresh token validRotatableReturned by /auth/token/refreshOne rotation, then consumed
refresh token consumedDeadUsed once (single-use)Use the new one from the response
oauth identity linked / unlinkedSocial login on/offSocial sign-in / /auth/social/unlinkLink or unlink (unlink blocked if last method)
OTP challenge active / verified / expired / locked / usedCode lifecycle/auth/otp/sendVerify (consumes) or re-send

Transitions

  • no account -> pending account + SMS: POST /auth/register
  • pending account -> active account + token pair: POST /auth/verify-otp
  • no/existing account -> active account + token: POST /auth/social/google or /auth/social/apple (links to a verified-email account or creates a customer)
  • no/existing account -> active account + token: POST /auth/otp/verify with purpose=sign_in (email find-or-create; phone login-only)
  • unauthenticated -> authenticated: POST /auth/login
  • email unverified -> verified: POST /auth/verify-email/confirm (or OTP verify_email; or implicitly on social link / OTP email sign-in)
  • phone unverified -> verified: implicitly on OTP phone sign_in
  • valid refresh token -> new access+refresh pair (old revoked): POST /auth/token/refresh
  • forgot password -> code sent: POST /auth/password/reset/start
  • code sent -> code verified (not consumed): POST /auth/password/reset/verify
  • code sent/verified -> password changed + ALL tokens revoked: POST /auth/password/reset/complete
  • known password -> password changed + OTHER tokens revoked (current kept): POST /auth/password/change
  • identity linked -> unlinked (blocked if last method): POST /auth/social/unlink
  • authenticated (this token) -> this token revoked: POST /auth/logout

Implementation Notes

Integration issueCorrect handling
Expecting tokens from /auth/register.Finish /auth/verify-otp to get access and refresh tokens. Existing login/social/generic OTP return access tokens only.
Sending the guest guest_<ULID> string as a Bearer token.It is not a real token and fails the guard. Use it only as a client-side read-only hint; guest endpoints are anonymous anyway.
Trying to "promote a guest" by registering with the guest token.Not implemented — /auth/register has no guest-upgrade path. Treat guest -> account as a fresh register.
Sending a refresh token in Authorization.Refresh tokens carry ability ['refresh'], not ['*'], so the api guard rejects them. Only send the access token.
Replaying a refresh token after rotation.Single-use: it is revoked on first use and replays return 401 REFRESH_TOKEN_INVALID. Always overwrite both stored tokens with the response.
Expecting the current device to stay logged in after a password reset./auth/password/reset/complete revokes ALL tokens — every device must re-login. Use /auth/password/change (keeps the calling token) when the user knows the old password.
Treating /auth/otp/verify failures as a generic CONFLICT.They are specific 409 codes: OTP_INVALID/EXPIRED/ALREADY_USED/LOCKED/NOT_FOUND (and OTP_NO_ACCOUNT for phone sign-in). After 5 wrong attempts it is OTP_LOCKED — re-send.
Assuming /auth/password/reset/verify advances state.It is a non-consuming peek so /complete can reuse the same code. Only /complete consumes it; wrong attempts still count toward the 5-attempt lockout.
Expecting phone OTP sign-in to create an account.Phone sign_in is login-only; unknown numbers get 409 OTP_NO_ACCOUNT. Only email sign-in is find-or-create.
Losing the Apple display name.Apple sends the name only on the first authorization, outside the JWT. Capture it then and send fullName on the first /auth/social/apple call — no second chance.
Expecting social link to a password account when the email is unverified.Linking needs the provider to assert the email is verified; otherwise 409. Tell the user to sign in with password and link from settings. A provider with no email -> 401.
Distinguishing unknown-email vs wrong-password on login.You cannot — both return 401 INVALID_CREDENTIALS by design. 5 fails/min -> 20-min 429 block with retryAfterSeconds.
Unlink quietly removing the last sign-in method./auth/social/unlink returns 409 LAST_AUTH_METHOD if it would lock the user out. Prompt them to set a password first.
Trusting the OTP-send rate-limit docstring.It says "3 per 15 min" but the real limit is ~5 per 15 min per (destination, purpose). Handle 429 RATE_LIMITED with retryAfterSeconds regardless.
Owner access blocked until KYC.Owner is live immediately (verificationStatus=not_required_for_mvp). No KYC gate exists for the MVP.

Locale and timezone: send Accept-Language: ar for Arabic error/notification/email copy (default en; persisted as the user's preferred language on first authenticated request). Display-string timezone is X-Timezone: Asia/Riyadh (IANA); wire timestamps stay UTC ISO-8601 with Z.

On this page