App attestation (React Native)
For React Native developers, bare or Expo, adding attestation to an app that already uses TrustPin pinning (@trustpin/react-native). At the end of this page, your fetch, XMLHttpRequest and axios requests carry a token your backend can verify, on iOS and Android.
How it works
@trustpin/react-native-attest wraps the native attestation modules: TrustPinAttestKit on iOS and kotlin-attest on Android. The device attests a key once with the attestation verifier you run, using Apple App Attest, or Android Key Attestation and Google Play Integrity as your policy asks. The verifier answers with a short-lived signed token, which the SDK renews cheaply with the same key. React Native’s networking is native, so fetch, XMLHttpRequest and axios requests to the hosts you choose carry the token in the TrustPin-Attestation header with no change to your code, and your backend verifies it.
The SDK never blocks or fails your requests. When no token is ready within a short, bounded time, the request goes out without the header, and your backend decides what to do.
Like pinning, attestation starts in native code, before JavaScript runs. Your JavaScript only binds tokens to the session and observes the state:
There is no JavaScript setup call. A JavaScript call made when the native start never ran rejects with NOT_SET_UP.
Requirements
| Item | Requirement |
|---|---|
| React Native | 0.85 or later, New Architecture only |
@trustpin/react-native | Set up in your app, at the same version as @trustpin/react-native-attest |
| iOS | 15 or later |
| Android | API 25 or later, Kotlin 2.3.0 or later |
| Expo | A development build. Expo Go can’t run attestation, which is native code |
| Verifier | Deployed, reachable over HTTPS, with a published policy |
| Devices | iOS: a device that supports App Attest. Android: hardware-backed key attestation, and Google Play only if your policy uses Play Integrity. Simulators and emulators need a debug token |
SDK and verifier compatibility
| SDK | Verifier |
|---|---|
@trustpin/react-native-attest 7.1.x | Contract version 2 or newer: verifier 1.0.0 or later |
With an older verifier the state is failed with VERIFIER_INCOMPATIBLE, and no header is sent until the verifier is upgraded. The app recovers on its own at the next attempt, with no update or reinstall.
Before you write code: the policy
Your verifier checks every attestation against a signed policy, which you manage on the project’s Attestation page in the TrustPin console and publish with Sign and publish. These settings matter for a React Native app; Setting up apps and the policy explains each one.
| Setting | What to set |
|---|---|
| Attest Apple apps | Team ID and Bundle ID of the iOS app |
| Accept development builds | On while you test development builds on an iPhone or iPad |
| Attest Android apps | Package name and every Signing certificate SHA-256: your debug key, and the Play app signing key for builds from Google Play |
| Evidence (Android) | Key Attestation only is the simplest start. The other options use Play Integrity, which needs a Google Cloud project number |
| Require token binding | On once your API checks the binding. See Bind tokens to the user’s session |
| Allow debug tokens | On if you test on simulators or emulators. Only your staging verifier, which has debug token hashes, accepts them |
| Mode | Monitor (recommended to start), then Enforce |
Register your verifier’s domain in your TrustPin project. Calls to the verifier are pinned, and in strict mode an unregistered host is never reached. See Registering the verifier’s domain.
Install
-
Add both packages, at the same version:
npm install @trustpin/react-native @trustpin/react-native-attestThey bring the native 7.1.x modules with them (7.1.1 or later on Android).
-
iOS: enable App Attest on the App ID in the Apple Developer portal. In a bare app, also add the App Attest capability to the app target in Xcode; the Expo plugin adds the entitlement for you (see Configure). The entitlement is:
<key>com.apple.developer.devicecheck.appattest-environment</key> <string>development</string>Use
developmentfor development builds, which needs Accept development builds on, andproductionfor TestFlight and the App Store. -
Android:
minSdk25 and the Kotlin Gradle plugin 2.3.0, as the pinning setup already requires. The Expo plugins set both.
Configure
Expo
List the attestation plugin next to the pinning one in app.json or app.config.js:
{
"expo": {
"plugins": [
["@trustpin/react-native", {
"organizationId": "<organization id>",
"projectId": "<project id>",
"publicKey": "<project public key>"
}],
["@trustpin/react-native-attest", {
"verifierUrl": "https://attest.example.com",
"attestedHosts": ["api.example.com"],
"appAttestEnvironment": "development"
}]
]
}
}Then generate the native projects and build a development build:
npx expo prebuild
npx expo run:ios # or: npx expo run:androidnpx expo prebuild adds the attestation keys to the configuration files the pinning plugin writes (keys already there are kept), sets the App Attest entitlement, and adds the native start call right after the pinning one on both platforms.
| Prop | Type | Notes |
|---|---|---|
verifierUrl | string | Your verifier, https:// on a host name, without credentials, query or fragment. Set it together with attestedHosts, or set neither when your pinning configFiles already carry the keys |
attestedHosts | string[] | One to fifty hosts that receive the header: exact names, or *.example.com for exactly one label. No other host ever receives it |
googleCloudProjectNumber | string of digits | Android, only when the policy uses Play Integrity |
appAttestEnvironment | development | production | The iOS entitlement’s value. Defaults to production |
logLevel | none | error | warning | info | debug | Passed to the native start call. Defaults to error |
To use development for development builds and production for store builds, set the prop from an environment variable in app.config.js.
Bare React Native
Add the attestation keys to the configuration files your pinning setup already reads.
iOS, ios/<YourApp>/TrustPin-Info.plist:
<key>AttestVerifierURL</key>
<string>https://attest.example.com</string>
<key>AttestedHosts</key>
<array>
<string>api.example.com</string>
</array>Android, android/app/src/main/assets/trustpin.json:
{
"organization_id": "<organization id>",
"project_id": "<project id>",
"public_key": "<project public key>",
"attest_verifier_url": "https://attest.example.com",
"attested_hosts": ["api.example.com"]
}| Key (plist / JSON) | Required | Notes |
|---|---|---|
AttestVerifierURL / attest_verifier_url | Yes | Your verifier’s base URL: https:// on a host name, without credentials, query or fragment. A deployment path is allowed. IP addresses are refused |
AttestedHosts / attested_hosts | Yes | One to fifty host names that receive the header, each exact or *.example.com for exactly one label |
google_cloud_project_number | Android, only for Play Integrity | Your Google Cloud project number (string or number). Leave it out otherwise: with a number, the app contacts Google Play services from setup on |
For Play Integrity, the same number goes in the policy’s Google Cloud project number, and your verifier’s operator enables Play Integrity on the verifier. See Android apps.
Set up
1. Start attestation natively, right after pinning. With Expo, npx expo prebuild has already done this; skip to step 2.
iOS, AppDelegate.swift:
import TrustPinReactNative
import TrustPinReactNativeAttest
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
) -> Bool {
TrustPinReactNative.start()
TrustPinReactNativeAttest.start() // or: .start(logLevel: .debug)
// ...existing React Native setup...
}Android, MainApplication.kt:
import cloud.trustpin.reactnative.TrustPinReactNative
import cloud.trustpin.reactnative.attest.TrustPinReactNativeAttest
override fun onCreate() {
TrustPinReactNative.start(this)
TrustPinReactNativeAttest.start(this) // or: .start(this, TrustPinAttestLogLevel.DEBUG)
super.onCreate()
loadReactNative(this)
}For the log level, import cloud.trustpin.kotlin.attest.TrustPinAttestLogLevel. Then run cd ios && pod install and rebuild the app.
The start call reads the configuration file, validates it and loads a device key from an earlier launch. It makes no verifier call, and a failure never crashes the app: it shows in the logs and the state, and requests go out without the header.
2. Bind and prefetch from JavaScript, once when the app starts, for example from your root component’s useEffect:
import TrustPinAttest from '@trustpin/react-native-attest';
export async function startAttestation(): Promise<void> {
try {
await TrustPinAttest.bindToHeader('Authorization');
await TrustPinAttest.prefetch();
} catch (error: any) {
console.warn('Attestation:', error.code); // NOT_SET_UP: the native start never ran
}
}prefetch() starts attestation in the background, so the first request doesn’t wait. It never rejects.
Check: with a debug log level, read the state. It reaches ready:
const state = await TrustPinAttest.getState();
console.log(state); // { status: 'ready', expiresAtMs: … }On a simulator or emulator, pass a debug token first.
Bind tokens to the user’s session
A bound token is valid only with the session it was issued for. Only a SHA-256 of the value leaves the device; the value itself is never sent or logged.
| Mode | Call | Use it when |
|---|---|---|
| Header binding | await TrustPinAttest.bindToHeader('Authorization') | Your requests carry the session in a header. Each request’s token is bound to that header’s value |
| Fixed binding | await TrustPinAttest.setTokenBinding(sessionId) | You have one session value, or a transport without such a header (gRPC, WebSockets) |
- Each mode clears the other.
setTokenBinding(null)removes the fixed binding only.bindToHeader(null)stops header binding and also clears a fixed binding, so it removes every binding. - A binding change renews the token with the existing device key. It is not a new attestation.
prefetch()with header binding attests early but can’t bind yet; the first request carrying the header renews the token once more, cheaply.- With Require token binding on, no token exists until a binding is known: the state is failed with
BINDING_REQUIREDand anullretryAtMs. That’s expected before sign-in, and attestation resumes as soon as a binding is set.
Send the header
A. fetch, XMLHttpRequest and axios: nothing to change. Requests to the attested hosts carry the header, added natively:
const response = await fetch('https://api.example.com/v1/items', {
headers: { Authorization: `Bearer ${session}` },
});B. Another HTTP client that doesn’t use React Native’s networking. Ask for the headers and add them yourself. attestationHeaders never rejects; an empty object means no header for this request:
const url = 'https://api.example.com/v1/items';
const headers = { Authorization: `Bearer ${session}` };
Object.assign(headers, await TrustPinAttest.attestationHeaders(url, { method: 'GET', headers }));C. Anything else (gRPC, some WebSocket clients). Send await TrustPinAttest.getToken() in the TrustPin-Attestation header (TrustPinAttest.headerName).
These rules apply to every path:
- HTTPS and attested hosts only. Other requests never get the header.
- A header the request already carries is kept. The SDK adds its own only when there is none.
- Redirects. A redirect never carries the header to another host: each redirect gets the header for its own URL only.
- Bounded wait. When no token is ready in time, the request goes out without the header.
React Native uses the default TrustPin instance only.
Sensitive operations
For an operation your backend must not accept on a reused token alone, such as a payment, send an assertion next to the token. It binds the device’s attested key to a SHA-256 digest of your choice, typically the request body. React Native has no built-in digest API: sha256 below is any function that returns the 32-byte digest of a Uint8Array, from your crypto library, or the small sha256.ts in the example app.
import TrustPinAttest from '@trustpin/react-native-attest';
import { sha256 } from './sha256';
export async function sendTransfer(session: string): Promise<Response> {
const url = 'https://api.example.com/v1/transfer';
const body = JSON.stringify({ amount: '1.00', to: 'demo' });
const headers: Record<string, string> = {
Authorization: `Bearer ${session}`,
'Content-Type': 'application/json',
};
// With header binding, ask for this request's token first, so it is bound
// to this Authorization value; then add the token and the assertion.
Object.assign(headers, await TrustPinAttest.attestationHeaders(url, { method: 'POST', headers }));
Object.assign(headers, await TrustPinAttest.assertionHeaders(sha256(new TextEncoder().encode(body))));
return fetch(url, { method: 'POST', headers, body });
}assertionHeaderstakes the digest as 32 bytes (Uint8ArrayorArrayBuffer) or 64 hex characters. It returns both headers:TrustPin-Attestationwith the token andTrustPin-Assertion(TrustPinAttest.assertionHeaderName) with the assertion. Your backend passes both, with its own digest of what it received, to your verifier. See Assertions for sensitive operations.- Each call produces a new assertion, one per operation, and costs one round trip to your verifier besides your request.
- It rejects with
INVALID_DIGESTfor any other digest, and with the same errorgetToken()would when no token is available.
Verify the token in your API
The header carries a signed JWT issued by your verifier. Your API checks its signature against the verifier’s published keys, its type, issuer, audience, expiry and project, and its binding, and refuses debug tokens in production. What to do with a request without a valid token is your decision, per endpoint. See Verifying tokens in your API.
The token’s sub identifies the device key. It changes when the device attests a new key, so don’t use it as a stable device identifier.
Simulators, emulators and development
Simulators and emulators can’t provide evidence your policy accepts. For development, your verifier’s operator issues a debug token, and the policy (Allow debug tokens) and the verifier must both allow it. Pass it from the build, never from a file in the app.
iOS simulator. Open ios/<YourApp>.xcworkspace, set TRUSTPIN_DEBUG_TOKEN in the scheme’s environment variables (Product, Scheme, Edit Scheme, Run, Arguments), and run from Xcode: npx react-native run-ios and npx expo run:ios don’t apply scheme variables. TrustPinReactNativeAttest.start(debugToken:) also takes one. The token is ignored on devices.
Android. Add a debug-only build field in android/app/build.gradle, and keep the token itself in ~/.gradle/gradle.properties (trustpinDebugToken=…), not in the repository:
android {
buildFeatures { buildConfig true }
buildTypes {
debug {
buildConfigField "String", "TRUSTPIN_DEBUG_TOKEN", "\"${project.findProperty('trustpinDebugToken') ?: ''}\""
}
release {
buildConfigField "String", "TRUSTPIN_DEBUG_TOKEN", "\"\""
}
}
}Then pass it to the start call in MainApplication.kt:
import cloud.trustpin.kotlin.attest.TrustPinAttestLogLevel
TrustPinReactNativeAttest.start(
this,
TrustPinAttestLogLevel.DEBUG,
BuildConfig.TRUSTPIN_DEBUG_TOKEN.ifEmpty { null },
)The token is used only in debuggable builds, on emulators and real devices. To test real device evidence, build without it or turn Allow debug tokens off. A debug token identifies the app by the package name it runs under, so a debug build with an applicationIdSuffix must be listed in the policy as its own package.
Expo. The plugin passes no debug token. After npx expo prebuild, apply the steps above to the generated ios and android projects; npx expo prebuild --clean discards them.
Debug tokens carry tp.env debug, which production APIs refuse.
State, errors and logging
await TrustPinAttest.getState() returns the current state. onStateChange delivers the current state first, then every change:
import TrustPinAttest, { TrustPinAttestState } from '@trustpin/react-native-attest';
const subscription = TrustPinAttest.onStateChange((state: TrustPinAttestState) => {
switch (state.status) {
case 'unavailable':
console.log('No token yet');
break;
case 'attesting':
console.log('Attesting…');
break;
case 'ready':
console.log('Token ready until', new Date(state.expiresAtMs));
break;
case 'failed':
console.log('Failed:', state.error.code, state.error.reasons, 'next attempt after', state.retryAtMs ?? 'restart');
break;
}
});
// subscription.remove() when you no longer need it.Retry time. No timer runs after a failure: nothing is tried before retryAtMs, and the next request, getToken() or prefetch() after it starts a new attempt. A null retryAtMs means no new attempt in this launch, until reset() or a restart. The exception is BINDING_REQUIRED, which resumes as soon as a binding is set.
Errors are TrustPinAttestError, with a stable code (constants in TrustPinAttestErrorCodes), a message, and reasons for ATTESTATION_FAILED:
| Code | Meaning | What to do |
|---|---|---|
INVALID_CONFIGURATION | A configuration value was rejected, or the file is missing | Fix the keys; on iOS, check that TrustPin-Info.plist is in Copy Bundle Resources |
ALREADY_INITIALIZED | The native start ran twice | Call it once, at launch |
NOT_SET_UP | The native start never ran, or the app wasn’t rebuilt | Add TrustPinReactNativeAttest.start(...) (or the Expo plugin) and rebuild |
UNSUPPORTED_DEVICE | iOS: this device can’t attest the app. Both platforms: new keys keep failing on it | Expected on some hardware. No header is sent |
EVIDENCE_UNAVAILABLE | The device can’t produce the evidence the policy requires, or Play Integrity is needed and the app has no project number | Review Evidence, or configure the project number |
BINDING_REQUIRED | The policy requires a binding and none is set yet | Expected before sign-in |
ATTESTATION_FAILED | The verifier refused; reasons carries its codes, such as app_not_allowed | See Troubleshooting |
VERIFIER_UNAVAILABLE | The verifier couldn’t be reached securely, including when strict pinning refuses its host | Check the URL and the verifier. In strict mode, register its domain |
VERIFIER_INCOMPATIBLE | The verifier is older than contract version 2 | Upgrade the verifier to 1.0.0 or later. No app change is needed |
INVALID_DIGEST | assertionHeaders got a digest that isn’t 32 bytes | Hash the payload with SHA-256 first |
New codes can appear in a minor release, and other failures carry INVALID_ARGUMENTS, CANCELLED or ATTEST_ERROR: handle unknown ones.
Logging
The native start call logs errors by default (error); set its log level, the Expo logLevel prop, or setLogLevel from JavaScript for more. Whether each request got the header is logged at debug. Messages reach you only through onLogEvent, not the Xcode console or logcat, and messages from before JavaScript was running, such as a failed native start, replay to the first subscriber:
TrustPinAttest.setLogLevel('debug'); // none, error, warning, info, debug. Development only
TrustPinAttest.onLogEvent(log => console.log(`[attest] ${log.level}: ${log.message}`));Log lines never contain tokens, key certificates, bound values or debug tokens.
Events
TrustPinAttest.onEvent(listener) delivers events for your metrics: keys generated or replaced, attestations and renewals with their durations, refusals and waits with their end, unsupported devices, an unreachable verifier, and assertions. Events from before JavaScript was running replay to the first subscriber.
TrustPinAttest.onEvent(event => {
switch (event.type) {
case 'attestationSucceeded':
console.log(`Attested in ${event.durationMs} ms`);
break;
case 'refused':
console.log('Refused, next attempt after', event.retryAtMs ?? 'restart');
break;
default:
break;
}
});Events never carry a token, a key or a device identifier. New event types can appear in a minor release: keep a default case.
Reset and backups
await TrustPinAttest.reset() discards the device key and token; the next request attests a new key, and the token’s sub changes. Use it for support flows, such as a “repair attestation” action, not routinely. It does nothing before setup.
Device keys and key certificates are never backed up or synced: a restored or reinstalled app attests again.
Rolling out
Start with the policy in Monitor (recommended to start), measure requests without a header and fail results, then switch to Enforce. See Rolling out: monitor to enforce.
Before a release build:
- The iOS entitlement says
production(with Expo,appAttestEnvironmentset toproductionor left out). - The policy lists the Play app signing certificate for builds from Google Play.
- Allow debug tokens is off in the production policy, and release builds pass no debug token (the
releasebuild field above is empty). - The log level is back to
noneorerror. google_cloud_project_numberis set only if the policy uses Play Integrity, and your Data safety form says so (see Privacy).
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Requests arrive without the header | The host isn’t in the attested hosts, the URL is http://, the native start never ran, or there is no token yet | Check the host list and the native start, read the state, and subscribe to onLogEvent with debug logging |
Every call rejects with NOT_SET_UP | TrustPinReactNativeAttest.start(...) isn’t called, or the app wasn’t rebuilt after installing | Add it after the pinning start (or the Expo plugin), run pod install, and rebuild |
Failed with UNSUPPORTED_DEVICE on the iOS simulator | No debug token | Set TRUSTPIN_DEBUG_TOKEN in the scheme and run from Xcode |
ATTESTATION_FAILED with app_not_allowed | The bundle ID, package name or signing certificate isn’t in the policy | Add it. Builds from Google Play are signed with the Play app signing key |
ATTESTATION_FAILED with dev_environment | A development build on an iPhone or iPad, with Accept development builds off | Turn it on while testing |
Failed with VERIFIER_UNAVAILABLE every time | The verifier’s domain isn’t registered, the verifier is down, or its URL is wrong | Register the domain, then check the URL and the verifier |
npx expo prebuild fails naming TrustPin-Info.plist or trustpin.json | The pinning plugin isn’t listed | List @trustpin/react-native with its props too |
Privacy
@trustpin/react-native-attest sends evidence and tokens only to your own verifier, and nothing to TrustPin. Bound values never leave the device, and tokens identify a device key, not a person. On iOS the native framework ships a privacy manifest (no tracking, no collected data). On Android, with a Google Cloud project number configured, declare your use of the Play Integrity API in Play Console’s Data safety form. If you forward events to a third-party service, that disclosure is yours to make.
Next steps
- Verifying tokens in your API: the next step on the path.
- Rolling out: monitor to enforce
- Certificate pinning for React Native
- @trustpin/react-native-attest on npm , and the
exampleandexample-expoapps’ Attestation tab