@offline-protocol/id-react-native
v0.4.0
Published
React Native SDK for Offline Protocol
Readme
@offline-protocol/id-react-native
React Native SDK for Offline Protocol identity: email OTP login, session restore, profiles, connections, and optional OfflineID credentials.
License
MIT — see LICENSE.
Install
npm install @offline-protocol/id-react-nativePeer dependencies
Install these in your app:
npm install @offline-protocol/core @react-native-async-storage/async-storage axios react-native-svgreact^18 or ^19react-native
Setup
Wrap your app with OfflineAppProvider and pass your project / app ID
(from the Offline developer portal):
import { OfflineAppProvider } from "@offline-protocol/id-react-native";
export default function App() {
return (
<OfflineAppProvider appId="app_xxxxxxxx">
{/* your screens */}
</OfflineAppProvider>
);
}The provider restores the session from AsyncStorage on launch, sets API headers, and exposes auth state to the tree.
Authentication
Use useAuth() for login, logout, and user state:
import { useAuth } from "@offline-protocol/id-react-native";
function SignInScreen() {
const {
user,
token,
loading,
loginWithModal,
logout,
sendCode,
verifyCode,
registerUsername,
isUsernameAvailable,
refreshUser,
sessionRestoreError,
} = useAuth();
if (loading) return null;
if (!user) {
return <Button title="Log in" onPress={loginWithModal} />;
}
return (
<>
<Text>Signed in as {user.email}</Text>
<Button title="Log out" onPress={logout} />
</>
);
}loginWithModal()— opens the built-in bottom-sheet flow (email → OTP → username if needed).sendCode/verifyCode— use directly if you build a custom UI instead of the modal.sendPhoneCode/verifyPhoneCode— the same, by SMS. The number must be E.164 (+18777804236). A phone number signs in to its own account, never to one created with an email address. The modal is email-only.registerUsername— after first login when the account has no username.sessionRestoreError— set when a stored token could not be restored (e.g. network or 401).sessionTrust— how far the server trusts the app on this session:{ trust, reason?, status? }withtrust"hardware","degraded"or"development", ornull(see Session trust).
Headless auth (no modal)
import { isOfflineIdError } from "@offline-protocol/id-react-native";
try {
await sendCode("[email protected]"); // resolves to true
const account = await verifyCode("[email protected]", "123456");
if (!account) {
// wrong or expired code
}
} catch (e) {
if (isOfflineIdError(e)) showError(e.message); // the server's reason
}
// or by SMS
await sendPhoneCode("+18777804236");
const account = await verifyPhoneCode("+18777804236", "123456");On success, token and user are updated and the token is persisted.
Errors
sendCode and sendPhoneCode resolve to true, and throw OfflineIdError
when the server refuses the request or does not answer. verifyCode and
verifyPhoneCode resolve to null for a wrong or expired code, and throw
OfflineIdError for anything else. The built-in login sheet shows the error's
message.
| Field | Meaning |
| ----- | ------- |
| code | The server's error code, such as app_credentials_required, invalid_app, origin_not_allowed, attestation_required, attestation_failed, attestation_key_unknown, attestation_not_configured, development_mode_required, code_requests_limited, development_sign_ins_limited or degraded_sign_ins_limited. development_build_required when a build without @expo/app-integrity's native module (Expo Go) was refused. network_error when no response arrived. |
| status | HTTP status; absent when no response arrived. |
| message | The server's message (for development_build_required, the SDK's, with the commands). |
| missing | What the app is missing: native_registration, attestation, credential or development_mode. |
| nextSteps | Commands that fix it, such as offline apps native add ios .... |
| docs | A page that explains it. |
| appId | The application the server checked. |
| reason | Why an attestation was refused, when the server says. |
| serverCode | The server's code when the SDK replaced it with development_build_required. |
| Code | Status | What to do |
| ---- | ------ | ---------- |
| development_mode_required | 403 | A simulator, emulator or Expo Go was refused: offline apps native dev-mode on --hours 24 --app-id <id> (or use a separate development application if this one is marked production). |
| development_build_required | 403 | Expo Go, or a build made before installing @expo/app-integrity: npx expo install @expo/app-integrity, then npx expo run:ios / npx expo run:android (or eas build --profile development); or turn on development mode as above. |
| development_sign_ins_limited | 429 | The app's hourly cap for development-mode sign-ins was reached. |
| degraded_sign_ins_limited | 429 | The hourly cap for Android devices that cannot fully attest was reached (per app, and per device). |
| code_requests_limited | 429 | The hourly cap for email code requests without an attestation was reached. |
In development builds each refused request also logs one console.warn with
the code, the message and the next steps, so the commands to run are in the
Metro log.
Manual API setup
If you do not use OfflineAppProvider, call before any API use:
import { setAppId, setAuthToken } from "@offline-protocol/id-react-native";
setAppId("app_xxxxxxxx");
setAuthToken(jwt);Guest sessions: one guest per install
A guest needs no sign-in, and each guest is a billed monthly active user of your app. Create one once per install, then resume it on every launch with the saved token; creating a new guest on every launch counts as a new user each time.
import { useGuestSession } from "@offline-protocol/id-react-native";
function Home() {
const { session, loading, error } = useGuestSession();
// session.token - send as `Authorization: Bearer` to APIs that accept guests
// session.guestId, session.resumed (true when the same guest continued)
}Without React: await getOrCreateGuestSession(). It saves the token and guest
id in AsyncStorage, sends the saved token back on later launches, and keeps the
token the server returns (it can be a fresh token for the same guest, or a new
guest if the old one could not be resumed). If the server cannot be reached it
returns the saved guest (session.source === "stored"). getStoredGuestSession()
reads the saved guest without calling the server, and clearGuestSession()
forgets it.
When the same install signs in by email code, the saved guest token is sent with the sign-in so the guest and the account count as one person (Privy sign-in cannot carry it).
App attestation (iOS App Attest, Android key attestation)
Your appId is public, so by itself it proves nothing. If your app is
registered with iOS bundle IDs / Android package names in the developer portal
(Native apps tab), each sign-in from your native app, and each new guest,
can prove it comes from your app. Resuming a guest needs no proof.
The SDK runs the protocol (challenge, binding, key registration, retries); you
give it the native calls, because they need a native module (use a library, or
write a small bridge to DCAppAttestService / the Android Keystore):
import { OfflineAppProvider, AttestationProviders } from "@offline-protocol/id-react-native";
// With Expo, use createExpoAppIntegrityProviders instead (see "Expo" below).
const attestation: AttestationProviders = {
// A successful login alone does not confirm attestation in report mode.
onStatus: (status) => console.info("Attestation:", status.state, status.message),
ios: {
isSupported: () => AppAttest.isSupported(),
generateKey: () => AppAttest.generateKey(), // -> key id
attestKey: (keyId, clientDataHash) => AppAttest.attestKey(keyId, clientDataHash), // base64 in, base64 out
generateAssertion: (keyId, clientDataHash) => AppAttest.generateAssertion(keyId, clientDataHash),
},
androidKey: {
isAvailable: () => KeyAttestation.isSupported(),
// Generate a fresh Keystore EC key with setAttestationChallenge(<the 32 bytes behind
// `challengeHash`, base64>), return its certificate chain (each cert DER, base64, leaf
// first), then delete the key.
attest: (challengeHash) => KeyAttestation.attest(challengeHash),
},
};
<OfflineAppProvider appId="app_..." attestation={attestation}>{children}</OfflineAppProvider>With attestation set, sendCode / sendPhoneCode, verifyCode /
verifyPhoneCode and Privy sign-in each attach their own attestation (a fresh
challenge each time), and a new guest attaches one when the server asks for
it. A refused attestation is retried once with a fresh one, and an iOS key the
server no longer knows is registered again.
A device that cannot attest says why instead of sending a proof:
"attestation": { "platform": "ios" | "android", "unavailable": <reason> },
on code requests, sign-ins and new guests, and the server decides. Without
attestation providers nothing is sent, as before.
| unavailable | When | Server |
| ------------- | ---- | ------ |
| simulator | iOS: the provider's isSupported() is false (the Simulator), or isSimulator() is true | Development mode only |
| emulator | Android: isSimulator() is true | Development mode only |
| expo_go | The native module is missing (Expo Go, or a build made before installing it) | Development mode only |
| unsupported | Android: isAvailable() is false; iOS: isSupported() is false and isSimulator() returned false | Android: degraded trust; iOS: development mode only |
| keystore_error | Android: the provider threw | Degraded trust |
isSimulator is an optional hint on AttestationProviders
(() => boolean | Promise<boolean>), for example () => !Device.isDevice
with expo-device. Android emulators are only recognised through it; without
it an emulator tries to attest with its software keystore.
A native app needs attestation to sign in. Without attestation, requests
carry no proof: an email code request is still accepted for an app with at
least one native signing identity registered (a limited number per app per
hour, code_requests_limited beyond that), but SMS code requests and the
sign-in itself (verifyCode) are refused with attestation_required.
Configure your application in the developer portal's Native apps tab:
iOS: register each bundle ID with its Apple App ID prefix (usually the 10-character Team ID). Preserve the exact bundle ID case used in your signed build. Enable the App Attest capability (
com.apple.developer.devicecheck.appattest-environment) in Xcode. For Xcode development builds, enable Allow development builds for this application (offline apps native dev-builds on).Android: register each package name with the SHA-256 fingerprint of the certificate your app is signed with (Play Console → App integrity → App signing, or
keytool -list -v). Nothing secret is uploaded. Debug builds use another certificate: add its fingerprint to the same package to attest from them. Devices with software-only keystores, an unlocked bootloader or a custom verified-boot key sign in at thedegradedtrust level (see below).Play Integrity is still supported through the
androidprovider (isAvailable,getPackageName,requestIntegrityToken), but only where the server hasPLAY_INTEGRITY_ENABLEDand your app uploaded a Google service-account key. When bothandroidKeyandandroidare given,androidKeyis used. There is no per-application enforcement setting: Offline Protocol decides for every application, and the production API enforces it.A sign-in from a native app without a valid proof is refused (403
attestation_required), and so is a native sign-in to an application with no native app registered. A request that names an app and carries no credential at all is refused by the gateway (401app_credentials_required, withmissingandnextSteps). Register every app you ship.Check that a fresh sign-in from your signed release build reports
verified(onStatus, ordata.attestation.statusin the sign-in response).Browsers and servers never need a proof. A sign-in from a browser on one of your allowed origins (Domains) and a request from your server with an API key are accepted without one, so one application can serve web, server and native clients.
The server uses each app's own signing identities and credentials. Developers do not need changes to backend environment variables. Settings may take up to 60 seconds to reach the server's registry cache.
Simulators, emulators and Expo Go: development mode
Simulators, emulators and Expo Go cannot prove they are your app. Turn on development mode for the application while you test on them:
offline apps native dev-mode on --hours 24 --app-id app_xxxxxxxx # 1 to 72 hours; off: offline apps native dev-mode offWhile it is on, email code requests, sign-ins and new guests are accepted
without a proof (never SMS codes), up to a number of sign-ins per app per hour
(development_sign_ins_limited beyond that). It ends by itself, every change is
recorded (offline apps native history), and sessions signed in under it have
sessionTrust.trust === "development" and stop working when it ends. It cannot
be turned on for an application marked production
(offline apps native production on); use a separate development application.
While it is off these devices are refused with development_mode_required.
Android devices that cannot fully attest
An Android device whose attestation is well-formed and bound to this sign-in,
app and registered signing certificate, but which cannot be fully trusted (key
in software, unlocked bootloader, a chain that does not end at Google's
hardware roots, an expired or revoked attestation certificate, or no key
attestation at all: unsupported / keystore_error), signs in at the
degraded trust level, capped per app and per device
(degraded_sign_ins_limited). SMS codes are not sent to them. A wrong
challenge, package or signing certificate is still refused. To refuse these
devices: offline apps native degraded refuse.
Session trust
The sign-in response says how the app was trusted
(data.attestation = { status, trust, reason? }). The SDK passes it on:
useAuth().sessionTrust:{ trust, reason?, status? }for the signed-in session, kept with the session across restarts;nullwhen signed out or when the server did not say.onStatus:{ state: "verified" | "degraded" | "development", trust, reason?, message }after a sign-in.
| trust | Meaning |
| ------- | ------- |
| hardware | Verified by App Attest or hardware-backed key attestation. |
| degraded | An Android device that could not fully attest; reason says why. |
| development | Signed in under development mode; ends when it does. |
const { sessionTrust } = useAuth();
if (sessionTrust?.trust === "degraded") {
// for example, ask for a second factor before a payment
}Expo
createExpoAppIntegrityProviders maps
@expo/app-integrity to
the SDK's providers. The SDK does not depend on Expo; pass a function that
loads the module (or the module itself).
npx expo install @expo/app-integrity expo-deviceimport * as Device from "expo-device";
import {
OfflineAppProvider,
createExpoAppIntegrityProviders,
} from "@offline-protocol/id-react-native";
// A loader, so that Expo Go (which does not have the native module) does not
// crash on the import. `import * as AppIntegrity from "@expo/app-integrity"`
// and passing the module also works, in development and release builds only.
const attestation = createExpoAppIntegrityProviders(
() => require("@expo/app-integrity"),
{
isSimulator: () => !Device.isDevice, // simulators and emulators say so
onStatus: (s) => console.info("Attestation:", s.state, s.trust ?? "", s.message),
}
);
export default function App() {
return (
<OfflineAppProvider appId="app_xxxxxxxx" attestation={attestation}>
{/* your screens */}
</OfflineAppProvider>
);
}@expo/app-integrity is a native module, so it needs a development build or a
release build (npx expo run:ios, npx expo run:android, EAS Build); it is not
in Expo Go.
Expo Go. Where the native module is missing (Expo Go, or a build made
before installing it), the loader throws or the module is null/undefined;
the helper then reports unavailable: "expo_go" and logs one development
warning. Requests succeed only while the app's development mode is on
(offline apps native dev-mode on --hours 24). Otherwise a refusal throws
OfflineIdError with code development_build_required (the server's code in
serverCode) and these nextSteps:
npx expo install @expo/app-integrity
npx expo run:ios # or: npx expo run:android, or: eas build --profile development
offline apps native dev-mode on --hours 24 --app-id app_xxxxxxxx # to keep using Expo Go or a simulatoriOS: add the App Attest entitlement in
app.json, then rebuild:{ "expo": { "ios": { "bundleIdentifier": "com.example.app", "entitlements": { "com.apple.developer.devicecheck.appattest-environment": "production" } } } }Register the bundle ID with your Apple Team ID (
offline apps native add ios --bundle-id com.example.app --team-id ABCDE12345). With the valuedevelopment(or without the entitlement, for builds run from Xcode), App Attest uses Apple's development environment; accept those proofs withoffline apps native dev-builds on(the portal's Allow development builds). App Attest does not run in the iOS Simulator: it sendsunavailable: "simulator", which needs development mode.Android: register the package with the SHA-256 of each certificate you sign with:
offline apps native add android --package com.example.app --sha256 <fingerprint>, oroffline apply --detect, which readsapp.jsonand your keystores. Debug builds are signed with the debug keystore and release builds with your upload or Play app-signing key: register each fingerprint you test with (keytool -list -v -keystore android/app/debug.keystore, or Play Console → App integrity → App signing). Emulators cannot attest: withisSimulatorthey sendunavailable: "emulator", which needs development mode. A real device without hardware key attestation signs in at thedegradedtrust level.
On Android, @expo/app-integrity sets the Keystore attestation challenge from a
string, so the helper attests the binding string
(<challenge>.<appId>.sign-in) itself rather than its SHA-256. auth-service
accepts this form from the release that supports it. The helper keeps one key
under the alias offline-id-attestation and replaces it on each attestation.
Its Play Integrity functions are not used.
Set up an app from the command line
The offline CLI (@offline-protocol/cli) registers what the API checks, and
every command is idempotent and accepts --json, so a coding agent can run
them:
offline login --email [email protected] # sends a code; rerun with --code <code>
offline apps status --app-id app_xxxxxxxx # what is registered, what is missing, what to run
offline apps native detect # reads app.json, the Xcode project, build.gradle, keystores
offline apps native add ios --bundle-id com.example.app --team-id ABCDE12345
offline apps native add android --package com.example.app --sha256 AB:CD:...
offline apps native dev-builds on # accept App Attest proofs from Xcode development builds
offline apps native dev-mode on --hours 24 # simulators, emulators, Expo Go (1 to 72 hours)
offline apps native degraded allow|refuse # Android devices that cannot fully attest
offline apps native production on # mark the app production (ends and blocks development mode)
offline apps origins add https://example.com # for web apps on the same application
offline apply --detect # converge offline.config.json's "app" blockAn OfflineIdError's nextSteps lists the commands for the problem it reports.
See App attestation.
Profiles and connections
import { useProfiles, useConnections } from "@offline-protocol/id-react-native";
const { profiles, profileCount, searchProfile } = useProfiles();
const { connections, addConnection, removeConnection, setLocationSharing } =
useConnections();Location sharing
Each item in connections is seen from the signed-in user's side:
| Field | Meaning |
| ----- | ------- |
| id | Connection ID |
| peer | The other profile's username |
| sharingLocationWithThem | You share your location with peer |
| sharingLocationWithMe | peer shares their location with you |
Location sharing is per connection and one way, and it is off by default,
including for connections made before it existed. A peer's location is only
returned to you (GET /connections/{username}/locations) once they turn
sharing on for your connection.
<Switch
value={c.sharingLocationWithThem}
onValueChange={(on) => setLocationSharing(c.id, on)}
accessibilityLabel={`Share my location with ${c.peer}`}
/>setLocationSharing(connectionId, share, opts?) turns sharing of your own
location with that peer on or off
(PUT /connections/by-id/{id}/location-sharing). It is idempotent and never
changes the peer's side. The connections list updates at once and rolls
back if the request fails. It resolves to the updated connection, or null
on failure. Pass { username } only when you own both profiles in the
connection, to say which side is yours.
OfflineID credential (optional)
Opt-in hook; does not run until you call it:
import { useOfflineIdCredential } from "@offline-protocol/id-react-native";
const { getCredential, getIssuerKey, loading, error } = useOfflineIdCredential();
const res = await getCredential();Session restore without the provider
import { setAppId, fetchSessionFromToken } from "@offline-protocol/id-react-native";
setAppId("app_xxxxxxxx");
const user = await fetchSessionFromToken(storedJwt);Related packages
- Proof of Location:
@offline-protocol/pol—await pol.location.verify({ claim })(recommended); passuseAuth().tokenviagetSessionTokenon init.
Contributing
See CONTRIBUTING.md for building and publishing the package from source.
