# Mobile apps

Everything a customer can do in the portal is a JSON route with bearer authentication, so a mobile app uses the same
API as everyone else. This page puts the pieces in the order an app needs them.

:::note{title="Native push"}

Sign-in (password, 2FA and providers), device sessions with refresh tokens and app billing return pages are all
available. Native push through FCM and APNs is not switched on yet; alerts reach the inbox meanwhile (see below).

:::

## Sign in

```bash
curl -sS -X POST "$RISKPILOT_URL/api/v1/customer/login" \
  -H "Content-Type: application/json" \
  -d '{ "email": "ops@acme.example", "password": "…" }'
# 200 { "session": "rps_…", "next": "signals" }
# 200 { "session": "rps_…", "next": "signals", "twoFactor": "required" }
```

1. If the answer has `"twoFactor": "required"`, ask for the 6-digit code (or a recovery code) and send it with that
   session within 10 minutes: `POST /customer/2fa/verify { "code": "…" }`. Until then every other route answers
   `401 two_factor_required`.
2. Keep the session in the platform's secure storage (iOS Keychain, Android Keystore-backed storage), never in plain
   preferences or logs.
3. Look at `next`: `signals` means the account has paid access; `billing` or `checkout` means it has not, and paid
   routes will answer 402. See [Billing from the app](#billing-from-the-app).
4. Turn the session into a [device session](#stay-signed-in-device-sessions) so the person stays signed in.
5. `GET /customer/me` says who signed in: the account holder or a team member, with the `role`.

Refusals to handle: `401` (wrong email or password), `403 email_unverified` (offer
`POST /customer/verify/resend { "email" }`), `429 throttled` (too many attempts; wait 15 minutes),
`POST /customer/password/forgot { "email" }` for a forgotten password (the reset link opens the portal).

Never ship a live or named API key inside an app: anyone can extract it. Sign the person in instead.

## Sign in with Google, Microsoft, GitHub or Apple

Native apps use the OAuth flow for native apps (RFC 8252) with PKCE. It is available once RiskPilot has registered
your app's redirect URI (`RP_NATIVE_REDIRECT_URIS`, exact match); ask for it before you ship.

1. Make a PKCE pair: `verifier` = 43 to 128 random URL-safe characters, `challenge` = base64url(SHA-256(verifier)).
2. Open in the **system browser** (iOS `ASWebAuthenticationSession`, Android Custom Tabs; never a web view):

   ```text
   GET /api/v1/customer/oauth/{provider}/start?redirect_uri=<registered>&code_challenge=<challenge>
       &code_challenge_method=S256&state=<your state>
   ```

   An unregistered `redirect_uri` answers `400 redirect_uri_not_allowed` and is never redirected to; a missing or
   `plain` challenge answers `400 pkce_required`.
3. The browser comes back to `<redirect_uri>?code=<one-time code>&state=<your state>`, or `?error=<code>` (`denied`,
   `expired`, `mismatch`, `provider`, `not_configured`, `email_unverified_account`, `email_password_account`,
   `email_taken`). Check `state`.
4. Exchange the code:

   ```bash
   curl -sS -X POST "$RISKPILOT_URL/api/v1/customer/oauth/native/token" \
     -H "Content-Type: application/json" \
     -d '{ "code": "…", "codeVerifier": "…", "redirectUri": "com.example.riskpilot:/oauth" }'
   # 200 { "session": "rps_…", "next": "signals" }   (plus "twoFactor": "required" when the person has 2FA)
   ```

   The code works once, for 2 minutes, and only with the matching verifier and redirect URI (`400 invalid_grant`
   otherwise). Then continue as after a password sign-in.

Prefer a claimed https redirect (iOS universal link, Android App Link) on a domain you own; a reverse-domain custom
scheme such as `com.example.riskpilot:/oauth` also works. Loopback redirects for desktop apps are not supported.

To connect a provider to an account that is already signed in: `POST /customer/oauth/{provider}/link { "redirectUri": "…", "state": "…" }`
returns `{ url }`; open it in the system browser; it ends on
`<redirectUri>?link_code=…&state=…`; then `POST /customer/oauth/link/confirm { "code": "…" }` with the same session.

## Stay signed in: device sessions

A plain sign-in session lasts 30 days. An app should turn it into a **device session**, which stays signed in for as
long as the app is used at least once every 90 days:

```bash
curl -sS -X POST "$RISKPILOT_URL/api/v1/customer/sessions/device" \
  -H "Authorization: Bearer rps_…" -H "Content-Type: application/json" \
  -d '{ "name": "Sara’s iPhone", "platform": "ios" }'
# 201 { "session": "rps_…", "refreshToken": "rpr_…", "expiresAt": "…", "refreshExpiresAt": "…", "item": { … } }
```

- Do it within **15 minutes** of signing in (`409 sign_in_too_old` after that) and after the 2FA step
  (`401 two_factor_required` before it). The token you sent stops working: store the new `session` and
  `refreshToken` in secure storage (iOS Keychain, Android Keystore-backed storage).
- The access token (`session`) works for 24 hours. Before it runs out, or on a `401`, refresh:
  `POST /customer/session/refresh { "refreshToken": "rpr_…" }` (no bearer) returns a new `session` **and** a new
  `refreshToken`; the refresh window starts again (90 days).
- **Rotation is strict.** Each refresh token works once. Presenting one that was already used ends the device session
  at once (`401 refresh_reused`), because it means someone has a copy. Send one refresh at a time, and store the new
  pair before you use it. If the refresh fails, show the sign-in screen.
- After a refresh an open [stream](/stream) closes with `4401`; reconnect with the new token.
- Sessions: `GET /customer/sessions` lists the person's own sessions (`current` marks this one),
  `PATCH /customer/sessions/{id} { "name" }` renames one, `DELETE /customer/sessions/{id}` ends one (this one too:
  a sign-out), `POST /customer/sessions/revoke-others` ends all the others.
- Every session also ends when the password is changed or reset, 2FA is turned on from another device, the person is
  removed from the team, or the account is suspended (`403 paused`) or erased. Treat any `401` that a refresh does not
  fix as signed out.
- Sign out with `DELETE /customer/sessions/{id}` for the current session, or `POST /customer/logout`, then delete both
  tokens from storage.

## Billing from the app

`POST /customer/billing/checkout { "packageId"?, "successUrl"?, "cancelUrl"? }` and
`POST /customer/billing/portal { "returnUrl"? }` answer `{ "url": "…" }`; open it in the system browser. Return URLs
must be https pages registered with RiskPilot (`RP_BILLING_RETURN_URLS`; a query string is allowed, so
`?session={CHECKOUT_SESSION_ID}` passes through), otherwise `400 return_url_not_allowed`. Use a universal link that
opens your app. Without return URLs, Stripe returns to the web portal.

## Read and stay live

- Lists and details: the same routes as any integration (`/customer/signals`, `/companies`, `/leaderboard`). They
  count against the package's quota like any other credential.
- Live updates: open `wss://…/api/v1/customer/stream` with `Authorization: Bearer rps_…` on the upgrade request
  (React Native's WebSocket accepts headers). Keep the newest event id and, when the app returns to the foreground,
  reconnect with `?lastEventId=` to get what was missed; on `reset`, refetch the first page over REST. Close the
  stream when the app goes to the background. See [Live stream](/stream).
- Watchlist, alert rules, inbox and unread badge: see [Watchlist, alerts and notifications](/alerts). Poll
  `GET /customer/notifications/unread-count` when the app comes to the foreground.
- Chat: the same routes as the portal; stream answers with `Accept: text/event-stream` (React Native needs a
  fetch-streaming polyfill). See [Chat](/chat).

## Push notifications

1. Read `GET /customer/notifications/settings`. `push.fcm.enabled` (Android) and `push.apns.enabled` (iOS) say whether
   the server takes your platform's tokens.
2. If enabled, after the person allows notifications, register the token:
   `POST /customer/push/devices { "provider": "fcm" | "apns", "token": "…", "label": "Pixel 9" }`. Register again
   whenever the platform gives you a new token; the same device moves to whoever registered it last.
3. On sign-out, `DELETE /customer/push/devices/{id}` (the id from the registration answer).
4. `POST /customer/push/test` sends a test to every device of the account.

Today both flags are `false` and registration answers `503 push_unavailable`: the FCM and APNs senders are not
implemented yet. Alerts still reach the inbox, so show the unread count until push is switched on.

## Least privilege for a companion backend

If your app talks to your own backend and the backend calls RiskPilot, give the backend a
[named key](/authentication#named-api-keys) with only the scopes it needs, and keep sessions on the devices.
