Skip to content

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.

GET/api/dxos:manifest
Public
Returns the static Web App Manifest (application/manifest+json) for /v/mobile with zero tenant or user PII.
GET/api/dxos:sw.js
Public
Serves the Service Worker script with Service-Worker-Allowed: / and Cache-Control: no-cache, no-store, must-revalidate.
GET/api/dxos:icon-192.png
Public
Serves the deterministic 192x192 PNG app icon (max-age=86400); a 512x512 variant is served at /api/dxos:icon-512.png.

Cache 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.

PWA Assets and Cache Directives
ParameterTypeDefaultDescription
/v/mobile
text/htmlno-cacheField app shell injected with manifest, icon links, and Service Worker registration.
/api/dxos:manifest
application/manifest+jsonmax-age=300Defines start_url=/v/mobile, display=standalone, and orientation=portrait-primary.
/api/dxos:sw.js
application/javascriptno-storeService Worker (aliased at /api/dxos:sw) fetched fresh on navigation checks.
/api/dxos:icon-192.png
image/pngmax-age=86400192x192 maskable/any PNG icon for PWA installation and iOS home screen.
/api/dxos:icon-512.png
image/pngmax-age=86400512x512 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.

Outbox Capacity Limits and Lifecycle States
ParameterTypeDefaultDescription
MAX_OUTBOX_ITEMS
number50Maximum concurrent queued mutations; exceeding this cap throws OFFLINE_QUEUE_FULL.
MAX_OUTBOX_PAYLOAD_BYTES
number327680 (320 KB)Maximum serialized JSON payload size for items without an evidence photo.
MAX_PHOTO_DATA_URL_BYTES
number524288 (512 KB)Maximum raster data URL length (PNG, JPEG, WebP) for evidencePhotoDataUrl.
MAX_OUTBOX_TOTAL_BYTES_WITH_PHOTO
number786432 (768 KB)Maximum total serialized JSON size when an evidence photo is attached.
VALID_OUTBOX_STATUSES
enumpendingAllowed item states: pending, syncing, failed, quarantined, and synced.
Outbox Item Schema
ParameterTypeDefaultDescription
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
enumpendingpending | syncing | failed | quarantined | synced.
attempts
integer0Flush 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.

actionTypeTarget EndpointMethodOperational Purpose
wms.epodCapture/api/dxosWms:epodCapturePOSTSubmits electronic proof of delivery with GPS coordinates, signature, and photo evidence.
iot.twinSetDesired/api/dxosBlocks:twinSetDesiredPOSTUpdates the desired temperature or operating setpoint on a cold-chain Digital Twin.
service.ticketCreate/api/latticeServiceTickets:createPOSTCreates a field maintenance or customer service ticket while offline.
iot.incidentCreate/api/dxosBlocks:alarmIngestPOSTReports 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 GroupResulting Item StatusflushOfflineQueue Behavior
2xxsynced (removed)Increments synced and deletes the item from IndexedDB or fallback storage.
401failed (flush paused)Sets unauthorized: true, pauses remaining items as deferred, and awaits fresh authentication (NOCOBASE_TOKEN).
400, 403, 404, 409, 422quarantinedRetains the item in quarantine with lastError and httpStatus so operators can inspect, edit, or discard it manually.
408, 429, 5xx, network errorfailedIncrements 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.

json
{
  "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.

text
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-8841

Parsed 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:

buildEpodPayload Field Validation Rules
ParameterTypeDefaultDescription
recipientNamerequired
string—Non-empty recipient name truncated to 128 characters.
deliveredQty
number0Non-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 activate hook deletes any cache key not matching latticedx-field-pwa-v0.4.2 and claims active tabs immediately.
  • If NOCOBASE_TOKEN expires (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 KB prior to base64 encoding so the full JSON item stays within the 768 KB per-item limit.

Apache-2.0 · LatticeDX v0.4.2 · Powered by NocoBase · v2.2.50 · Apache-2.0 (Clause 5.2)