Mobile Field PWA
The Mobile Field PWA at /v/mobile provides an offline-capable interface for drivers, warehouse operators, and field technicians executing electronic proof of delivery (ePOD), IIoT setpoint commands, service tickets, and incident reports inside cold storage facilities or low-connectivity transit corridors. Instead of caching authenticated API payloads in browser HTTP caches, the application separates static shell delivery from an IndexedDB mutation outbox.
Serving Architecture and Service Worker Lifecycle
The LatticeDX gateway serves /v/mobile via createMobilePwaGatewayHandler behind the public Nginx route configuration (10-lattice-public-routes.sh). On GET or HEAD /v/mobile, the handler injects <meta name="theme-color">, <meta name="apple-mobile-web-app-capable" content="yes">, the manifest link, touch icon metadata, and an inline registration script into the Client-v2 HTML shell.
Once /api/dxos:sw.js registers at scope /, the client posts a PRECACHE_ASSETS message containing static asset URLs extracted from the HTML document (/assets/*, /v/assets/*, /v/global.css, /v/browser-checker.js). sanitizePrecacheAssets rejects any path containing .. or %2f to prevent path traversal.
/api/dxos:manifest/api/dxos:sw.js/api/dxos:icon-192.pngCache Boundaries and Security Invariant
The Service Worker (CACHE_NAME = latticedx-field-pwa-v0.4.2) applies network-first with cache fallback exclusively to /v/mobile, the manifest, the two PNG icons, and static assets matching STATIC_ASSET_RE.
Every /api/* request outside those three static PWA endpoints executes strictly in NetworkOnly mode so tenant-scoped JSON responses are never stored in Cache Storage. isCacheableResponse rejects redirected responses, non-basic responses, responses with Cache-Control: no-store or private, and any response containing Set-Cookie.
| Parameter | Type | Default | Description |
|---|---|---|---|
/v/mobile | text/html | no-cache | Field app shell injected with manifest, icon links, and Service Worker registration. |
/api/dxos:manifest | application/manifest+json | max-age=300 | Defines start_url=/v/mobile, display=standalone, and orientation=portrait-primary. |
/api/dxos:sw.js | application/javascript | no-store | Service Worker (aliased at /api/dxos:sw) fetched fresh on navigation checks. |
/api/dxos:icon-192.png | image/png | max-age=86400 | 192x192 maskable/any PNG icon for PWA installation and iOS home screen. |
/api/dxos:icon-512.png | image/png | max-age=86400 | 512x512 maskable/any PNG icon for mobile splash screens. |
IndexedDB Offline Outbox (latticedx-mobile-outbox)
The mobile-offline-db.js module manages offline mutations through a three-tier storage fallback chain: IndexedDB (latticedx-mobile-outbox version 1, object store outbox with keyPath id and indexes status, createdAt) first, localStorage (latticedx:mobile:offline-queue) when IndexedDB is unavailable, and an in-memory Map as a final fallback.
Before persisting any entry, stripForbiddenKeys recursively removes __proto__, constructor, and prototype up to depth 16 to block prototype pollution. Browser storage exhaustion (QuotaExceededError) raises OFFLINE_STORAGE_QUOTA_EXCEEDED.
| Parameter | Type | Default | Description |
|---|---|---|---|
MAX_OUTBOX_ITEMS | number | 50 | Maximum concurrent queued mutations; exceeding this cap throws OFFLINE_QUEUE_FULL. |
MAX_OUTBOX_PAYLOAD_BYTES | number | 327680 (320 KB) | Maximum serialized JSON payload size for items without an evidence photo. |
MAX_PHOTO_DATA_URL_BYTES | number | 524288 (512 KB) | Maximum raster data URL length (PNG, JPEG, WebP) for evidencePhotoDataUrl. |
MAX_OUTBOX_TOTAL_BYTES_WITH_PHOTO | number | 786432 (768 KB) | Maximum total serialized JSON size when an evidence photo is attached. |
VALID_OUTBOX_STATUSES | enum | pending | Allowed item states: pending, syncing, failed, quarantined, and synced. |
| Parameter | Type | Default | Description |
|---|---|---|---|
idrequired | string | — | Deterministic identifier formatted as mq-<ts36>-<seq36>-<uuid8>, capped at 128 chars. |
actionTyperequired | string | — | One of the 4 allowlisted ALLOWED_OFFLINE_ACTIONS keys. |
endpointrequired | string | — | Target NocoBase resource action derived automatically from actionType. |
payloadrequired | object | — | Sanitized JSON mutation payload checked against byte ceilings. |
status | enum | pending | pending | syncing | failed | quarantined | synced. |
attempts | integer | 0 | Flush attempt counter incremented on network or HTTP failures. |
httpStatus / lastError | integer | string | — | Last HTTP status code and error message truncated to 240 characters. |
conflictData | object | null | — | Sanitized server record returned on HTTP 409 with base64 media fields masked. |
Supported Offline Actions (ALLOWED_OFFLINE_ACTIONS)
To keep offline permissions bounded, the outbox accepts only four allowlisted action keys. Any unknown actionType fails with UNSUPPORTED_OFFLINE_ACTION on enqueue or quarantines with HTTP 400 during flush.
actionType | Target Endpoint | Method | Operational Purpose |
|---|---|---|---|
wms.epodCapture | /api/dxosWms:epodCapture | POST | Submits electronic proof of delivery with GPS coordinates, signature, and photo evidence. |
iot.twinSetDesired | /api/dxosBlocks:twinSetDesired | POST | Updates the desired temperature or operating setpoint on a cold-chain Digital Twin. |
service.ticketCreate | /api/latticeServiceTickets:create | POST | Creates a field maintenance or customer service ticket while offline. |
iot.incidentCreate | /api/dxosBlocks:alarmIngest | POST | Reports a field equipment alarm or cold-chain incident for triage. |
Queue Synchronization and Conflict Quarantine
When connectivity resumes (navigator.onLine === true), flushOfflineQueue processes all non-quarantined entries ordered by createdAt and seq. Server HTTP responses map deterministically to three outcomes:
| HTTP Status Group | Resulting Item Status | flushOfflineQueue Behavior |
|---|---|---|
2xx | synced (removed) | Increments synced and deletes the item from IndexedDB or fallback storage. |
401 | failed (flush paused) | Sets unauthorized: true, pauses remaining items as deferred, and awaits fresh authentication (NOCOBASE_TOKEN). |
400, 403, 404, 409, 422 | quarantined | Retains the item in quarantine with lastError and httpStatus so operators can inspect, edit, or discard it manually. |
408, 429, 5xx, network error | failed | Increments attempts and keeps the item queued for the next sync cycle. |
For 409 version conflicts, extractConflictData captures the server payload (serverRecord) and runs maskConflictMediaFields to replace base64 image or signature strings with a placeholder string, capping conflictData at 4096 serialized bytes.
{
"total": 4,
"synced": 2,
"failed": 0,
"quarantined": 1,
"conflicts": 1,
"deferred": 1,
"unauthorized": false,
"results": [
{ "id": "mq-0001", "actionType": "wms.epodCapture", "status": "synced" },
{ "id": "mq-0002", "actionType": "iot.twinSetDesired", "status": "quarantined", "httpStatus": 409, "error": "Version conflict" }
]
}QR/Barcode Parser and buildEpodPayload
parseFieldQrPayload normalizes camera or handheld scanner strings up to 2048 characters (MAX_QR_PAYLOAD_LENGTH). It blocks control characters, <, >, \, .., unsafe URI schemes (javascript:, data:, vbscript:), and raw JSON keys named __proto__, constructor, or prototype before invoking JSON.parse.
1. JSON object: {"trackingCode":"LDX-TRK-2026-001","orderId":42,"targetTempC":-18}
2. Full NGSI-LD URN: urn:ngsi-ld:Asset:org-a:native:104
3. Short NGSI-LD URN: urn:ngsi-ld:Asset:104
4. Tracking code: LDX-TRK-2026-001
5. Stock lot code: LOT-2026-CC-09
6. Order code: ORD-2026-8841Parsed outputs return { valid: true, kind, ... } containing the matched identifiers: urn, entityType, organizationId, source, entityId, assetId, trackingCode, trackingToken (ldx_trk_*), lotCode, orderCode, orderId, and targetTempC (accepting targetTempC or setpointC within [-80, 120] °C).
buildEpodPayload validates every field before dispatching to dxosWms:epodCapture or enqueuing into latticedx-mobile-outbox:
| Parameter | Type | Default | Description |
|---|---|---|---|
recipientNamerequired | string | — | Non-empty recipient name truncated to 128 characters. |
deliveredQty | number | 0 | Non-negative finite delivered quantity (>= 0). |
gpsLat / gpsLng | number | — | Finite coordinates in [-90, 90] and [-180, 180]; required unless gpsUnavailable is true. |
gpsUnavailableReason | string | — | Required (max 240 chars) when gpsUnavailable=true, such as underground cold dock signal loss. |
signatureDataUrlrequired | string | — | Signature raster data:image/* URI capped at 256 KB. |
evidencePhotoDataUrl | string | — | Optional PNG, JPEG, or WebP data URI up to 512 KB. Rejects data:image/svg+xml. |
targetTempC | number | — | When parsed from JSON QR payloads, must be a finite number in [-80, 120] °C. |
Operational Notes
- During platform upgrades, the Service Worker
activatehook deletes any cache key not matchinglatticedx-field-pwa-v0.4.2and claims active tabs immediately. - If
NOCOBASE_TOKENexpires (isJwtTokenExpired), queued mutations remain intact in IndexedDB until the operator signs in again and triggers a flush. - Compress field photos to JPEG or WebP below
400 KBprior to base64 encoding so the full JSON item stays within the768 KBper-item limit.
