Skip to content

field-android

field-android is an Android library (AAR) that owns a field worker’s FlowCatalyst session: the device key, DPoP proofs, tokens, refresh, nonces and an OkHttp interceptor. It has no UI and no React Native dependency, and it never needs the main thread. Use it directly from a native Android app, or through @flowcatalyst/field-react-native, which is a thin bridge over it. The wire behaviour is a port of @flowcatalyst/field-js.

Current version: 0.7.0 (VERSION). Requirements: minSdk 26, compileSdk 35. Dependencies: OkHttp 4, kotlinx-coroutines, and androidx.biometric (for unlock only).

For the model, read Field-worker identity; for the wire, the field protocol reference.

The session is one object per process: keys in memory, the nonce cache and a single-flight refresh. Refresh tokens rotate, and reusing a rotated token revokes the whole token family. If a second process (or a second copy of the library) refreshed independently, the two would fight. So the JavaScript layer of a React Native app, a native foreground service and any other component all call the same FieldSession.get(...).

The artifact is io.flowcatalyst:field-android, published to GitHub Packages (https://maven.pkg.github.com/flowcatalyst/flowcatalyst) by the release workflow on a field-android/vX.Y.Z tag. GitHub Packages needs credentials even for reads, so add them to the repository declaration.

// settings.gradle.kts or build.gradle.kts
repositories {
maven {
url = uri("https://maven.pkg.github.com/flowcatalyst/flowcatalyst")
credentials {
username = providers.gradleProperty("gpr.user").orNull ?: System.getenv("GITHUB_ACTOR")
password = providers.gradleProperty("gpr.key").orNull ?: System.getenv("GITHUB_TOKEN")
}
}
}
dependencies {
implementation("io.flowcatalyst:field-android:0.7.0")
}

If you build from a checkout of the platform repository instead, use a composite build in the app’s settings.gradle: includeBuild("../path/to/clients/field-android"), then implementation("io.flowcatalyst:field-android").

The library manifest declares INTERNET and USE_BIOMETRIC.

val session = FieldSession.get(applicationContext, FieldConfig(
platformUrl = "https://platform.example.com",
appCode = "warehouse",
clientIdentifier = "acme", // needed for worker-code sign-in on an unenrolled device
requireUnlock = UnlockPolicy(afterColdStart = true, afterBackground = 5.minutes),
))
session.restore() // optional: waits for the stored session to load
session.enrolledDevice() // the stored DeviceRecord, or null when not enrolled
session.enrol("fcfield:1:https://platform.example.com:ABCDE12345", DeviceInfo(model = Build.MODEL))
session.login(LoginCredentials(workerCode = "W001", pin = "1234")) // or badgeToken = scanned
session.redeemSignInCode(code)
session.actAs(ActAsTarget(workerCode = "W002", pin = supervisorPin))
session.endImpersonation()
session.changePin(old, new)
session.logout() // or logout(LogoutScope.DEVICE_ALL)

FieldSession.get returns the process-wide owner. Call it from anywhere with the same config; a different config throws. All suspend functions switch to the library’s own dispatcher.

Field 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 (first-run provisioning). A platform URL adopted from the QR code is kept in the device record and survives an app restart (from v0.2.1; before it, every call failed with NOT_ENROLLED after a restart until the device was enrolled again).
allowedPlatformOrigins empty Further origins an enrolment QR may name, for example https://fc-eu.example.com. An http: QR is accepted only for loopback hosts (localhost, 127.0.0.1, [::1], 10.0.2.2) or an origin named here or in platformUrl.
appCode required The application the session is for.
clientIdentifier null Needed to sign in by worker code on a device that is not enrolled.
requireUnlock UnlockPolicy.NEVER When the app lock engages (below).
expiryWarnings 30 and 10 minutes Times before absolute expiry at which ExpiryWarning fires.
keepAliveLead 2 minutes How long before the idle deadline keepAlive refreshes.

session.state is a StateFlow<FieldState>: SignedOut, SignedIn(session) or Locked(session). session.addListener(listener) delivers FieldEvents and returns a Closeable.

FieldEvent Meaning
SessionChanged(session) The session changed; null on sign-out
SessionEnded(reason) "logout", "invalid_token" or a platform code
PinChangeRequired(session) The worker must change the PIN
ExpiryWarning(remaining) Once per threshold per login
UnlockKeyChanged(key) An unlock key was registered (key) or forgotten (null). A when that names every FieldEvent needs this member (since 0.6.0).

The Session inside FieldState.SignedIn and FieldState.Locked ((session.state.value as FieldState.SignedIn).session) carries, besides the worker, device and times:

Member Meaning
clientIdentifier The client’s identifier, for example "acme" (the access token’s client_identifier claim), or null. For building addresses such as /api/clients/{client}/... and showing a name.
clientId The platform’s id for the client (the client_id claim), or null.
worker.photoVersion, worker.canSetOwnPhoto See The worker’s own photo.
amr How the login family was signed in (["hwk","uv"] after an unlock key); empty for a session stored by a version before 0.6.0.
unlockKeys SessionUnlockKeys(allowed, attestationRequired, registerExpiresAt) from the token answer, or null from a platform older than unlock keys.

clientIdentifier and clientId are read from the access token’s claims at every sign-in, refresh, act-as and sign-in code (so an impersonated session has the worker’s client) and stored with the session, so they survive an app restart and are present while Locked. They are null when the token does not carry the claim, which every platform release since the field token’s first release does, so null is met only on a session stored by an older library until its next refresh. Do not guess a client: wait for the refresh or ask the worker to sign in again. They are read from a token the phone cannot verify: your server must take the client from the verified token and refuse a {client} in the path that differs. | Locked(session) | The app lock engaged | | WorkerLocked(hard, retryAfterSeconds) | Locked out of sign-in; retryAfterSeconds is null for a hard lock |

Failures are FieldAuthException(code, message, status, retryAfterSeconds, violations), an IOException so interceptors can throw it. The codes are the field-js codes (list). e.isPinResetRequired is true for 403 PIN_RESET_REQUIRED (from login and actAs): the worker’s PIN was set under an app key that has been removed, which is not a wrong PIN and cannot be retried away. Tell the worker to ask a supervisor to reset it. The library does not retry, does not emit WorkerLocked, and does not clear the enrolment or end a session. The message never contains a PIN or a refresh token, and LoginCredentials and ActAsTarget print *** for secrets in toString().

val http = OkHttpClient.Builder()
.addInterceptor(session.interceptor()) // as an application interceptor
.build()

The interceptor signs every request. It retries once on 401 WWW-Authenticate: DPoP error="use_dpop_nonce" with the new nonce, and once on a 401 invalid_token after a refresh (exactly one refresh request however many callers need one).

  • If the refresh ends the session (INVALID_GRANT, SESSION_EXPIRED, DEVICE_REVOKED, DEVICE_SUSPENDED, UNKNOWN_DEVICE, NO_APP_ACCESS), the session emits SessionEnded(code) and the request fails with FieldAuthException.
  • An invalid_token that survives a refresh emits SessionEnded("invalid_token") and the 401 is returned.
  • Requests with one-shot bodies are not retried.
  • It blocks the calling thread (OkHttp’s own), so do not call enqueue or execute from the main thread.

For anything that is not OkHttp:

val h = session.headersFor("POST", url) // Authorization + DPoP; refreshes first if needed
// on 401 use_dpop_nonce:
val again = session.headersForRetry("POST", url, response.header("DPoP-Nonce")!!)
// any DPoP-Nonce seen elsewhere:
session.noteNonce(url, nonce)
// Java or non-coroutine code, off the main thread:
val hb = session.headersForBlocking("POST", url)

Offline queues: store requests unsigned and sign when sending. Platform /field/ nonces are single-use and application nonces last about five to ten minutes, so a stored proof is useless.

class TrackingService : Service() {
private val http by lazy {
OkHttpClient.Builder().addInterceptor(FieldSession.get(this, config).interceptor()).build()
}
override fun onCreate() { FieldSession.get(this, config).keepAlive(true) } // while a trip is active
override fun onDestroy() { FieldSession.get(this, config).keepAlive(false) }
}

The service must run in the app’s process: do not set android:process on it.

keepAlive(true) refreshes at min(idleExpiresAt - keepAliveLead, idle midpoint) and re-plans after every refresh. It uses a coroutine, not an Android alarm; the foreground service keeps the process alive. Turn it on only while a trip or tracking is genuinely active. It stops when the session ends and resumes on the next sign-in while still on. ExpiryWarning fires once per threshold per login so the app can ask for a new sign-in at a stop.

Tokens are stored under a Keystore AES-GCM key without user authentication (StrongBox first, then the trusted execution environment), so refresh works in the background and after a reboot. A biometric is an app unlock, not a token gate.

With UnlockPolicy(afterColdStart, afterBackground) the state becomes Locked(session) when due, for enrolled PERSONAL, non-impersonated sessions only. Locked never blocks headersFor, the interceptor or keepAlive. The UI calls:

session.unlock(activity, "Unlock")

The prompt is BiometricPrompt with BIOMETRIC_STRONG or device credential on API 30 and later; weak biometrics or credential below that. “Background” means no started activity (lifecycle callbacks are registered by get); hosts can also call noteBackgrounded() and noteForegrounded(). Do not use unlock on SHARED devices, which use the PIN only.

The signed-in Session’s worker.photoVersion is null when there is no photo or photos are off, and worker.canSetOwnPhoto is true only when the client’s policy lets workers set their own and the session is the worker’s own. Both are kept across restarts. A photo changed elsewhere shows as a new photoVersion at the next sign-in or refresh, each time with a SessionChanged.

val me = (session.state.value as FieldState.SignedIn).session
val photo = session.getPhoto(PhotoSize.THUMB, haveVersion = held) // null: no photo; photo.notModified: keep yours
if (me.worker.canSetOwnPhoto) {
session.setPhoto(bytes, "image/jpeg") // JPEG, PNG or WebP; the platform decides from the bytes
session.removePhoto()
}

Refusals are FieldAuthException codes: OWN_PHOTO_NOT_ALLOWED, PHOTOS_DISABLED, PHOTOS_DISABLED_FOR_CLIENT, IMPERSONATING (reading is allowed while impersonating, changing is not), PHOTO_EMPTY, PHOTO_TOO_LARGE, PHOTO_UNSUPPORTED_TYPE, PHOTO_TYPE_MISMATCH, PHOTO_DIMENSIONS_TOO_LARGE, PHOTO_UNREADABLE, PHOTO_BUSY and TOO_MANY_REQUESTS with retryAfterSeconds.

Unlock keys: sign in again with a fingerprint or face

Section titled “Unlock keys: sign in again with a fingerprint or face”

An unlock key lets a worker whose session has ended sign in again on their own phone with a fingerprint or face instead of the PIN. The phone holds an ECDSA P-256 key in the Keystore (StrongBox first, then the TEE) that signs only after a strong (Class 3) biometric match and is invalidated when a biometric is enrolled; the platform holds its public half, sends a fresh challenge, verifies the signature and issues a new session with amr ["hwk","uv"]. The PIN is never stored. Added in 0.6.0.

Requirements: Android 11 (API 30) or later (OS_TOO_OLD before that), a phone with secure hardware and a strong biometric enrolled, an enrolled PERSONAL device, and a client policy with unlockKeysEnabled. Never for a shared phone, an unenrolled key, an impersonated session or a session that itself came from an unlock key. It needs a platform whose token answers carry unlockKeys; against an older one availability is POLICY_OFF and nothing is offered.

// Right after a PIN sign-in on this phone, while its register window is open (no network):
when (session.unlockKeyAvailability()) {
UnlockKeyAvailability.AVAILABLE -> if (workerSaysYes()) {
session.enableUnlockKey(activity, UnlockKeyPrompt(title = "Use your fingerprint to sign in", cancel = "Not now"))
}
else -> {} // ENABLED, PIN_SIGN_IN_REQUIRED, POLICY_OFF, ...
}
// On the sign-in screen, when session.unlockKey() names a worker ("Sign in as Ann"):
try {
session.loginWithUnlockKey(activity, UnlockKeyPrompt(title = "Sign in", cancel = "Use PIN"))
} catch (e: FieldAuthException) {
showPinPad(reason = e.code) // every failure means "sign in with the PIN"
}
session.disableUnlockKey() // switch it off on this phone (no session needed)
Call What it does
unlockKeyAvailability() Whether to offer it now. No network: computed from the session’s latest token answer and the phone’s state.
unlockKey() The key on this phone (worker id, code, name, pinRequiredBy), whoever’s it is. No network.
enableUnlockKey(activity, prompt) Makes the key, signs the key proof (one prompt) and registers it. Replaces the worker’s own earlier key.
loginWithUnlockKey(activity, prompt) Asks for a challenge, shows the prompt, and returns a new session as login does.
disableUnlockKey() Deletes the key and revokes it on the platform with the device key alone.

UnlockKeyAvailability is one of UNSUPPORTED, OS_TOO_OLD, NOT_ENROLLED, SHARED_DEVICE, NOT_SIGNED_IN, IMPERSONATING, PIN_SIGN_IN_REQUIRED, OTHER_WORKER, ENABLED, POLICY_OFF, BIOMETRIC_NOT_ENROLLED, BIOMETRIC_UNAVAILABLE, NO_SECURE_HARDWARE, ATTESTATION_REQUIRED or AVAILABLE. The register window opens at a PIN sign-in and lasts 10 minutes; it is counted from when the answer arrived on the monotonic clock and is kept in memory only, so after a restart availability is PIN_SIGN_IN_REQUIRED until the next refresh.

On failure the codes include NO_UNLOCK_KEY, UNLOCK_KEY_INVALIDATED (the phone’s biometrics changed; the key is revoked and deleted), UNLOCK_KEY_INVALID (revoked or unknown on the platform; deleted), UNLOCK_KEYS_DISABLED, PIN_REAUTH_REQUIRED (the key is kept and works again after the next PIN sign-in), ATTESTATION_STATUS_UNAVAILABLE (try again later), INVALID_UNLOCK_PROOF (counts as a wrong PIN), WORKER_LOCKED, CHALLENGE_EXPIRED and the BIOMETRIC_* codes of the prompt. The field-android README has the full table of which keep the key.

The app unlock above is separate and works as before: it gates the screens of a live session, whereas an unlock key starts a new one after the old one ended and the platform verifies it. A phone can use both.

Tested: the JVM tests check the signer byte for byte against the platform’s api/field-fixtures/unlock.json and every flow against a fake platform. The Keystore key, the attestation chain and the biometric prompt are not covered by automated tests. The owner has run unlock keys end to end on a real Android phone against a non-production platform (switching on, signing in with the fingerprint, an administrator’s revoke with the fallback to the PIN, a newly enrolled fingerprint invalidating the key, and switching off).

JDK 17 and the Android SDK (local.properties with sdk.dir=, or ANDROID_HOME):

Terminal window
./gradlew assembleRelease testDebugUnitTest

Tests are JVM unit tests (JUnit, MockWebServer, kotlinx-coroutines-test) with a software EC key and in-memory storage. The Keystore classes (AndroidKeystoreStorage, AndroidKeyProvider, BiometricUnlocker) are not covered by them; instrumented tests are not part of the module yet.