Skip to content
For the complete documentation index, see llms.txt. This page is also available as Markdown.

🌠Facial Recognition

Offline facial verification for HCM field workers

Overview

Offline-first facial recognition for HCM field workers. Provides identity verification at login, periodic re-verification during the workday, co-worker (non-mobile user) enrollment/verification on a supervisor's device, and a PIN fallback — all functional without connectivity, with audit events and enrollment data syncing to the server when online.

At a glance

  • Used by: HCM field workers, supervisors, and non-mobile co-workers.

  • Works offline: profiles and verification events remain available without a network.

  • Protects: sign-in, periodic attendance checks, and co-worker verification.

  • Fallback: workers can use a backup PIN after configured failed attempts.

  • Syncs: profiles go to the worker registry. Audit events use HCM sync.

In short: enrol once, verify offline, and sync securely when online.

Dependencies

  • MobileFaceNet and ML Kit create face profiles and perform liveness checks.

  • MDMS defines match thresholds, prompt timing, and attempt limits.

  • Worker registry stores profiles for recovery and co-worker verification.

  • Attendance service and HCM sync receive audit events when the device reconnects.

Business Flow

Enrol a worker

  1. The worker captures five face angles.

  2. The app checks liveness through a blink or head-turn challenge.

  3. The app rejects duplicate profiles and saves the approved profile locally.

  4. The worker receives a backup PIN once. The app stores only its salted hash.

  5. The profile and enrollment event sync when connectivity returns.

Supervisors can enrol non-mobile co-workers from Non-mobile users.

Verify a worker

  1. After HCM authentication, the app captures and compares the worker's face.

  2. It compares only with the signed-in worker's profile.

  3. A match opens the app and records a success event.

  4. Failed attempts lead to backup PIN verification, then HCM password verification.

The app also schedules periodic attendance prompts. Team and district supervisors are exempt. Co-workers verify after the system user verifies.

Configuration

MDMS loads tenant-scoped settings at app start and login.

Setting
Default
Purpose

START_HOUR / END_HOUR

8 / 18

Daily verification window

PROMPT_COUNT

3

Prompts each day

MIN_GAP_MINUTES

180

Minimum time between prompts

COUNTDOWN_DURATION_MINUTES

5

Time allowed to respond

MAX_FACE_ATTEMPTS

3

Attempts before PIN fallback

FACE_MATCH_THRESHOLD

0.70

Minimum face-match score

Failure & Privacy Handling

  • No connection: verification continues with the locally stored profile.

  • Missing profile: the app restores it from the registry or starts enrollment.

  • Failed upload: updates remain queued until the device reconnects.

  • Expired prompt: the app records a MISSED event.

  • Local protection: audit events use an encrypted database and secure storage.

The app stores one-way face embeddings, not reconstructable face images. A face profile can unlock only its matching signed-in worker. Logout and user switches clear local face data.

Technical reference

1. Architecture and implementation details

The system is split into three layers:

  • App layer (health_campaign_field_worker_app) — owns policy: when to gate, when to prompt, what to log, how to sync.

  • Package layer (digit_face_verification) — self-contained ML + UI.

  • Shared layer — data models and sync infrastructure used across the app.

App layer

Category
Components

Pages

FaceGatePage, PinFallbackPage, FaceAuthHistoryPage, NonMobileUserListPage, NonMobileFaceEnrollPage

Widgets

ReVerificationListener, reverification popup/sheet, countdown banner, FaceVerificationDialog

Blocs

FaceGateBloc, ReVerificationBloc

Services

ReVerificationScheduler, FaceAuthEventLogger, WorkerRegistryService, NotificationService, FaceDataCleanupService

Package layer

Category
Components

Views

FaceEnrollmentView, FaceVerificationView, FaceCaptureView, LivenessChallengeView, CustomPinPad

Blocs

FaceEnrollmentBloc, FaceVerificationBloc, LivenessBloc

Data

FaceModelService (TFLite), LivenessDetectionService, FaceEmbeddingRepository (Isar), PinService

Assets

mobilefacenet.tflite, audio cues (add.wav, buzzer.wav)

Shared layer

  • digit_data_model — FaceAuthEventModel, oplog

  • transit_post — FaceAuthEvent local/remote/oplog repositories

  • sync_service — SyncService, SyncLock

2. ML Pipeline

Item
Value

Model

MobileFaceNet (TFLite), bundled at packages/digit_face_verification/assets/models/mobilefacenet.tflite

Input

112 × 112 × 3 cropped face (JPEG-encoded crop retained for audit)

Output

192-dimension embedding vector

Similarity metric

Cosine similarity (utils/distance_metrics.dart)

Match threshold

Default 0.70; overridable from MDMS (FACE_MATCH_THRESHOLD, currently 0.75 on demo)

Duplicate-enrollment threshold

0.75 — a new enrollment whose embedding matches an existing profile above this is rejected (FaceEnrollmentBloc.duplicateThreshold)

Face detection/landmarks come from ML Kit via the camera stream in FaceCaptureView; lighting quality is assessed (lighting_assessment.dart) before capture.

Liveness detection

LivenessDetectionService requires active challenges before an enrollment is accepted:

  • Blink — eye-open probability crossing 0.7 → 0.3 → 0.7

  • Head turn — left/right

Verification flows use the same service via LivenessChallengeView.

3. Enrollment

Entry points

  • System user (distributor) — FaceGatePage routes to FaceEnrollmentView on first login after authentication (HomePage._checkFaceEnrollment → FaceGateRoute).

  • Co-worker (non-mobile user) — sidebar → Non mobile users → NonMobileFaceEnrollPage, performed on the supervisor/distributor device.

Flow (FaceEnrollmentView)

  1. Intro screen (steps + logout escape hatch).

  2. Capture 5 angles: straight, left, right, up, down.

  3. Liveness challenge pass.

  4. Duplicate check against all locally stored profiles (≥ 0.75 → rejected with duplicateDetected; device cap reached → maxUsersReached).

  5. A backup PIN is generated and shown once. Only SHA-256(salt:pin) + a 16-byte random salt are stored (PinService) — the PIN itself is never persisted.

  6. Profile persisted locally and pushed to the worker registry. GPS is captured for the enrollment audit event.

  7. FaceAuthEventLogger.logEnrollment writes an ENROLLMENT audit event into the sync pipeline

Sequence diagram for Enrollment

4. Verification Flows

4.1 Login gate (FaceGatePage + FaceGateBloc)

After HCM login, the gate matches the camera face only against the logged-in user's own embedding (never all profiles — a co-worker's face or PIN must not unlock another user's session).

Outcomes:

  • Face match ≥ threshold → proceed (LOGIN / FACE_SUCCESS event).

  • Max attempts (MDMS MAX_FACE_ATTEMPTS, default 3) → PIN fallback (PIN_FALLBACK) → HCM-password fallback (HCM_FALLBACK).

  • If the local embedding is missing (fresh install), the bloc attempts WorkerRegistryService.syncEnrollmentFromRegistry to restore the enrollment from the server; fails open to enrollment when offline.

Login gate sequence diagram

4.2 Periodic re-verification

Wired in AuthenticatedPageWrapper (lib/pages/authenticated.dart):

  • ReVerificationScheduler generates PROMPT_COUNT random prompt times inside START_HOUR–END_HOUR, at least MIN_GAP_MINUTES apart. The day's schedule is persisted in SharedPreferences and reused for the rest of the day (a same-day MDMS timing change only takes effect after a config-change restart or the next day).

  • On trigger: countdown banner (_ReVerificationCountdownBanner) + bottom sheet (Verify Now / Remind Me Later) with a COUNTDOWN_DURATION_MINUTES timer, and an "Attempt X of Y" AppBar counter. Expiry logs MISSED.

  • Triggers are deferred (markPending) while no enrollment exists, on the FaceGate/enrollment routes, or when the app is backgrounded — a local notification fires instead; tapping it (even cold-start) re-dispatches the trigger (_checkNotificationLaunch, pending-tap drain).

  • Supervisors are exempt (TEAM_SUPERVISOR, DISTRICT_SUPERVISOR roles → face_reverify_skip).

  • Attendance-register additionalDetails.startHour/endHour override the MDMS window when an active register exists for today.

  • App resume calls scheduler.checkNow() to catch missed windows.

Periodic re-verification sequence Diagram

4.3 Co-worker verification

When the system user verifies, pending co-workers on today's attendance register are prompted next (coWorkerPendingNotifier, "System user must verify their face first before co-workers can proceed"). Co-worker embeddings are prefetched from the worker registry after login (_prefetchCoWorkerEmbeddings) so verification works offline later. Events are logged with the co-worker's individualId and the subject name in additionalFields.

4.3 Co-worker verification

When the system user verifies, pending co-workers on today's attendance register are prompted next (coWorkerPendingNotifier, "System user must verify their face first before co-workers can proceed"). Co-worker embeddings are prefetched from the worker registry after login (_prefetchCoWorkerEmbeddings) so verification works offline later. Events are logged with the co-worker's individualId and the subject name in additionalFields.

5. Server Configuration (MDMS, tenant-scoped)

5.1 Configuration

Fetched live (never cached) by MdmsRepository.searchFaceAuthConfig each time the authenticated wrapper mounts (login / app start):

Key
Default (client)
Purpose

START_HOUR / END_HOUR

8 / 18

Re-verification window

PROMPT_COUNT

3

Prompts per day

MIN_GAP_MINUTES

180

Minimum spacing between prompts

COUNTDOWN_DURATION_MINUTES

5

Response window per prompt

MAX_FACE_ATTEMPTS

3

Attempts before PIN fallback

FACE_MATCH_THRESHOLD

0.70

Cosine-similarity cutoff

5.2 Service registry (HCM-SERVICE-REGISTRY.serviceRegistry)

Required entry (present on demo under AttendanceService):

entityName must be exactly FaceAuthEvent (matched by camelCase against DataModelType.faceAuthEvent). The app refreshes its cached registry when the MDMS module-version changes; without that bump a device keeps its first-install registry.

5.3 Access control (ACCESSCONTROL-ACTIONS-TEST / role-actions)

The DIGIT gateway 401s any URI not mapped to the caller's roles. The worker-registry endpoints must be mapped for enrolling roles (e.g. DISTRIBUTOR):

  • /worker/v1/_search — present on demo (action id 4124).

  • /worker/v1/bulk/_update — must also be mapped; without it the embedding push fails with HTTP 401 and stays queued (known gap on demo as of 2026-07-20).


6. Local Data Model & Storage

Store
Contents

Isar (FaceEmbeddingRepository)

Per-individual profile: primary embedding, per-angle embeddings (flattened, angleCount × 192), model version, isSystemUser, enrolledBy, enrollment profile (PIN hash + salt, enrolledAt, supervisorApprovalStatus, twinFlagged)

Encrypted SQLCipher DB (LocalSqlDataStore)

FaceAuthEvent rows + oplog entries for sync

FlutterSecureStorage

Session/user data, isFaceEnrollmentComplete, userIndividualId, DB encryption key, SyncLock

SharedPreferences

Day schedule + completed prompt indices, face_reverify_skip, pending worker-registry queues (face_registry_sync_pending, face_registry_sync_pending_ids), notification bookkeeping

FaceAuthEventModel (audit event) — field reference

Field
Description

clientReferenceId

UUID for the event

individualId

Subject of the event

eventType

One of LOGIN, CHECK_IN, RE_VERIFY, ENROLLMENT

outcome

One of FACE_SUCCESS, FACE_REJECTED, PIN_FALLBACK, HCM_FALLBACK, MISSED

confidence

Match confidence score

latitude / longitude / locationAccuracy

GPS at time of event

timestamp

Event time

failedAttemptCount

Number of failed attempts leading to this event

fallbackReason

Reason fallback was triggered

popupTime / responseTime / responseType

Re-verification prompt timing; responseType is one of FACE, PIN, DISMISS, TIMEOUT, ATTEMPT

anomalyFlags

Flags raised during the event

faceImage

Optional base64 112×112 crop for review

projectId / tenantId

Scoping identifiers

Audit details

Includes createdBy (system-user UUID — required for oplog pickup)

additionalFields

App-only fields: isSync, deviceId, boundaryCode, syncTimestamp


7. Sync Architecture

7.1 FaceAuthEvent audit events (oplog → sync service)

Standard HCM offline-first path: local create writes the row + an oplog entry; SyncService.performSync (manual Sync Data button, and the background service) bulk-uploads via FaceAuthEventRemoteRepository.bulkCreate → POST /health-attendance/face-auth/v1/bulk/_create (HTTP 202 = accepted by the async persister).

Wired in:

  • Constants.getLocalRepositories / getRemoteRepositories (background isolate)

  • NetworkManagerProviderWrapper (UI providers)

  • attemptSyncUp (utils.dart) — manual sync repo lists

  • EntityMapper (sync_service_mapper.dart) — sync count / response mapping

⚠️ A pending oplog type with no matching remote repository throws Remote repository is not passed to sync service and blocks the whole sync — this is what a missing/stale service-registry entry looks like.

7.2 Worker registry (enrollment data)

Direct calls (not oplog-based), handled by WorkerRegistryService:

  • Push after enrollment: _search worker by individualId, then POST /worker/v1/bulk/_update with face fields in additionalDetails.fields (embedding, angle embeddings, model version, PIN hash+salt, enrolledBy, approval status…).

  • Pull: syncEnrollmentFromRegistry restores a profile from the server (login-gate restore; co-worker prefetch).

  • Offline queues: a failed push leaves the ID queued —

    • face_registry_sync_pending (self-enrollment, FaceGatePage)

    • face_registry_sync_pending_ids (co-workers)

    • Drained by _retryPendingWorkerRegistrySync in AuthenticatedPageWrapper on mount and on every offline→online transition.

    • updateWorkerWithFaceEnrollment returns true for success or terminal states (dequeue), false only for retryable network failures.

Data sync sequence Diagram

8. Localisation

All UI codes are FACE_AUTH_* (153 codes) under module hcm-common for every locale (en_DEMO, pt_DEMO, fr_DEMO on demo). hcm-common is in Constants.initialLocalizationModules, so codes are cached at boot for the selected locale.

The package's FaceVerificationLocalization.translate resolves from its own delegate rows first, then falls back to the app-level AppLocalizations resolver via the static appTranslate hook (set in getAppLocalizationDelegates) — this keeps package screens localised even when the package delegate's one-shot row snapshot is stale.


9. Security & Privacy

  • Raw face images are not stored as a gallery; only the 112×112 crop optionally rides along on audit events (faceImage) for review.

  • Embeddings are one-way features; the model never reconstructs faces.

  • PIN: salted SHA-256 only; shown once at enrollment.

  • Event rows live in the SQLCipher-encrypted DB; keys in secure storage.

  • Login gate matches strictly against the logged-in user's profile — co-worker embeddings on the same device cannot unlock a session.

  • SSL pinning enforced by DioClient; bad certificates always rejected.

  • FaceDataCleanupService handles local face-data removal (logout / user-switch hygiene).



Last updated

Was this helpful?