Mobile apps (React Native and Expo)

Explanation: what & why

A mobile app can use Vectros the way a single-page web app does, with no server of its own. Your users sign in with your identity provider. The app exchanges the provider's token for a short-lived Vectros bearer (st_*) and calls the API directly from the device. No Vectros key is ever shipped in the app.

 app ── system browser ──► your identity provider      (sign-in, PKCE)
  │◄── ID / access / refresh tokens ──┘
  │
  ├── POST /v1/auth/token/exchange (the provider's JWT) ──► Vectros
  │◄── st_* (at most one hour) ────────────────────────────┘
  │
  └── SDK calls with the st_* ─────────────────────────────► Vectros

@vectros-ai/react gives a React Native app the same auth state, token cache and scope gates the web toolkit uses, through two entries that need no web UI kit:

  • @vectros-ai/react/core: AuthProvider, useAuth, ScopeGate, useScopeGate, CurrentTenantProvider, the token cache (getVectrosApiToken, setPartnerApiTokenMinter), the exchange call itself (exchangeSubjectToken), useInferenceStream, the schema form logic, API error helpers and IntlProvider.
  • @vectros-ai/react/providers/expo: ExpoAuthProvider, which signs in through the system browser with expo-auth-session, keeps the provider's refresh token in expo-secure-store, and exchanges the provider's token for an st_*. It works with any identity provider that offers the OpenID Connect authorization-code flow with PKCE to a public client: Amazon Cognito (with a user pool domain), Auth0, Okta and Microsoft Entra ID among them. Firebase Authentication has no such flow; see Firebase Authentication.

Import from /core, never from @vectros-ai/react itself, in a mobile app. The root entry adds the MUI components and needs MUI, Emotion, react-dom and react-router installed; without them the app does not bundle (Metro: Unable to resolve module @mui/material).

How-to: sign in and call the API

Prerequisites:

  • @vectros-ai/react 0.18.0 or later, with react, react-intl, @tanstack/react-query and @vectros-ai/sdk.
  • Expo SDK 53 or later (React Native 0.79 or later), whose bundler resolves package exports by default; the /core and providers/* subpaths depend on it. TypeScript resolves their types under every moduleResolution setting, including node10.
  • expo-auth-session and expo-secure-store.
  • An app context, and your identity provider registered and verified as a trusted issuer on it: see Register a trusted external IdP issuer. Until the registration is active, every exchange answers 404, the same answer as for an unknown issuer.
npx expo install expo-auth-session expo-secure-store
npm install @vectros-ai/react @vectros-ai/sdk react-intl @tanstack/react-query

1. Create the provider and wire the token cache, once, at app start.

import * as AuthSession from 'expo-auth-session';
import * as SecureStore from 'expo-secure-store';
import { VectrosClient } from '@vectros-ai/sdk';
import { getVectrosApiToken, setPartnerApiTokenMinter } from '@vectros-ai/react/core';
import { ExpoAuthProvider } from '@vectros-ai/react/providers/expo';

export const auth = new ExpoAuthProvider({
  issuer: 'https://cognito-idp.us-east-1.amazonaws.com/us-east-1_EXAMPLE',
  clientId: 'your-public-client-id',
  redirectUri: AuthSession.makeRedirectUri({ scheme: 'org.example.app' }),
  subjectToken: 'id_token',
  exchangeEndpoint: 'https://api.vectros.ai/v1/auth/token/exchange',
  authSession: AuthSession,
  secureStore: SecureStore,
});

// The cache calls the provider to mint, and re-mints on the first call within a minute of expiry.
setPartnerApiTokenMinter((tenantId, contextId) => auth.mintPartnerApiToken(tenantId, contextId));

// The exchange decides the tenant and context, so the cache key is only a label.
export const vectros = new VectrosClient({
  token: () => getVectrosApiToken('app'),
  environment: 'https://api.vectros.ai',
});

The Expo modules are passed in rather than imported by the package, so @vectros-ai/react itself depends on neither Expo nor React Native.

Which token to exchange (subjectToken). The token's iss and aud must match the issuer registration. An ID token's aud is always your client id; an access token's aud is the API it was issued for.

Identity providersubjectTokenRegister this audience
Amazon Cognito'id_token' (Cognito's access token has no aud claim)the app client id
Auth0'access_token', with extraParams: { audience: '<API identifier>' } and scopes: ['openid', 'email', 'profile', 'offline_access']the API identifier
Other OpenID Connectthe JWT whose aud you registeredthat aud

scopes replaces the default openid email profile, so keep those three when you add one. openid gives the ID token, and useAuth().user stays null for an ID token without an email claim. With 'id_token', the identity provider must also return an ID token when it refreshes.

One public client (no client secret) can serve iOS, Android and the web: register each platform's redirect on it.

2. Wrap the app in AuthProvider and sign in from a screen.

import { Button } from 'react-native';
import { AuthProvider, useAuth } from '@vectros-ai/react/core';
import { auth } from './auth';

export function Root({ children }: { children: React.ReactNode }) {
  return <AuthProvider provider={auth}>{children}</AuthProvider>;
}

export function SignInButton() {
  const { signInWithRedirect, handleRedirectCallback } = useAuth();
  return (
    <Button
      title="Sign in"
      onPress={async () => {
        await signInWithRedirect?.(); // opens the system browser; throws "Sign-in was cancelled." if the user closes it
        await handleRedirectCallback?.(); // reloads the signed-in user into AuthProvider
      }}
    />
  );
}

On a relaunch, AuthProvider restores the session from the stored refresh token without showing the sign-in page. Sign out with useAuth().signOut().

3. Call the API. Use the vectros client from step 1; every call gets a current st_* from the cache.

const page = await vectros.records.listRecords({ type: 'opportunity' });

Expected result: the user signs in once in the system browser; the app holds the provider's refresh token in the Keychain (iOS) or Keystore (Android) and every Vectros credential only in memory.

Firebase Authentication

Firebase signs users in through its own SDK, not a browser authorization-code flow, so ExpoAuthProvider does not apply. Sign in with the Firebase SDK, register the issuer https://securetoken.google.com/<project id> with the project id as its audience, and mint with the exchange call from /core:

import { clearVectrosApiTokenCache, exchangeSubjectToken, setPartnerApiTokenMinter } from '@vectros-ai/react/core';

setPartnerApiTokenMinter(async (_tenantId, contextId) =>
  exchangeSubjectToken('https://api.vectros.ai/v1/auth/token/exchange', await getFirebaseIdToken(), {
    ...(contextId ? { contextId } : {}),
    skipOwnRetry: true, // the cache retries a failed mint itself
  }),
);

// Every time Firebase reports a different user (or none), forget the bearers cached for the previous one.
onFirebaseAuthStateChanged(() => clearVectrosApiTokenCache());

where getFirebaseIdToken returns the signed-in user's current ID token from the Firebase SDK and onFirebaseAuthStateChanged is that SDK's auth-state listener. Clearing the cache on every auth-state change is required: nothing reloads a React Native app between users, and without it the next user's first calls are served the previous user's cached st_*. Check Firebase's own compliance documentation before using it for health data.

Rules for a mobile client

  • Sign in in the system browser, never in a webview. expo-auth-session uses the system browser. RFC 8252 requires it for native apps, and identity providers (Google among them) refuse or discourage embedded login pages.
  • Use a reverse-DNS custom scheme for the redirect (org.example.app), never a short word another app could claim. A claimed https redirect (an iOS universal link or an Android App Link) is stronger, but completing a sign-in through one depends on the OS version; test it on your oldest supported devices before you rely on it.
  • Keep the refresh token in secure storage, never in AsyncStorage. ExpoAuthProvider stores only the identity provider's refresh token, in expo-secure-store, split into values of at most 2,000 characters because some iOS releases refuse a keychain value above about 2,048 bytes. ID tokens, access tokens and st_* stay in memory. If the app refreshes in the background, pass keychainAccessible: SecureStore.AFTER_FIRST_UNLOCK; the default allows reads only while the device is unlocked.
  • Re-exchange when the app returns to the foreground and before background work. An st_* lasts at most one hour, and the cache re-mints on the first call within a minute of expiry. Call getVectrosApiToken('app') (or make any SDK call) before work that must not stall on a refresh.
  • Signing out is local and immediate; ending access everywhere is not. signOut() forgets the session and every cached st_*, and deletes the stored refresh token. If the device's secure storage refuses the delete (a locked keychain, for example), signOut() throws and AuthProvider keeps the user signed in, so the app can say so and retry; until a delete succeeds nothing restores the session in that run of the app. After the delete it asks the identity provider to revoke the token, without waiting, when the provider publishes a revocation endpoint. Amazon Cognito's discovery document does not, so for Cognito pass discovery with all three endpoints (https://<your domain>/oauth2/authorize, /oauth2/token and /oauth2/revoke). An st_* already issued keeps working until it expires (up to 3,600 seconds).
  • Signing out does not end the identity provider's browser session, so the next sign-in may complete without asking for credentials, as the same user. To let people switch accounts, pass extraParams: { prompt: 'login' }.
  • Suspending a user stops new exchanges at once (they are refused); an st_* issued before keeps working until it expires.
  • Give each provider instance its own storageKey if an app creates more than one (two identity providers, or two environments): instances that share the default vectros.auth overwrite each other's stored session.
  • iOS keeps keychain items after the app is uninstalled, so a reinstall can restore the previous session. Call signOut() on first launch after an install if that matters for your app.
  • An app launched offline keeps its session, but AuthProvider shows it as signed out until it re-reads. When the refresh cannot reach the identity provider, getCurrentUser() returns null and the stored refresh token is kept; only a refusal by the provider (invalid_grant) deletes it. AuthProvider reads the user once, at mount: call handleRedirectCallback() from useAuth() when the device reconnects or the app returns to the foreground, and it reads the user again without opening a browser.
  • Apple Guideline 4.8. If the app offers a third-party or social login, it must also offer an equivalent login that limits data to name and email, lets the user hide their email and does not track for ads without consent. Configure it in your identity provider (Sign in with Apple is the usual choice).
  • Rate limits apply per tenant and environment, shared by every device: see Rate limits.
  • The SDK on a device. The SDK streams chat, RAG and document-ask answers with fetch; React Native's built-in fetch may not stream response bodies, while Expo's expo/fetch does. React Native's TextDecoder and URL support has also been partial on older versions. None of this has been verified on a device against Vectros: test streaming before you depend on it.

Offline reads and safe retries

Most mobile apps need a cache and safe retries, not a sync engine:

  • Reads: persist your TanStack Query cache to device storage (for example with @tanstack/query-async-storage-persister) so the app opens with the last data it saw. Keep records that hold personal or health data out of an unencrypted persister. On sign-out, and whenever a different user signs in, call queryClient.clear() and remove the persisted cache (the persister's removeClient()), or the next user sees the previous user's records.
  • Writes: send the version you last read as expectedVersion on an update. If the record changed while the device was offline, the API answers 409; re-read it, merge, and retry. See Make the update conditional.
  • Queue writes made offline and replay them in order when the device reconnects; each one still carries its expectedVersion.

Send the invitation's acceptUrl as an https link your app claims (a universal link or App Link), so a tap opens the app when it is installed and your website when it is not. In the app, after the user signs in, call acceptInvite(inviteToken) from useAuth() with the token from the link. See Invite a sub-user by email.

Let users delete their own account

Apps in the App Store and Google Play that create accounts must let users delete them from inside the app. Vectros lets the signed-in user delete their own account in your app with their own token, so the app needs no server for it.

Turn it on for your app context (a root key or the provisioning capability). It is off by default:

PUT /v1/app-contexts/my-app
{ "allowSelfErasure": true, "selfErasureGraceDays": 7 }

selfErasureGraceDays is the waiting period before the deletion runs, 0 to 30 days (7 when unset); during it the user can cancel. If your identity provider's registration has an API as its audience (as with Auth0), also list your app's client ids in the issuer's acceptedIdTokenClientIds; Amazon Cognito and Firebase need nothing there.

In the app:

  1. Confirm it's the user. Ask the identity provider to sign the user in again, and take the new ID token (not the access token): with OpenID Connect providers, request max_age=0 (the token then carries auth_time); with Firebase, call reauthenticateWithCredential and then getIdToken(true).
  2. Request the deletion within 5 minutes of that sign-in, with the user's own Vectros token (a scoped st_* token bound to the user, as the token exchange issues; root and other API keys are refused): POST /v1/me/erasure with { "idToken": "<the new ID token>" } (requestSelfErasure in the SDKs). The answer is 202 with the request and scheduledFor. The ID token that requested a deletion cannot be used again.
  3. Show it until it runs. On launch, call GET /v1/me/erasure (getPendingSelfErasure); while one is pending, show when it will happen and offer to cancel. Cancelling needs a fresh sign-in too: sign the user in again as in step 1 and send the new ID token to POST /v1/me/erasure/{id}/cancel (cancelSelfErasure) with { "idToken": "..." }. Once the deletion has started it can no longer be cancelled. Because cancelling needs a sign-in, a pending deletion can no longer be cancelled if the app's identity provider registration is deactivated or changed, or the user's account there is deleted, during the waiting period: it then runs as requested. Requesting and cancelling are never refused because your Vectros account is over its monthly credit limit.
  4. Delete the sign-in account in your identity provider when the deletion has completed (see the checklist below). Deleting it earlier would stop the user signing in to cancel during the waiting period.

What is deleted: the user's data in your app context (what they solely own) and their access to it. Other app contexts in your tenant are other apps and are not touched. The user's identity is removed too only when your app context is the tenant's only one. The account owner of your Vectros account cannot use this; that account is closed from the developer portal.

The emails. Vectros emails the user when the deletion is scheduled and when it completes, to the email in the ID token, and only when the identity provider marks it verified (email_verified). With no verified email, no email is sent: show the scheduled deletion on every launch. A deletion can be cancelled only with a fresh sign-in by the user, never with a Vectros API key alone, so if someone else had the user's session, the scheduled email is what lets the real user notice, sign in and cancel. (Whoever administers your identity provider can sign in as any of its users, so this protects against a leaked API key, not against your identity provider's own administrators.) Send ID tokens from the app straight to Vectros, not through your server: an ID token used to cancel stays valid for a new request for the rest of its 5 minutes, and the user would then get another "scheduled" email and have to cancel again.

Refusals carry an errorCode, for example SELF_ERASURE_NOT_ENABLED (turned off for this app), SELF_ERASURE_PROOF_INVALID (sign in again and retry), SELF_ERASURE_ALREADY_PENDING, or SELF_ERASURE_ALREADY_STARTED on a cancel, and SELF_ERASURE_PROOF_REUSED when the ID token was already used to request the deletion.

Store submission checklist

Both stores ask what data the app collects and how it is protected. What you store in Vectros is yours to declare; these are the parts Vectros and the sign-in flow contribute.

  • Apple privacy manifest and nutrition label, and the Google Play Data safety form: declare the account data your identity provider collects (email, name) and the user content you store in Vectros. Vectros serves its API only over HTTPS (a plain-HTTP request is redirected, not served), so you can declare the data encrypted in transit.
  • Account deletion (Apple Guideline 5.1.1(v) and Google Play). An app that creates accounts must let users delete their account and its data from inside the app, and Google Play also asks for a web link where users can request deletion without the app. Five parts:
    • The sign-in account lives in your identity provider; prefer one that lets the app delete it. With Amazon Cognito, add aws.cognito.signin.user.admin to scopes and call DeleteUser with auth.getAccessToken(); some providers need a server-side call instead.
    • The user's data in Vectros: turn on allowSelfErasure for your app context and let the user delete their account from the app (Let users delete their own account). It deletes the user's data and access in your app's context only; other app contexts are other apps. Google Play's web deletion link can run the same flow from a web page that signs the user in with your identity provider. (A server holding a root key can still use end-subject right-to-erasure.)
    • A verified email. The deletion notices go to the verified email your identity provider puts in the ID token. Make sure it releases one (email, email_verified: true); without it no notice is sent.
    • Model a person's own data so erasure finds it. Erasing a user deletes only what that user solely owns. A record that also carries another owner's stamp (an organisation, a client or any other scope) is shared, so it is kept. Give the types that hold a person's own data no other owner's stamp, or declare publicView.ownedBy: [userId] on a public type so erasing the user deletes it. Put data an organisation owns (its profile, its listings) under the organisation, not under one staff member's user, or that person's deletion takes it with them.
    • Sign in with Apple: if you offer it, also revoke the user's Apple tokens when they delete their account, as Apple asks.
  • Health data: if your tenant handles protected health information, use an identity provider covered by your business associate agreement (Amazon Cognito is eligible; Firebase Authentication is not; check your provider's current coverage), keep cached records in the app sandbox with the platform's file protection, and keep personal data out of logs and crash reports.

Reference

ExportFromWhat it is
ExpoAuthProviderproviders/expoThe sign-in provider: signInWithRedirect, handleRedirectCallback, signOut, getCurrentUser, getIdToken, getAccessToken, exchangeToken, mintPartnerApiToken, acceptInvite.
ExpoAuthProviderConfigproviders/expoissuer, discovery? (used instead of the issuer's discovery document), clientId, redirectUri, scopes? (default openid email profile), extraParams?, subjectToken, exchangeEndpoint, storageKey? (default vectros.auth), keychainAccessible?, authSession, secureStore.
getVectrosApiToken(tenantId, contextId?, identityOverride?)coreA current st_* for that cache slot, minted on first use and re-minted on the first call within a minute of expiry; concurrent callers share one mint.
setPartnerApiTokenMinter(fn)coreSets how the cache mints; wire it to ExpoAuthProvider.mintPartnerApiToken.
exchangeSubjectToken(endpoint, token, options?)coreOne POST /v1/auth/token/exchange call; for a minter of your own.
clearVectrosApiTokenCache()coreForgets every cached st_*. ExpoAuthProvider calls it on sign-in and sign-out.

Errors. The provider's sign-in, sign-out and exchange calls fail with an AuthError (import { AuthError } from '@vectros-ai/react/core'): NETWORK_ERROR when a request cannot be sent, INVALID_CREDENTIALS when there is no session to exchange, and UNKNOWN otherwise, with the message naming the cause (Sign-in was cancelled., Another sign-in is already in progress., Secure storage failed: …, or Token exchange failed: <status> <error>).

What has been tested. A headless suite on React Native's Jest preset proves that /core and providers/expo load without the web UI kit, that the token cache mints, caches and reads against the live API, and that the Expo provider's exchange reaches the API. It runs on Node, so it does not exercise Metro, Hermes, React Native's networking, a device or simulator, or a successful exchange with a real identity provider.