field-react-native
@flowcatalyst/field-react-native gives a React Native app the same field-worker sign-in as
@flowcatalyst/field-js, but with the session held by native code. On
Android the single owner of keys, tokens, refresh and DPoP nonces is the Kotlin
FieldSession; on iOS it is the Swift FieldSession of
field-ios. Your JavaScript
screens and native code in the same app share it. Current version: 0.7.0.
Read Field-worker identity first for the model (device-bound sessions, PINs held by the platform, biometrics for unlock and, on native, platform-verified unlock keys). Wire details are in the field protocol reference.
Platform support
Section titled “Platform support”- New Architecture only. The native module is a TurboModule named
FcField, with the codegen spec insrc/NativeFcField.ts. React Native 0.76 or later. - Android: a thin bridge over
io.flowcatalyst.field.FieldSession. All session methods work. - iOS: the same module, spec and JavaScript API over the Swift
FieldSessionofclients/field-ios(see Choosing a field library). EveryFieldClientmethod, event and error code behaves as on Android; the differences are listed under iOS notes. The package carries a verbatim copy of the field-ios sources (ios/FieldIos) and compiles them with the bridge into one Swift module,FlowcatalystFieldReactNative. iOS 15.1 or later (the pod needs 15.0; React Native 0.76 itself needs 15.1). - WebView pages keep using
@flowcatalyst/field-jsthrough the bridge host. On Android, the bridge’s key operations use the same Keystore key asFieldSession(aliasfc_field_device), so an app has one device key.
Install
Section titled “Install”The package is installed from a git tag of a split repository, not from a registry. The published
repository holds the built package; Metro reads the TypeScript source through the react-native
entry, and lib/ carries JavaScript and .d.ts files for everything else.
{ "dependencies": { "@flowcatalyst/field-react-native": "github:flowcatalyst/field-react-native#v0.7.0" }}Peer dependencies: react 18 or later, react-native 0.76 or later, and optionally expo 51 or
later and react-native-webview 13 or later (for the bridge). The Android side depends on the
io.flowcatalyst:field-android library; see field-android for where it
comes from.
Expo (prebuild or dev client; not Expo Go)
Section titled “Expo (prebuild or dev client; not Expo Go)”{ "expo": { "plugins": [["@flowcatalyst/field-react-native", { "faceIdPermission": "Unlock the app with Face ID", "fieldAndroidVersion": "0.7.0" }]] }}The config plugin (app.plugin.js) adds USE_BIOMETRIC, raises android.minSdkVersion to at least
26 (option minSdkVersion to go higher), adds the GitHub Packages Maven repository
(https://maven.pkg.github.com/flowcatalyst/flowcatalyst, with credentials from the Gradle
properties gpr.user and gpr.key or the environment variables GITHUB_ACTOR and GITHUB_TOKEN),
adds implementation "io.flowcatalyst:field-android:<version>" to the app module, and sets
NSFaceIDUsageDescription (faceIdPermission: false skips it; an existing value is kept). It is
idempotent and needs a Groovy android/build.gradle, the Expo default.
Bare React Native
Section titled “Bare React Native”- Set
minSdkVersion 26. The hostActivitymust be aFragmentActivity(ReactActivityis). - Add the Maven repository above to
allprojects.repositories, with credentials.io.flowcatalyst:field-androidis published there; this bridge needs 0.6.0 or later, and its default is the version it was built against (0.6.0). For local work on the library, a composite build in the app’ssettings.gradlealso works:includeBuild("../path/to/clients/field-android"). - Autolinking registers
FcFieldPackage. Override the library version withext.fieldAndroidVersionin the rootbuild.gradle. - iOS:
cd ios && pod install, and setNSFaceIDUsageDescriptioninInfo.plist(Face IDunlockneeds it). The podFlowcatalystFieldReactNativeneeds nouse_frameworks!setting, linksSecurity,LocalAuthentication,CryptoKitandUIKit, and registers as the TurboModuleFcField. The device key and the Keychain items need no entitlement and no capability. An app that talks to a local platform over plainhttpneeds an App Transport Security exception inInfo.plist(NSAllowsLocalNetworkingcoverslocalhost); the library itself acceptshttp:only for loopback hosts and origins named in the config.
A known build issue, not specific to this library: Expo SDK 58’s expo-modules-jsi does not compile with
Xcode 26.3 (Swift 6.2) (“sending ‘slot’ risks causing data races” in JavaScriptObject.swift). It needs
a newer Xcode or a small patch to that package.
Create the client
Section titled “Create the client”import { FieldClient } from "@flowcatalyst/field-react-native";
const field = new FieldClient({ platformUrl: "https://platform.example.com", appCode: "warehouse", clientIdentifier: "acme", // for worker-code sign-in on an unenrolled device requireUnlock: { afterColdStart: true, afterBackgroundMs: 5 * 60_000 }, expiryWarningsMs: [30 * 60_000, 10 * 60_000], // default keepAliveLeadMs: 2 * 60_000, // default});| Config key | Default | Meaning |
|---|---|---|
platformUrl |
required | The platform’s public base URL. An enrolment QR for a different origin (scheme, host and port) is refused with PLATFORM_MISMATCH and nothing is stored, unless that origin is in allowedPlatformOrigins. With an empty URL the first QR is adopted. |
allowedPlatformOrigins |
none | Further platform origins an enrolment QR may name (for example https://fc-eu.example.com). An http: QR is accepted only for loopback hosts or an origin named here or in platformUrl. |
appCode |
required | The application the session is for. |
clientIdentifier |
none | Needed for worker-code sign-in on a device that is not enrolled. |
requireUnlock |
never | { afterColdStart?, afterBackgroundMs? }: when the app lock engages. |
expiryWarningsMs |
30 and 10 minutes | Times before the absolute expiry at which ExpiryWarning fires. |
keepAliveLeadMs |
2 minutes | How long before the idle deadline keepAlive refreshes. |
The first method call (or on) configures the native owner. A second FieldClient with a
different config rejects with CONFIG_MISMATCH: the config must be the same everywhere in the
process, including the config a native service uses.
Sign in
Section titled “Sign in”The method names and the Session shape match field-js FieldAuth (worker, actor, test,
deviceMode, deviceId, appCode, expiresAt, idleExpiresAt, refreshExpiresAt,
pinChangeRequired; times are milliseconds since the epoch), plus clientId, clientIdentifier, amr and unlockKeys (below) and worker.photoVersion and worker.canSetOwnPhoto.
const { state, session, device } = await field.restore(); // state: SignedOut | SignedIn | Lockedawait field.enrol(qrPayloadOrCode, { label: "Truck 7" });await field.login({ workerCode: "W001", pin: "1234" }); // or { badgeToken, pin? }await field.redeemSignInCode(code);await field.actAs({ workerCode: "W002", pin: supervisorPin });await field.endImpersonation();await field.changePin({ currentPin, newPin }); // changes, then refreshesawait field.refresh();await field.logout({ scope: "session" }); // or "device-all"field.session and field.state hold the last values this client saw.
Errors
Section titled “Errors”Failures reject with FieldAuthError: code, optional status and retryAfterSeconds, and
violations (a list, empty when there are none). The codes are the field-js codes
(list: INVALID_CREDENTIALS, INVALID_GRANT, SESSION_EXPIRED,
DEVICE_REVOKED and the rest) plus NETWORK, NOT_ENROLLED, NOT_CONFIGURED, CONFIG_MISMATCH,
KEY_INVALIDATED, BIOMETRIC_* and INTERNAL. Native rejections
pass through mapNativeError; one without a code becomes INTERNAL. Messages never carry a PIN.
PIN_RESET_REQUIRED (HTTP 403, from login and actAs): the worker’s PIN was set under an app key that has since
been removed. It is not a wrong PIN and retrying cannot help: show “Ask your supervisor to reset your PIN”.
isPinResetRequired(e) tests for it. The library does not retry, does not emit WorkerLocked, and does not clear
the enrolment or end a session.
Events
Section titled “Events”const off = field.on("SessionEnded", ({ reason }) => navigateToSignIn(reason));| Event | Payload |
|---|---|
SessionChanged |
{ session } (null on sign-out) |
SessionEnded |
{ reason } |
PinChangeRequired |
{ session } |
ExpiryWarning |
{ remainingMs } |
Locked |
{ session } |
WorkerLocked |
{ hard, retryAfterSeconds? } |
UnlockKeyChanged |
{ key } (null when the key is forgotten; since 0.7.0) |
Callbacks are plain functions: no EventTarget, no DOM, so it runs on Hermes. on returns the
unsubscribe function; field.dispose() drops every native subscription and listener.
Unlock
Section titled “Unlock”Tokens are stored without user authentication so a refresh works in the background and after a
reboot. The biometric is an app unlock, not a token gate. When state is Locked (policy
requireUnlock; enrolled PERSONAL, non-impersonated sessions only), show your lock screen and call:
await field.unlock("Unlock");Never use biometrics on SHARED devices; they sign in with the PIN.
Unlock keys: sign in again with a fingerprint or face
Section titled “Unlock keys: sign in again with a fingerprint or face”Since 0.7.0. An unlock key lets a worker whose session has ended sign in again on their own enrolled
PERSONAL phone with a fingerprint or face instead of the PIN. The phone holds a key in secure hardware (the
Android Keystore, the iOS Secure Enclave) that signs only after a strong biometric match; the platform holds
its public half, verifies a signature over a fresh challenge and issues a new session with amr
["hwk","uv"]. The client’s field policy must have unlockKeysEnabled. Both platforms delegate to the native
libraries with the same methods, shapes, events and codes.
// Right after a PIN sign-in on this phone, while its register window is open (no network: the sign-in answer says):if ((await field.unlockKeyAvailability()) === "AVAILABLE" && (await askWorker())) { await field.enableUnlockKey({ title: "Use your fingerprint to sign in", cancel: "Not now" }); // one prompt}
// On the sign-in screen:const key = await field.unlockKey(); // { workerId, workerCode, workerName, ... } | null: "Sign in as Ann"if (key) { try { await field.loginWithUnlockKey({ title: "Sign in", cancel: "Use PIN" }); // a Session, as login gives } catch (e) { showPinPad((e as FieldAuthError).code); // every failure means "sign in with the PIN" }}
await field.disableUnlockKey(); // switch it off on this phone (works signed out)- Needs field-android 0.6.0 or later on Android (the bridge’s
fieldAndroidVersion; its default is the version it was built against) and the field-ios copy this package carries on iOS. Against a native module built before unlock keys, availability isUNSUPPORTEDand the calls reject withUNLOCK_KEYS_UNSUPPORTED. Android needs API 30 (Android 11) or later (OS_TOO_OLDbefore that). unlockKeyAvailability()resolves one ofUNLOCK_KEY_AVAILABILITIESwith no network request:AVAILABLE,ENABLED,NOT_ENROLLED,SHARED_DEVICE,NOT_SIGNED_IN,IMPERSONATING,PIN_SIGN_IN_REQUIRED,OTHER_WORKER,OS_TOO_OLD,NO_SECURE_HARDWARE,BIOMETRIC_NOT_ENROLLED,BIOMETRIC_UNAVAILABLE,POLICY_OFF,ATTESTATION_REQUIREDorUNSUPPORTED. It is computed fromsession.unlockKeys({ allowed, attestationRequired, registerExpiresAt }ornull), which every sign-in and refresh answer carries.- The prompt
{ title, cancel, subtitle? }is your words. Face ID needsNSFaceIDUsageDescription; the Expo plugin sets it, but its default text speaks of unlocking the app, so passfaceIdPermissionwith words that cover signing in. - Rejections are
FieldAuthErrors: the library’sUNLOCK_KEY_CODES(NO_UNLOCK_KEY,UNLOCK_KEY_INVALIDATED,UNLOCK_KEYS_UNSUPPORTED,BIOMETRIC_NOT_ENROLLED,BIOMETRIC_LOCKOUT,UNLOCK_KEY_OTHER_WORKER),BIOMETRIC_CANCELLED, and the platform’s (UNLOCK_KEY_INVALID,UNLOCK_KEYS_DISABLED,PIN_REAUTH_REQUIRED,INVALID_UNLOCK_PROOF,ATTESTATION_REQUIRED,ATTESTATION_STATUS_UNAVAILABLEwithretryAfterSeconds). - iOS cannot attest a Secure Enclave key. A client whose policy sets unlock key attestation to
REQUIREDrefuses every iOS key and cannot use unlock keys on iOS. - A sign-out does not remove the key (signing in again after one is what it is for). To forget a worker on
the phone, call
disableUnlockKey()and thenlogout(). - Tested: the owner has run unlock keys end to end on a real Android phone against a non-production platform. Not run on an iPhone: the iOS side of this package has run on the simulator only, which has no Secure Enclave.
The client of the session
Section titled “The client of the session”field.session?.clientIdentifier is the client’s identifier, for example "acme" (the access token’s
client_identifier claim), and field.session?.clientId is the platform’s id for the client (the client_id
claim). Use them to build addresses such as /api/clients/{client}/... without a “who am I” call. They are
read from the token at every sign-in and refresh, stored with the session (so they survive a restart), and
null when the token does not carry the claim: wait for the refresh or ask the worker to sign in again rather
than guessing. They come from a token the phone cannot verify, so your server must take the client from the
verified token and refuse a path that names a different one.
The worker’s own photo
Section titled “The worker’s own photo”session.worker.photoVersion (null when there is none, or photos are off) and
session.worker.canSetOwnPhoto come with the session and survive restarts. A photo changed elsewhere shows as
a new photoVersion at the next sign-in or refresh.
const photo = await field.getPhoto({ size: "thumb", haveVersion: held }); // null: none; photo.notModified: keep yoursif (field.session?.worker.canSetOwnPhoto) { await field.setPhoto({ bytes, contentType: "image/jpeg" }); // JPEG, PNG or WebP, decided from the bytes await field.removePhoto();}Bytes cross the bridge as base64url strings, one third larger each way (a 3 MB camera photo crosses as
about 4 MB), so resize before uploading if you can; the platform accepts up to 10 MiB by default. The Android bridge needs a field-android release that has
getPhoto, setPhoto and removePhoto (ext.fieldAndroidVersion). Refusals are the platform’s photo codes
(OWN_PHOTO_NOT_ALLOWED, PHOTOS_DISABLED, PHOTOS_DISABLED_FOR_CLIENT, IMPERSONATING, PHOTO_*,
TOO_MANY_REQUESTS) as in field-android.
Requests to your backend
Section titled “Requests to your backend”const res = await field.fetch("https://api.example.com/trips", { method: "POST", body });field.fetch signs the request with Authorization: DPoP and a proof, retries once on
401 use_dpop_nonce, and remembers every DPoP-Nonce it sees. Network failures reject with
NETWORK. For code that is not fetch (SSE or upload libraries), ask for headers directly:
const h = await field.headersFor("GET", url); // { Authorization, DPoP }; refreshes first if needed// on 401 use_dpop_nonce:const again = await field.headersForRetry("GET", url, response.headers.get("DPoP-Nonce")!);// any DPoP-Nonce you see elsewhere:await field.noteNonce(url, nonce);A proof is bound to one method, one URL and one nonce.
Offline queue rule: store requests unsigned and sign when sending. A stored proof fails anyway: nonces are single-use or last about five minutes, and access tokens last ten minutes.
Long shifts: keepAlive
Section titled “Long shifts: keepAlive”await field.keepAlive(true); // while a trip or tracking is activeawait field.keepAlive(false);While on, the native owner refreshes before the idle deadline. Turn it on only while the worker is
genuinely busy, and use ExpiryWarning to ask for a new sign-in at a stop.
Foreground service (Android)
Section titled “Foreground service (Android)”A tracking service is plain Kotlin and uses FieldSession directly
(FieldSession.get(ctx, config).interceptor() for OkHttp, or headersForBlocking). It must run in
the app’s process (no android:process) so JavaScript and the service share the one owner, and its
config must equal the JavaScript config (CONFIG_MISMATCH otherwise). There is no alarm; the
foreground service keeps the process alive. See field-android.
Native code on iOS
Section titled “Native code on iOS”Native code in the same app process (a background location module, for example) reaches the same
owner through the pod’s Swift module. The other pod depends on FlowcatalystFieldReactNative:
import FlowcatalystFieldReactNative
let config = try FieldBridgeConfig.fieldConfig(fromJSON: storedConfigJson) // or fieldConfig(from: [String: Any])let session = try FieldSession.get(config: config) // the same object JavaScript configured_ = try await session.restore()let signed = try await session.authorize(urlRequest) // Authorization: DPoP and a DPoP proofFieldSession.get(config:) refuses a config that differs from the first one it received
(CONFIG_MISMATCH). FieldBridgeConfig is the mapping configure applies to the JavaScript config
object (milliseconds in, seconds in FieldConfig), so a module that stores the JSON JavaScript passed to
configure rebuilds an equal config after a relaunch, with or without JavaScript. The whole public API
of field-ios is visible through that one import. If your own pod imports this module from Swift, keep
its Objective-C++ part out of public headers, as this pod does.
iOS notes
Section titled “iOS notes”- The device key is created by
SecureEnclaveKeyProvider: Secure Enclave on a device, a software Keychain key in the simulator (attestation levelTEEon a device,SOFTWAREin the simulator; no attestation chain, so the platform treats a device enrolled this way as attestation levelNONE). - Signing with the device key while the phone is locked (the key is usable only when unlocked) rejects
with
INTERNAL, notKEY_INVALIDATED. It is temporary: retry after unlock. restoreandgetStateinclude the enrolleddevicerecord.unlockshows the system prompt (Face ID or Touch ID, then the passcode). The process is suspended in the background, sokeepAliveand the expiry-warning timers run only while the app runs; a refresh is also done on first use.- Events are delivered once a listener is registered (
FieldClient.ondoes that). Events fired before that are not replayed. keepAliveandnoteNoncereturn at once and are applied in call order.
Push: job updates
Section titled “Push: job updates”PushStream here is the same reader as in @flowcatalyst/field-js
with no DOM (it runs on Hermes, with or without TextDecoder) and addListener instead of
EventTarget. The two packages share one source file, push-core.ts, so reconnect, backoff,
auth-expired handling and resume behave identically. The signal-not-state model is explained in
Push to clients.
import { PushStream } from "@flowcatalyst/field-react-native";import { fetch as streamFetch } from "expo/fetch"; // streams response bodies; RN's built-in fetch does not
const topic = `warehouse:field-worker:${principal}:jobs`;const stream = new PushStream({ baseUrl: "https://app.example.com/api", topics: [topic], fetch: field.fetch.bind(field), // signs the subscribe call (DPoP and refresh) streamFetch, // the stream GET carries its token in the URL, so it needs no signature lastEventId: await loadSavedId(),});
stream.on(topic, (push) => refreshJobs()); // push = { id, topic, type, data }stream.addListener("reset", () => refreshJobs());stream.addListener("denied", (topics) => console.warn(topics));stream.addListener("error", (err) => console.warn(err.code));stream.start();
// The OS drops the connection in the background: end it, then start it again.AppState.addEventListener("change", (s) => { if (s === "active") { stream.stop(); stream.start(); } else stream.stop();});addListener(event, fn) returns { remove() }. Events: subscribed, reset, denied, error,
state. After stop(); start() the reader resumes from the last id; stop() alone does not forget
it. Save stream.lastEventId and pass it back next start.
WebView bridge (protocol v1)
Section titled “WebView bridge (protocol v1)”When part of your app is a web page, that page uses @flowcatalyst/field-js and the app hosts the
bridge it talks to:
import { useFieldBridge } from "@flowcatalyst/field-react-native";
const bridge = useFieldBridge({ allowedOrigins: ["https://field.example.com"], onMessage: myHandler, // gets every message that is not a bridge request});
<WebView source={{ uri: "https://field.example.com" }} {...bridge} />;useFieldBridge returns ref, onMessage and injectedJavaScriptBeforeContentLoaded (which
installs window.__fcFieldBridge with version: 1). Only the listed origins are served, and the
host never logs request contents. createBridgeHost is the lower-level function the hook wraps.
NativeKeyProvider and NativeSecureStore implement the field-js KeyProvider and SecureStore
interfaces over the same native module (the Keystore key shared with FieldSession on Android;
Secure Enclave and Keychain on iOS, the same key as the session owner). They are what the bridge host calls. On SHARED devices, do not
use biometrics for worker identity.
Exports
Section titled “Exports”FieldClient, FieldAuthError, mapNativeError, FIELD_EVENT_NAMES, PushStream, PushError,
SseParser, topicMatches, useFieldBridge, createBridgeHost, NativeKeyProvider,
NativeSecureStore, setNativeModule (for tests), FieldError and the shared KeyProvider,
SecureStore and DeviceKey types, plus the config, session and event types.
Develop and test
Section titled “Develop and test”CI=true pnpm install && pnpm lint && pnpm test # tsc; JS and Expo plugin testspnpm sync:field-ios # after changing clients/field-ios: refresh ios/FieldIosswift test --package-path ios # the pod's Swift files as one module, plus helper tests (macOS)pnpm codegen # TurboModule spec -> android/build/codegenFieldClient accepts { native, events, platform, fetch } options, so tests can supply a fake
native module and event source. The package’s tests cover the JavaScript layer and the Expo plugin;
the Kotlin module has JVM unit tests, and a test fails when ios/FieldIos differs from clients/field-ios.
What the library’s authors have verified:
- Android: the Kotlin module compiles against React Native 0.76.9, the generated codegen spec and
field-android, and its JVM tests pass. Not verified: a real app build with autolinking, a device or emulator run. - iOS: a Release app (Expo SDK 58, React Native 0.88.1, New Architecture) run on the iOS 26.3 simulator
against a local platform: enrol, login, PIN change, refresh, a signed request accepted by the
platform, logout, events, relaunch and restore, the key and store methods, and
unlockwith a simulated Face ID. A second pod importingFlowcatalystFieldReactNativesigned a request on the same session. - iOS, not verified: a physical iPhone (the Secure Enclave key, real Face ID or Touch ID, Keychain
after a restart or restore, background behaviour),
use_frameworks!builds, React Native versions other than 0.88.1, an Expo SDK other than 58, and the biometric Keychain access control: on the simulator the prompt did not appear, so that access control and its cancel path (BIOMETRIC_CANCELLEDfrom a store read) are unproven.