Skip to content

field-js

@flowcatalyst/field-js is the TypeScript library a web page or a WebView uses to sign a field worker in and to call your backend as that worker. It has no runtime dependencies and runs in any browser with Web Crypto and IndexedDB. Current version: 0.6.0.

For what field-worker identity is and why sessions are bound to a device key, read Field-worker identity. The wire details (endpoints, token claims, error codes) are in the field protocol reference. To choose between this library, React Native and native Android, see Choosing a field library.

  • Enrols a device with a one-time code or a QR payload, creating a non-extractable device key.
  • Signs in by worker code and PIN, or by badge. It works on a device that has not been enrolled.
  • Holds the session: rotates the refresh token, reads the access token’s claims, and exposes the session as plain data.
  • Calls your backend with Authorization: DPoP <token> and a fresh proof for every request, refreshing first and retrying once on a nonce or token challenge.
  • Supports supervisors acting as a worker (impersonation) and redeeming a sign-in code.
  • Reads the push stream for live job updates (PushStream).
  • Ships <fc-pin-pad>, a framework-free PIN keypad custom element.
  • Talks to a native host through the WebView bridge, so the key and the stored tokens can live in the Android Keystore or iOS Keychain instead of the page.

The package is installed from a git tag of a split repository, not from a registry:

{
"dependencies": {
"@flowcatalyst/field-js": "github:flowcatalyst/field-js#v0.6.0"
}
}

The repository holds the built package (dist/). Tags follow the library’s VERSION file; Packages and versions lists the current one. Node 22 or later is needed to build or test; the library itself targets browsers.

FieldAuth takes a key provider and a secure store. defaultProviders() picks them for you: the WebView bridge when a native host installed it, otherwise a Web Crypto key in IndexedDB.

import { FieldAuth, defaultProviders } from "@flowcatalyst/field-js";
const { keys, store } = defaultProviders();
const auth = new FieldAuth({
platformUrl: "https://platform.example.com", // optional until enrolment; a QR payload carries it
appCode: "warehouse",
clientIdentifier: "acme", // needed for worker-code sign-in on an unenrolled device
keys,
store,
});
const { device, session } = await auth.restore(); // loads what the store holds
Option Type Meaning
platformUrl string? The platform base URL. Optional until enrolment, because an enrolment QR carries it. A restored device record also supplies it. When it is set, an enrolment QR for any other origin is refused with PLATFORM_MISMATCH and nothing is stored (see allowedPlatformOrigins).
allowedPlatformOrigins string[]? Further platform origins (scheme, host and port, for example https://fc-eu.example.com) an enrolment QR may name besides platformUrl’s. An http: origin is accepted only for loopback hosts or when named here or as platformUrl. Default: none.
appCode string The application the session is for.
keys KeyProvider Creates and uses the device key.
store SecureStore Keeps the device record, session metadata and refresh token.
fetch typeof fetch? Replaces the global fetch (tests, custom transports).
clock () => number? Milliseconds since the epoch; tests only.
biometricUnlock boolean? Keep the refresh token behind a biometric prompt on PERSONAL devices whose store supports it, and allow unlock().
unlockPrompt string? Text for the biometric prompt.
clientIdentifier string? The client’s identifier; login can override it per call.
// 1. Enrol (optional). Accepts the 10-character code or a whole fcfield:1: QR payload.
const device = await auth.enrol(scannedText, { label: "Truck 7" });
// device = { deviceId, mode: "PERSONAL" | "SHARED", clientId, appCodes, platformUrl }
// 2. Sign in by worker code and PIN, or by badge.
const session = await auth.login({ workerCode: "W001", pin: "1234" });
// or: await auth.login({ badgeToken: scanned, pin: "1234" }); (PIN optional when the client allows badge-only)
// 3. Change the PIN (required when session.pinChangeRequired is true).
await auth.changePin({ currentPin: "1234", newPin: "829104" });
// 4. Sign out this session, or every session on this device.
await auth.logout({ scope: "session" }); // or "device-all" (needs an enrolled device)

login needs exactly one of workerCode or badgeToken; anything else throws INVALID_REQUEST. Badge strings are normalised (whitespace and control characters dropped, upper-cased) with normaliseBadgeToken. QR payloads have the form fcfield:1:<platformUrl>:<code>; parseEnrolmentQr splits one into { platformUrl, code } and throws INVALID_ENROLMENT_CODE when it is malformed.

The PIN is passed through to the platform. The library never stores it and removes it, and any token, from error messages.

auth.session is null or a Session. All times are milliseconds since the epoch on the device clock.

Field Meaning
worker { id, workerCode, name, photoVersion, canSetOwnPhoto } (the photo members are described under The worker’s own photo)
clientId The platform’s id for the worker’s client (the access token’s client_id claim), or null when the token does not carry it
clientIdentifier The client’s identifier, for example "acme" (the token’s client_identifier claim), or null. Use it to build addresses such as /api/clients/{client}/... and to show a name; it comes from a token the page cannot verify, so your server must take the client from the verified token and refuse a path that names another
amr How the login family was signed in, for example ["pin"], ["badge","pin"] or, after an unlock key on a native app, ["hwk","uv"]
unlockKeys { allowed, attestationRequired, registerExpiresAt } from the token answer, or null. Kept for parity with the native libraries: a browser offers no unlock keys whatever it says
actor Who is acting as the worker (impersonation), or null
test true for a test identity
deviceMode PERSONAL, SHARED or UNENROLLED
deviceId null on an unenrolled device
appCode The application the session is for
expiresAt When the access token expires
idleExpiresAt, refreshExpiresAt The idle and absolute deadlines of the session
pinChangeRequired The worker must change the PIN before doing anything else

Other getters: auth.enrolledDevice (the DeviceRecord once restored or enrolled) and auth.impersonating (true while someone acts as the worker).

FieldAuth extends EventTarget. Each event carries its value in detail.

Event detail
sessionChanged The new Session, or null on sign-out
sessionEnded { reason }: "logout", "invalid_token" or a platform code such as SESSION_EXPIRED
pinChangeRequired The Session
locked { hard, retryAfter? }: the worker is locked out; retryAfter is in seconds and absent for a hard lock
auth.addEventListener("sessionEnded", (e) => {
const { reason } = (e as CustomEvent<{ reason: string }>).detail;
showSignIn(reason);
});
await auth.actAs({ workerCode: "W002", pin: supervisorPin }); // or { workerId, pin }
await auth.endImpersonation(); // back to the supervisor; returns the supervisor's Session or null
await auth.redeemSignInCode(code); // a code issued from the console or by a supervisor

changePin throws IMPERSONATING while someone is acting as the worker. Impersonation ends on its own when its token cannot be refreshed, and control returns to the supervisor.

auth.unlock() reads the stored refresh token (the host shows the biometric prompt) and refreshes. It applies only to enrolled PERSONAL devices on a store that supports biometrics, and never to an impersonated session; otherwise it throws BIOMETRIC_UNAVAILABLE. If the biometric key was invalidated (for example a new fingerprint was enrolled), the session ends with BIOMETRIC_INVALIDATED and the worker signs in with the PIN. Biometrics are an app unlock, not a substitute for the PIN on SHARED devices.

The platform’s unlock keys (sign in again with a fingerprint or face, verified by the platform) need a key behind a biometric in secure hardware, which a page cannot hold. So FieldAuth has the native libraries’ methods and answers them plainly: unlockKeyAvailability() is always "UNSUPPORTED", unlockKey() is null, enableUnlockKey() and loginWithUnlockKey() reject with UNLOCK_KEYS_UNSUPPORTED, and disableUnlockKey() does nothing. Use field-android, field-ios or field-react-native for unlock keys (see the guide).

The session says what the platform knows: session.worker.photoVersion is null when there is no photo or photos are off for the client or the platform, and session.worker.canSetOwnPhoto is true only when the client’s policy lets workers set their own and this is the worker’s own session.

const photo = await auth.getPhoto({ size: "thumb" }); // or "full"; null when there is none
// { bytes: Uint8Array, contentType: "image/jpeg", version, notModified: false }
const same = await auth.getPhoto({ haveVersion: auth.session!.worker.photoVersion }); // notModified: true, bytes: null while unchanged
if (auth.session!.worker.canSetOwnPhoto) {
await auth.setPhoto({ bytes: new Uint8Array(await file.arrayBuffer()), contentType: file.type }); // or a Blob
await auth.removePhoto();
}

The platform decides the type from the bytes (JPEG, PNG or WebP; a contentType may only agree), scales the picture to 512 px and 128 px and keeps nothing else of the upload. A changed or removed photo shows as a different photoVersion at the next sign-in or refresh, and sessionChanged is raised each time; setPhoto and removePhoto raise it too. Failures are FieldAuthErrors with the platform’s code: OWN_PHOTO_NOT_ALLOWED, PHOTOS_DISABLED, PHOTOS_DISABLED_FOR_CLIENT, IMPERSONATING (a supervisor acting as the worker may read but not change), PHOTO_EMPTY, PHOTO_TOO_LARGE, PHOTO_UNSUPPORTED_TYPE, PHOTO_TYPE_MISMATCH, PHOTO_DIMENSIONS_TOO_LARGE, PHOTO_UNREADABLE, PHOTO_BUSY and TOO_MANY_REQUESTS with retryAfter (120 reads and 20 changes an hour per worker by default).

On a web page: the platform must allow your origin

Section titled “On a web page: the platform must allow your origin”

A page in a browser calls the platform’s /field/* from your application’s origin, which is not the platform’s, so the browser applies CORS. A phone’s native app sends no Origin header and is not affected. The platform answers CORS on /field/* only for origins listed on the console’s CORS Origins page, and this is the same list the push gateway uses. Until the page’s origin is on it, sign-in fails in the browser before the platform sees it (the preflight is refused, 403).

Before a web page can sign a worker in:

  1. Add the page’s origin (scheme, host and port, for example https://app.example.com, with no path) on CORS Origins. A platform administrator does this; the entry is matched exactly, never as *.
  2. Wait up to about 15 seconds for the platform to pick up the change.
  3. Nothing else changes on the platform: /field/* allows POST with the Content-Type, DPoP and Authorization headers, exposes DPoP-Nonce, Retry-After, WWW-Authenticate and ETag to the page, and never sends credentials (cookies). Photo calls, which send an image Content-Type, are covered by the same rule.

Adding an origin lets a page there call the device protocol, so list only applications you control. The rest of the platform (/oauth/*, /auth/*, /api/*) still answers no CORS. In a WebView inside a React Native app the page’s key and store come from the host, and the same origin rule applies to the page.

const res = await auth.fetch("https://api.example.com/jobs", { method: "POST", body });

auth.fetch has the same signature as fetch. It adds Authorization: DPoP <access> and a DPoP proof bound to the method and URL. It refreshes first when the access token expires within 30 seconds (REFRESH_SKEW_MS), retries once on a use_dpop_nonce challenge, and on invalid_token refreshes and retries once; if the answer is still invalid_token, it emits sessionEnded. Your backend verifies the token and proof as described in Verify field tokens in your backend.

Do not queue signed requests for later. Proofs are single-use or bound to a short-lived nonce, and access tokens are short. Store the request unsigned and call auth.fetch when you send it.

Every failure is a FieldAuthError with a code, and when the platform answered, status, retryAfter (seconds, from Retry-After) and violations (the PIN policy rules that failed).

Code Meaning
INVALID_CREDENTIALS Wrong worker code, badge or PIN
WORKER_LOCKED, WORKER_LOCKED_TEMPORARILY, TOO_MANY_ATTEMPTS Locked out; read retryAfter
NO_APP_ACCESS The worker has no access to this application
DEVICE_REVOKED, DEVICE_SUSPENDED, UNKNOWN_DEVICE The device cannot be used; the session ends
INVALID_GRANT, SESSION_EXPIRED The refresh token is no longer valid; sign in again
PIN_RESET_REQUIRED 403 from sign-in and act-as (and the platform’s PIN change): the worker’s PIN was set under an app key that has been removed. Not a wrong PIN; retrying cannot help. Test with isPinResetRequired(e) and tell the worker to ask a supervisor to reset the PIN. The library does not retry, emit locked, clear the enrolment or end a session
PIN_POLICY The new PIN breaks a rule; see violations
INVALID_ENROLMENT_CODE Bad code or QR payload
FIELD_IDENTITY_UNCONFIGURED The client has not set up field identity
CLIENT_MISMATCH, PIN_REQUIRED, INVALID_CODE, INVALID_REQUEST Request-level problems
IMPERSONATING, IMPERSONATION_FORBIDDEN, NOT_IMPERSONATING Impersonation state errors
NETWORK, NOT_ENROLLED, BIOMETRIC_INVALIDATED Library-side failures
PLATFORM_MISMATCH An enrolment QR names an origin other than platformUrl and allowedPlatformOrigins
UNLOCK_KEYS_UNSUPPORTED An unlock key call in a browser
KEY_INVALIDATED, BIOMETRIC_UNAVAILABLE, BIOMETRIC_CANCELLED, NO_SECURE_LOCK_SCREEN, INTERNAL From the key provider or store (FieldProviderError)

The platform also sends invalid_dpop_proof, use_dpop_nonce and invalid_token in lower case; they pass through unchanged. The session-ending codes (INVALID_GRANT, SESSION_EXPIRED, DEVICE_REVOKED, DEVICE_SUSPENDED, UNKNOWN_DEVICE, NO_APP_ACCESS) clear local state and emit sessionEnded.

Importing the package registers <fc-pin-pad> when there is a DOM. It keeps the digits in a private array, never in an attribute, the DOM text, storage or the console, and wipes them once the pin event is emitted.

<fc-pin-pad length="6" scrambled label="Enter your PIN"></fc-pin-pad>
import type { FcPinPadElement, PinEventDetail } from "@flowcatalyst/field-js";
const pad = document.querySelector<FcPinPadElement>("fc-pin-pad")!;
pad.addEventListener("pin", async (e) => {
const { pin } = (e as CustomEvent<PinEventDetail>).detail;
await auth.login({ workerCode, pin });
pad.clear();
});
Attribute / property Meaning
length PIN length; the pad submits when it is reached
scrambled Shuffle the digit layout (resists shoulder-surfing and smudges)
disabled Ignore input
label Text above the dots
clear() Wipe entered digits (and reshuffle when scrambled)

The keyboard Enter key submits early once at least four digits are entered. Style it with the CSS custom properties --fc-pin-font, --fc-pin-fg, --fc-pin-bg, --fc-pin-dot, --fc-pin-key-bg, --fc-pin-key-fg, --fc-pin-key-border, --fc-pin-key-active-bg and --fc-pin-focus. Call definePinPad("my-name") to register under another tag name.

KeyProvider and SecureStore are the two interfaces a host implements to give the library a key and a place to keep secrets.

interface KeyProvider {
getOrCreateDeviceKey(): Promise<DeviceKey>; // { jwk, attestation: { level, chain? } }
sign(data: Uint8Array): Promise<Uint8Array>; // ES256 over SHA-256(data), raw r||s (64 bytes)
deleteDeviceKey(): Promise<void>;
}
interface SecureStore {
get(key: string, opts?: { prompt?: string }): Promise<string | null>;
set(key: string, value: string, opts?: { requireBiometric?: boolean }): Promise<void>;
delete(key: string): Promise<void>;
biometricAvailable(): Promise<boolean>;
}

In a browser, WebCryptoKeyProvider keeps a non-extractable ECDSA P-256 key in IndexedDB (attestation level SOFTWARE) and IndexedDbSecureStore keeps plain values there; it cannot do biometrics, so set(..., { requireBiometric: true }) throws BIOMETRIC_UNAVAILABLE. MemorySecureStore and MemoryDb are for tests. Inside a native host, the bridge providers below replace them.

A page inside a React Native WebView (or any host that installs window.__fcFieldBridge with version: 1 and a ReactNativeWebView.postMessage) can delegate key operations and secure storage to the native side. bridgeAvailable() tells you whether it is there, and defaultProviders() uses it automatically:

Export Role
bridgeAvailable() True when the host installed the bridge
BridgeClient Request and response correlation (60 s timeout, BRIDGE_TIMEOUT_MS, because a biometric prompt can be slow)
BridgeKeyProvider, BridgeSecureStore KeyProvider and SecureStore that call the host
defaultProviders() Bridge providers when available, otherwise Web Crypto and IndexedDB

The host side is useFieldBridge in @flowcatalyst/field-react-native. It allow-lists the page origins and answers key.getOrCreate, key.sign, key.delete, store.get, store.set and store.delete.

A host that uses the framework’s push module pushes small signals to a worker’s device. A worker’s jobs arrive on the topic {app}:field-worker:{principal}:jobs. The push says what changed; read the state through your API. See Push to clients and Live job updates for field devices.

import { PushStream } from "@flowcatalyst/field-js";
const principal = auth.session!.worker.id; // use the principal id your app puts in topics
const topic = `warehouse:field-worker:${principal}:jobs`;
const stream = new PushStream({
baseUrl: "https://app.example.com/api",
topics: [topic],
fetch: auth.fetch.bind(auth), // DPoP and token refresh for the subscribe call
lastEventId: await loadSavedId(), // optional: resume after an app restart
});
stream.on(topic, (push) => refreshJobs()); // push = { id, topic, type, data }
stream.addEventListener("reset", () => refreshJobs()); // away too long: reload your state
stream.addEventListener("denied", (e) => console.warn((e as CustomEvent).detail));
stream.addEventListener("error", (e) => console.warn((e as CustomEvent).detail));
stream.start();
Option Meaning
baseUrl The host’s base URL; /push/subscriptions and /push/stream hang off it
topics Topics to subscribe to; stream.setTopics([...]) subscribes again with a new set
fetch Used for the subscribe call. auth.fetch.bind(auth) in a field app; globalThis.fetch.bind(globalThis) for cookie sessions on a web page
streamFetch Used for the stream GET (the token in the URL is the capability). Defaults to globalThis.fetch
getTickets Fetches tickets from your own endpoint when a topic needs one; called again on every subscribe
lastEventId Resume from this id
eventTypes Needed only for the EventSource fallback, which can hear only event types it is told about
eventSource, random, sleep Injection points for non-streaming runtimes and tests
  • on(pattern, handler) takes a topic, or a pattern where * matches one segment and a final ** matches the rest. onAny(handler) takes every push. Both return a function that removes the handler.
  • Pushes arrive once and in order. A push with an id at or below the last delivered is dropped. Ids are 64-bit, so they are strings. Save stream.lastEventId and pass it back next start.
  • Events (EventTarget, value in detail): subscribed ({ granted, latest }), reset ({ reason, latest }: reload your state), denied ([{ topic, code }]), error (a PushError), state (connecting, open, reconnecting, stopped).
  • When the server ends the stream with auth-expired, or answers 401, the reader subscribes again and resumes from the last id. Other drops reconnect after the server’s retry (3 seconds) with jitter and back off to 60 seconds on repeated failures. 403 NO_TOPICS stops the stream and reports it.
  • The stream is read with a streaming fetch body. Where bodies are not streamable (React Native’s default fetch), the reader falls back to EventSource when there is one.

The library is written for injection: pass fetch, clock, a MemorySecureStore and a WebCryptoKeyProvider({ db: new MemoryDb() }) to run without a browser. The package’s own tests run with pnpm test (Node’s test runner, fake-indexeddb and happy-dom); end-to-end tests are under e2e/ (pnpm test:e2e) and need a running platform.