Skip to content

ePOD & Public QR Verification ​

The Electronic Proof of Delivery (ePOD) subsystem bridges @latticedx/plugin-dxos-studio (wms-engine.js, qr-svg.js, public-track-html.js) with the cryptographic ledger in @latticedx/plugin-lattice-foundation (pki-ledger.js) to bind physical handoffs to immutable Ed25519 signatures. Drivers capture signatures, GPS coordinates, and raster delivery photos from the /v/mobile Field PWA (with IndexedDB offline queueing), while external recipients scan voucher QR codes at /v/track/:code to verify authenticity without exposing internal tenant data.

Cryptographic Signing and Merkle Verification Architecture ​

Ed25519 PKI Signing, Merkle Ledger & Public QR Verification
IMMUTABLE HASH-CHAINED LEDGER, ED25519 SIGNING & MERKLE TREEPUBLIC EPOD QR HMAC PROOF & /V/TRACK/:CODE VERIFICATIONJSONSHASignTreeQR Token#verify=VerifydxosLedger:verifyMerkle ProofBusiness / ePODMutationlatticeEpodRecordsCanonical JSON +SHA-256payloadHashDeterministic JSONPG16 Advisory LockAppendlatticeCryptoLedgerprevHash -> entryHashPer-Org Ed25519SignlatticePkiKeysAES-256-GCM WrapBinary SHA-256Merkle RootcomputeMerkleRoot:verify · :exportePOD QR HMAC ProofHMAC-SHA256#verify= FragmentPublic Track Portal/v/track/:codeNonce CSP · MaskedPublic SignatureVerifyGET/POST:verifyTrackSignature
InspectorPG16 Advisory Lock AppendClick any component to inspect bindings & boundaries
Role
Immutable Hash-Chained Audit Ledger
Package / Port
pki-ledger.js · pg_advisory_xact_lock
Protocol
pg_advisory_xact_lock(hashtext('latticedx:ledger:' || orgId))
Payload / Schema
seq · payloadHash · prevHash -> entryHash · LEDGER_IMMUTABLE
Responsibilities
Serializes per-org appends under pg_advisory_xact_lock, chains prevHash (64 zeros at seq=1) into entryHash, and blocks updates/deletes.
ePOD mutations are canonicalized and SHA-256 hashed, serialized under pg_advisory_xact_lock into latticeCryptoLedger (prevHash -> entryHash), signed with per-org AES-256-GCM-wrapped Ed25519 keys, and aggregated into a binary Merkle root for public /v/track/:code verification.

Each ePOD entry forms a linked record inside the per-organization hash chain (latticeCryptoLedger), serialized by PostgreSQL transaction advisory lock pg_advisory_xact_lock(hashtext('latticedx:ledger:' || orgId)) so sequence numbers (seq) remain strictly monotonic under concurrent writes.

ePOD Capture and Validation Rules ​

The dxosWms:epodCapture endpoint accepts delivery confirmation directly from online clients or replayed from the /v/mobile offline outbox (wms.epodCapture). It enforces strict payload bounds on signatures, coordinates, and raster images before issuing tracking credentials.

POST/api/dxosWms:epodCapture
Bearer JWT | ldx_pat_*write, wms
Records delivery proof, appends an Ed25519-signed ledger entry, issues a trackingToken, and completes the order.
Input Parameters and Bounds for dxosWms:epodCapture
ParameterTypeDefaultDescription
recipientNamerequired
string—Full name of the consignee accepting delivery (max 128 characters).
deliveredQtyrequired
number—Delivered quantity (>= 0).
signatureDataUrlrequired
string—Signature image Data URL (max 256 KB); hashed via SHA-256 into signatureSha256.
gpsLat / gpsLng
number—Valid coordinates within lat [-90, 90] and lng [-180, 180].
gpsUnavailable
booleanfalseSet to true when delivering inside shielded cold rooms or underground docks.
gpsUnavailableReason
string—Required when gpsUnavailable=true (max 255 characters) explaining why GPS is absent.
evidencePhotoDataUrl
string—Raster evidence photo in PNG, JPEG, WebP, or GIF format (max 512 KB; SVG rejected).
tempSummary
object—Transit temperature summary containing mktCelsius and boolean inRange.

Once validated, the database transaction executes five atomic updates:

  1. Generates epodUid (EPOD-...), public trackingCode (LDX-TRK-...), and a single-issue trackingToken (ldx_trk_..., persisted strictly as its SHA-256 trackingTokenHash).
  2. Masks the recipient phone number into recipientPhoneMasked before storing the record in latticeEpodRecords.
  3. Appends wms.epod_captured (scope: 'dxos:epod') to latticeCryptoLedger and stores ledgerSeq, ledgerSignatureBase64, and keyId on the ePOD row.
  4. Transitions latticeOrders to completed and linked latticeOrderLines to delivered.
  5. Records a delivered_by edge in latticeDataLineage for end-to-end supply-chain traceability.
bash
curl -X POST https://app.example.com/api/dxosWms:epodCapture \
  -H "Authorization: Bearer ldx_pat_a1b2c3d4_..." \
  -H "Content-Type: application/json" \
  -d '{
    "orderCode": "ORD-2026-0192",
    "recipientName": "Nguyen Van A",
    "deliveredQty": 120,
    "gpsLat": 10.0299,
    "gpsLng": 105.7706,
    "signatureDataUrl": "data:image/png;base64,iVBORw0KGgo...",
    "tempSummary": { "mktCelsius": 4.6, "inRange": true }
  }'

Hashing Math, Ed25519 Signatures, and HMAC QR Proofs ​

Document integrity relies on two independent cryptographic primitives: an Ed25519 signature stored in the internal append-only ledger and an HMAC-SHA256 proof embedded in printed QR vouchers.

text
payloadHash = sha256Hex(canonicalJson(payload))
prevHash    = (seq === 1) ? "0".repeat(64) : prevEntry.entryHash
entryHash   = sha256Hex(`${orgId}|${seq}|${eventType}|${targetCollection}|${targetRecordId}|${payloadHash}|${prevHash}|${recordedAtIso}`)
signature   = Ed25519.sign(`${orgId}|${seq}|${entryHash}`, unwrappedOrgPrivateKey)

Per-organization Ed25519 private keys in latticePkiKeys are encrypted at rest with AES-256-GCM derived from ENCRYPTION_FIELD_KEY || APP_KEY. When rendering a delivery voucher via dxosWms:printVoucher (supporting Unicode HTML-to-PDF export through Gotenberg DXOS_GOTENBERG_URL), the embedded QR SVG (qr-svg.js) encodes /v/track/<trackingCode>#verify=<qrVerificationHash>:

text
verifySecret       = LATTICE_TRACK_VERIFY_SECRET || ENCRYPTION_FIELD_KEY || APP_KEY
qrVerificationHash = HMAC-SHA256(verifySecret, `${org}|${trackingCode}|${epodUid}|${trackingTokenHash}|${ledgerSeq}`)

Because #verify= resides in the URL fragment, browsers do not transmit the proof token in HTTP request URLs or reverse-proxy access logs; client-side script reads the fragment and posts it directly to the verification API.

Public Tracking Portal (/v/track/:code) and CSP Hardening ​

The Nginx public gateway (10-lattice-public-routes.sh) routes /v/track/* to public-track-html.js, which issues a fresh cryptographic script/style nonce on every HTTP response under a strict Content Security Policy:

text
default-src 'none'; script-src 'nonce-<n>'; style-src 'nonce-<n>'; img-src data:; connect-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'self'

The portal queries two public endpoints, dxosWms:publicTrack and dxosWms:verifyTrackSignature, both enforcing constant-time comparisons (timingSafeEqualHex) against token hashes and HMAC proofs:

GET/api/dxosWms:publicTrack
Public (trackingCode + trackingToken)
Returns PII-masked delivery status, MKT temperature summary, and ledger signature verification.
POST/api/dxosWms:verifyTrackSignature
Public (trackingToken or #verify proof)
Recomputes entryHash and verifies the Ed25519 signature against the non-revoked public key in latticePkiKeys.
Verification ModeCredentials ProvidedpublicProofOnlyReturned Payload
QR #verify= fragmenttrackingCode + verifytrueverified, epodUid, ledgerSeq, entryHash, keyId, publicKeyFingerprint, signedAt, requiresTokenForDetails: true
Full trackingTokentrackingCode + tokenfalseFull cryptographic proof alongside order reference and tempSummary
bash
curl -X POST https://app.example.com/api/dxosWms:verifyTrackSignature \
  -H "Content-Type: application/json" \
  -d '{
    "trackingCode": "LDX-TRK-81D2A4C90E",
    "verify": "9b74c9897bac770ffc029102a200c5de..."
  }'

Offline ePOD Capture from the Field PWA (/v/mobile) ​

Inside shielded cold rooms or dead cellular zones, /v/mobile queues ePOD payloads in IndexedDB latticedx-mobile-outbox (version 1, object store outbox) under action wms.epodCapture. The outbox flusher enforces strict size bounds and classifies HTTP responses during replay:

Parameter / HTTP StatusConfigured Limit / StateSynchronization Behavior
MAX_OUTBOX_ITEMS50 itemsRejects new offline captures once the local outbox reaches 50 pending items.
MAX_OUTBOX_PAYLOAD_BYTES320 KB / 768 KB (with photo)Validates payload byte length prior to storing in IndexedDB (with localStorage fallback).
HTTP 400, 403, 404, 409, 422quarantinedMoves the item to quarantined and masks base64 media inside conflictData.
HTTP 401Flush pausedPauses queue draining until the driver re-authenticates via Keycloak OIDC.
HTTP 408, 429, 5xx, or network errorfailedRetains the payload for automatic retry on the next connectivity cycle.

Security Boundaries and Failure Modes ​

ControlEnforcement BehaviorError Code / Outcome
Ledger immutabilityORM and database hooks reject any update or delete attempt on latticeCryptoLedger.Raises LEDGER_IMMUTABLE; out-of-band tampering breaks entryHash and Merkle verification.
Public key revocationverifyEpodLedgerSignature checks active status and organizationId on latticePkiKeys before Ed25519.verify.Revoked or cross-tenant keys immediately return verified: false.
Constant-time rejectionMissing trackingCode or invalid trackingToken / verifyProof executes timingSafeEqualHex against DUMMY_HASH_HEX.Returns 401 TRACKING_UNAUTHORIZED without leaking prefix or length timing.

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