# Dyspash Universal Arrival Check-In — Protocol Specification v1

**Status:** Published 2026-07-09 · Token prefix `DYSP1`
**Reference implementation:** the Dyspash iOS app (issuer) and this validation server (verifier).

This document specifies everything needed to *issue* or *verify* Dyspash arrival
tokens, so any warehouse system, TMS, or driver app can interoperate. The goal:
one check-in experience at every facility — arrive, tap check in, show QR.

---

## 1. Design principles

1. **The QR contains no personal information.** No names, phone numbers,
   coordinates, or shipment details — only one-time identifiers, timestamps, and
   a signature. A photographed QR leaks nothing and replays nothing.
2. **The phone owns arrival facts; the server owns workflow state.** Arrival
   records are signed on-device and stored verbatim; validation/doors/status
   live server-side.
3. **Verification requires no installation.** Any camera + browser validates.

## 2. Token format

A token is the ASCII string:

```
"DYSP1." + base64url( COSE_Sign1 )
```

where `base64url` is RFC 4648 §5 without padding, and `COSE_Sign1` is a CBOR
(RFC 8949) structure per RFC 9052, wrapped in CBOR tag **18**:

```
18( [ protected: bstr, unprotected: {}, payload: bstr, signature: bstr ] )
```

In QR codes the token is carried either bare, or as the URL
`https://<validation-host>/a/<token>` so scanning opens a browser directly.
Total payload budget: **≤ 300 bytes** (reference tokens measure ~215 bytes,
≈293 chars, QR version ~13 at ECC level M).

### 2.1 Protected header (CBOR map, encoded as bstr)

| Label | Value | Meaning |
|---|---|---|
| 1 | -7 | Algorithm: ES256 (ECDSA P-256 + SHA-256) |
| 4 | bstr(8) | `kid` — first 8 bytes of the signer's key ID (§4) |

### 2.2 Payload claims (CWT, RFC 8392; CBOR map encoded as bstr)

| Label | Type | Claim |
|---|---|---|
| 4 | uint | `exp` — expiry, Unix seconds (issuers SHOULD use issue + 24 h) |
| 6 | uint | `iat` — issued at, Unix seconds |
| 7 | bstr(16) | `cti` — one-time token ID (random; never reused) |
| -65537 | bstr(16) | Opaque driver pseudonym (stable per device) |
| -65538 | bstr(16) | Opaque load pseudonym (stable per trip) |
| -65539 | tstr | Arrival event ID (UUID string; joins the announced record) |
| -65540 | bool | `offline` — true when device-signed without server issuance |
| -65541 | uint | Token schema version — **1** for this spec |

### 2.3 Signature

Raw 64-byte `r ‖ s` ECDSA P-256 signature over the COSE `Sig_structure` for
`Signature1` (RFC 9052 §4.4):

```
[ "Signature1", protected_bstr, external_aad: h'', payload_bstr ]
```

CBOR-encoded with definite lengths. Verifiers MUST rebuild `Sig_structure`
from the received protected and payload byte strings — never from re-encoded
values.

## 3. Verification procedure

1. Strip `DYSP1.`, base64url-decode, CBOR-decode; require tag 18 and a
   4-element array.
2. Decode the protected header; require `alg == -7`. Extract `kid`.
3. Look up the registered device key whose key ID (§4) starts with `kid`
   (hex). Unknown key → **not verified** (tier: unregistered).
4. Rebuild `Sig_structure` and verify the raw signature with the key.
5. Enforce `exp`.
6. Enforce one-time use of `cti`: on first validation, mark consumed; on
   re-scan, display *first validated at &lt;time&gt; by &lt;facility&gt;* rather than
   rejecting (legitimate re-scans at the dock happen).
7. Join claim -65539 to the announced arrival record for display fields.

**Trust tiers** (from the registered key's class): `secureEnclave` → High,
`software` → Medium, unregistered → Not verified. Display the tier; do not
pretend binary certainty.

## 4. Device keys & arrival records

- Device key: P-256. Public key is exchanged as **X9.63** (65 bytes,
  `04 ‖ X ‖ Y`). **Key ID** = lowercase hex SHA-256 of the X9.63 bytes.
- Arrival record: canonical JSON — compact separators, **keys sorted
  lexicographically** — signed with ECDSA P-256, **DER** encoding, over the
  exact canonical bytes. Records chain per device via `prevRecordHash`
  (SHA-256 hex of the previous record's canonical bytes; `"genesis"` first).
- Records carry wall clock AND monotonic uptime + boot time; disagreeing
  deltas between consecutive records expose clock tampering.
- Departure reports sign the canonical JSON
  `{"departedAt":<ISO8601>,"recordID":<uuid>,"ver":1}` with the same key.

## 5. Validation server HTTP contract

| Method & path | Body / params | Purpose |
|---|---|---|
| POST `/v1/devices/register` | `{keyID, publicKeyX963(b64), keyClass, apnsToken?}` | Anonymous device registration |
| POST `/v1/devices/erase` | `{keyID, publicKeyX963(b64), purpose:"erase", ts, ver:1, signatureDER(b64)}` — the device signs `canonicalJSON({keyID, publicKeyX963, purpose:"erase", ts, ver:1})` (`lib/erasure.mjs eraseCanonical`; Wire §7 `probes/erase.json`) with its own key; `ts` ISO 8601 within ±5 min | **Delete my data** (Phase 1 Step 10 DEL), in-app only on both phones. Verified against the registered key when a devices row exists (a request naming another key is **401**), else against the request's own `publicKeyX963` after `keyID = sha256(publicKeyX963)` (announce does not require registration). Scrubs the identity data tied to that key and retires it — push tokens (`apnsToken`, `fcmToken`, `location_push_token`) null, the key revoked, the announce's `driverPhone` null on every arrival the key announced, the pre-check-ins' unsigned `driverLabel` / `note` null, `driver_name` / `driver_phone` null on the tenant-less loads (origin `app`) the key's yard events created, `driverPhone` / `driverPhoneNorm` null on walk-in appointments created from its arrivals, a bound identity anonymized (`anonymizeIdentity`, its passkeys revoked, its opt-in position deleted) — and **keeps every signed byte** (arrival canonicals, yard events, probes, the facility rail) and the stop documents, photos and signatures filed with the facility as its record of the visit (`wire/v1/conformance/data-erasure.json` `server` rows). **200 `{ok:true, already:false}`** scrubbed; **200 `{ok:true, already:true}`** a repeat (nothing left to change); **404 `{held:false, error}`** no row of any kind holds the key (the phone still erases its own side — and only on this body: a 404 without `held:false`, from a server that predates the route or a proxy, and a 2xx without `ok:true` erase nothing on the phone); **401** no / bad signature or a foreign key; **422** `ts` outside ±5 min; **400** malformed. One office audit row `device.erase` per 200 (the key id's first 16 hex characters and counts, never PII). Synchronous on the phone (15 s, never queued); no migration. |
| POST `/v1/arrivals/announce` | signed record fields (see reference); **Simple Flow (SF-2):** two UNSIGNED optional envelope members `trailerEmptyWeightLbs`, `trailerMaxWeightLbs` (non-negative integers, omitted when unset — the `driverPhone` rule), stored on the arrival row as side metadata and signed by the FACILITY inside `gate.checked_in` (`trailerEmptyLbs`, `trailerMaxLbs`) at bind; malformed → ignored, never a rejection; nothing enters the signed canonical | Store arrival verbatim; server re-verifies DER signature before accepting. **Return to a stop already left:** an announce whose `reasonCode` starts `return_` (`return_rework`, `return_yard_incident`, `return_other`; detection is by PREFIX) REJOINS the arrival record this device already has for that load instead of minting a new one — `arrivedAt` (the detention anchor) is never disturbed and the visit code is not re-minted. Response carries `{ok, episode: {anchorRecordID, anchorArrivedAt, visitIndex, returnedAt, reasonCode, visitCode, reopened}}`. The return announce is still stored verbatim as signed evidence; it simply is not a second board card. **The anchor is the signed instant** (Step 6 S7): when the unsigned envelope `arrivedAt` differs from the canonical's signed `arrivalWallClock` by more than 2 s, the signed value is stored as `arrivedAt` and an audit row `arrival.anchor_corrected {envelope, signed}` is written; an unparseable canonical (or one with no wall clock) keeps the envelope. Never a rejection. |
| POST `/v1/tokens/validate` | `{token}` | JSON verdict (machine integrations) |
| GET `/a/{token}` | — | Human receiver page; validates + consumes |
| POST `/a/{token}/action` | `facility?, action, door?` | validated / door_assigned / at_door / loading / loaded / paperwork_ready / rejected |
| POST `/a/{token}/upload` | multipart: `kind`, `file` | Facility paperwork → driver |
| GET `/v1/arrivals/status?recordID=` | — | `{status, door, reports}` (+ `visitCode`, `dockCheck`, `gate`, `yard` when present; `reports: [{purpose, trigger, status, sentAt}]` — one entry per stop report sent or being sent, newest first, no recipient; `[]` until one exists). Polling a RETURN announce's `recordID` serves the ANCHOR's live state — same door, same visit code — plus `episode: {anchorRecordID, anchorAt, returns: [{returnedAt, reasonCode, reason, leftAt}]}`. Step 6 S7: `facility` (null until bound) also carries `id`, `policies {autoCheckIn, detentionThresholdMinutes, signatureRequired}` and `policySource` (`facility` \| `default`, the capabilities resolver), and a `detention` block `{anchorAt, thresholdMinutes, thresholdAt, policySource, thresholdRecordID, thresholdRecordedAt}` — the episode anchor (the first arrival, never a return), the facility's free time (the 120-minute default while unbound or when the bound facility never saved its free time — `policySource: "default"` then; `facility.policySource` stays the row's), when that free time on the property runs out (the sweep's claim walk over the episode's visits: time off the property between a departure and a return is never free time used; a single visit ends at anchor + threshold), and the facility-signed `detention.threshold` record and its signed instant once the sweep stamps it (null before). Minutes only, never an amount. **Simple Flow (SF-2, Wire §6.1.4 (f)):** `facility` += `shortCode`, `companyName` (null until set); `facility.siteBrief` += `requirements[]` (common `siteRequirement` values, catalog order), `restroomDirections`, `restroomNote` (verbatim \| null), `translations` (`translationEntry[]`, `[]`) — and the brief is non-null when only requirements are saved; new top-level **`load`** `{shipmentID, loadCode, reference, referenceKind, shipperName, destinationShortCode, carrierShortCode, trailerWeights {emptyLbs, maxLbs, source driver\|carrier\|placard\|null, placardHash}, requirements[]}` — null until the bound appointment names a shipment (the carrier's weights win over the driver's announced ones); new **`facilityRelease`** `{at, undoneAt}` — null until the board's Release ran (read from the stop's own `arrival.release` / `arrival.release_undone` audit rows, never from `departed`; the hero's one-tap Depart input); `visitCode` unchanged — it IS the load code once bound. **SF-11c (F-37):** `dockCheck` (null until bound) carries `complete: null` while `dockCheck.status` is null — nothing directed, "not asked" (`missing []`, `covered []`); once the facility directs the proofs (`status` requested \| submitted \| verified) `complete` is coverage's boolean, unchanged. Phones key on `status` first and read a null `complete` — and a pre-SF-11c `true` beside a null `status` — as "not asked". |
| GET `/v1/arrivals/documents?recordID=` · GET `/v1/documents/{id}?recordID=` | — | Paperwork list / download |
| POST `/v1/arrivals/departed` | `{recordID, departedAt, signatureDER(b64)}` | Signed departure (§4). **`departedAt` never moves backwards** (Step 6 S6): a verified departure signed earlier than the one on record — a superseded post arriving late, after the stop was reopened by an undo and left again — answers 200 `{ok:true}` and moves nothing, so the phone's lane settles and the board keeps the real departure. |
| POST `/v1/arrivals/undo` | `{recordID, kind, undoneAt, signatureDER(b64)}` — the device signs `JSON.stringify({kind, recordID, undoneAt, ver:1})` with the ARRIVAL's key; `kind` `arrival` \| `departure`; `undoneAt` whole seconds `Z` (the instant the driver tapped — the phones send their correcting yard event's `occurredAt`) | The driver's ten-minute undo of an AUTOMATIC stamp (Wire §6.1.5, §7 `probes/undo.json`). `arrival` cancels the card; `departure` reopens the record (`departedAt` cleared, so the detention episode and the sweep resume) — on a RETURN announce it reopens the anchor. The appointment the stamp moved goes back with a signed `appointment.updated {status, action:"driver_undo"}` (`departed` → `checked_in`, the one path out of a terminal status; `checked_in` → `en_route` / `scheduled`; a walk-in the arrival created is cancelled) unless a facility act (any non-system facility event on it) followed the stamp, in which case nothing moves and the answer says `appointment: {reopened:false, reason:"facility_acted"}`. **Window on the signed `undoneAt`:** more than 12 min after the stamp or more than 2 min before it is **422** (final); late delivery of a timely tap passes. A repeat of the same signed probe answers **200 `{already:true}`** (recognised from its audit row, which is written before the state change and read newest-first, together with the state: a repeat whose state change was lost applies it again, and an old probe never reopens a departure stored later than its `undoneAt`); a `departure` undo whose departure has not landed yet is **404** (retry, like a probe behind its announce); a `departure` undo signed BEFORE the departure on record is **422 `a later departure is on record`** (Step 6 S6: it undoes an earlier departure, never the one the truck really made, and nothing moves). Response `{ok, status, appointment?}`. The `arrival.undo_arrival` / `arrival.undo_departure` webhook carries the signed probe as `record` (eventType `undo_<kind>`, schemaVersion 1, `prevRecordHash` genesis — the `driver.departed` shape). |
| POST `/v1/pushes/{pushID}/ack` | device-signed `{canonicalJSON(b64), signatureDER(b64), keyID}` over the `dispatchEventV1` form `{assignmentID, eventType:"dispatch.acknowledged", loadRef, occurredAt, prevRecordHash, pushID, recordID, schemaVersion:2}` (+ the optional `seenAt`, Wire §6.1.4 (b)) | The driver's own signature that a facility instruction was on screen (Phase 1 Step 6 S10; vector `event-dispatch-acknowledged.json`). `assignmentID` = the push's appointment, `pushID` = the path segment, `occurredAt` within ±5 min (the phones sign at send time, a fresh `recordID` per attempt), `loadRef` the arrival's verbatim, `prevRecordHash` `"genesis"`; a replay answers by `pushID` first. The alert that announced the instruction carries `pushID` and (when the push names one) `appointmentID` in its custom data — the caller's own values never win — and the poll's `pushes[]` rows carry the additive `door` the instruction named; the Dock board shows "Seen HH:MM" / "Not seen yet" for the newest ackable instruction. Doors are capped at 40 characters on every assign path and the yard move. |
| GET\|HEAD `/f/{facilityID}` | — | Public (Phase 1 Step 6 S9): the page a facility's check-in QR opens in any phone camera — a VERIFIED facility's name and how to check in with Dyspash (Play link; the App Store link only when `APP_STORE_URL` is set), nothing else; `Cache-Control: public, max-age=300`, `nosniff`. An unknown, unverified or non-UUID id (checked before any store read) is **404**. The phones read the id out of the URL itself (Wire `conformance/facility-qr.json`). |
| GET `/v1/facilities/search?q=` | — (public; the `api` rate class) | **Simple Flow (SF-2; §18.1 #5):** the phones' walk-in facility search by short code — `q` must normalise (ASCII letters and digits, upper) to ≥ 2 characters (**400** otherwise); matched and ranked by the any-order rule of `wire/v1/conformance/short-code.json` (`lib/shortcode.mjs`: `001ca`, `horham`, `cahorham001`, `ca-horham`, `001 CA Hor` all find `CA-HorHam-001`; since SF-11e (F-22) a run is cut every way per candidate, so a digit-led or two-letter company part finds its facility too — `3m`, `ca 3m 001`, `ge`, `tx ge 001` — and a bare two-letter query lists its state's codes before a company that starts with those letters; hyphens, spaces, symbols, case ignored, non-ASCII dropped); **200** `{facilities: [{id, name, companyName, shortCode, city, state, timeZoneID}]}`, ≤ 10 rows, VERIFIED facilities with a short code only — no phone, address or e-mail (the `/f/{id}` stance); `Cache-Control: no-store`. The phones' `ShortCodeMatcher` twins rank a local cache offline by the same table (SF-7). At any registry size the answer is exact and the server reads a bounded number of rows by index (SF-13d, migration 135); until that migration is applied the answer is an empty list. |
| POST `/v1/appointments/lookup` | device-signed `{keyID, ts, signatureDER}` over `canonicalJSON({keyID, purpose:"appointment_lookup", ts, ver:1, phone?, code?, facilityID?})` (Wire §7 `probes/appointment-lookup.json`, bytes unchanged) | Phase 126 (D7). **Simple Flow (SF-2):** `code` is signed as an opaque string — 6 characters are the appointment code as today (the ±12 h / 48 h window); **4 valid visit-alphabet characters are a LOAD code** (`common.loadCode`) → the shipment's receiver appointment (any window, status scheduled \| en_route \| checked_in). **SF-13c (D8, RV-03): the lookup is read-only** — the shipment moves `created\|sent → linked` (and `load.linked` is sent) when the phone pre-checks in on that appointment (`POST /v1/arrivals/precheckin` + `appointmentID`); a bind moves it straight to `checked_in`. A device key that sends **20 distinct four-character codes that match nothing within an hour** is answered **429** `{error:"too many codes tried — check the code with dispatch"}` for every four-character code until the hour (from its first miss) ends; a hit never counts, a repeated code counts once. The budget is **20 distinct misses per key per hour on each server machine (40 with today's two)** (`lib/lookupguard.mjs`; SF-13h R3, Dustin's ruling of 2026-11-08): device keys are anonymous, so the per-IP `auth` bucket is the cap across keys, and a store counter would cost a database write per miss and stop nothing a key-minter cannot route around. The phone path reads the 60-hour window in the query and answers the 25 soonest, plus `more: true` when there were more (RV-16). Answer: `appointments[]` rows carry the appointment 1.1.0 members (`loadCode`, `shipmentID`, `shipperFacilityID`, `referenceKind`, `carrierShortCode`, `windowDateOnly`, `requirementsSnapshot`); `facility` keys `id, name, shortCode, siteBrief, timeZoneID`; optional **`load`** = the status poll's block + `destination {facilityID\|null, shortCode\|null, name, city, state}` — answered even when the destination is not on Dyspash (`appointments: []`, `facility: null`); `load: null` when nothing names a shipment. An unknown or released four-character code answers `appointments: []` (a new phone against an older server degrades the same way). |
| POST `/facility/checkin-code` | facility session (clerk+), `code` — its own `gate` rate class (60 burst, 1/s per IP; F-20) **and** 300 keyed codes an hour per facility session (R-04; 429) | Phase 87: a keyed VISIT code checks the truck in like a scan (binds the facility + the appointment / walk-in). **Simple Flow (SF-2; §18.8 Q6):** resolves the visit code FIRST (an announced truck, unchanged); else a four-character **LOAD code** — the load's receiver appointment at THIS facility: already bound → "already checked in"; unbound and `scheduled` → signed `appointment.updated {action:"precheckin"}` (en_route) + the notice "Load K7M3 — PO 4471, <carrier> expected — the driver checks in on the phone or by QR"; a live code at ANOTHER facility — a load code, or the announced truck's visit code once the bind adopted it — answers the unknown-code sentence "No live visit for code X." and writes no audit row, exactly like an unknown code (F-25: no cross-facility oracle on the page or on the facility's own `/f1/events` trail). A clerk never mints an arrival without a device key. |
| GET `/facility/short-code/check?state=&company=` | facility session (admin) | **Simple Flow (SF-2; §18.1 #9):** the first-run wizard's live uniqueness probe against the ONE short-code namespace (facilities AND carriers, the `short_codes` registry): `{ok, state, company, suggested, nextNumber, preview "SS-NNNNNN-FFF", conflict: null \| {kind:"company"} \| {kind:"exhausted"}}` — a different company name holding (state, company6) is the conflict (**409**, with `suggested`; the holder's name is never disclosed); the same company gets its next number; the facility's own row answers its number. Nothing is claimed here (SF-3's `POST /facility/setup/short-code`). |
| GET `/facility/setup` · GET\|POST `/facility/setup/{1..6}` | facility session (admin) | **Simple Flow (SF-3; §18.1 #10, §18.3):** the first-run wizard — `/facility/setup` resumes at the first unfinished step; the six steps (1 company name · 2 complete address, HERE typeahead through `/facility/address-suggest` · 3 "how many dock doors?" → the editable door list = `doors_json`, the ONE dock count · 4 the truck-entrance pin · 5 keyed driver requirements + restroom directions/note as typed + the eleven photo boxes + proof deadline · 6 the short code, suggested, live-checked, the number assigned from the registry). One Continue per step, PRG, no JavaScript needed; a validation 400 re-renders the step with `role="alert"`. Each step is a signed `facility.settings_updated {section}` — `company`, `address` (the street as a SHA-256), `doors`, `site_brief` (the pin, from the row), `site_requirements` (+ `rules` / `site_brief` when the photo boxes / deadline moved), `short_code`. Finish stamps `setup_completed_at` and adopts the `shipments` already addressed to the facility by short code or typed address (their receiver appointments are created then). The board carries a "Finish setup" banner until the stamp; the confirm page offers the wizard once. |
| POST `/facility/settings/company` · `/facility/settings/address` · `/facility/settings/entrance` · `/facility/settings/site-requirements` · POST `/facility/setup/short-code` | facility session (admin) | **Simple Flow (SF-3):** the wizard's writes as settings fragments for later edits, hosted by GET `/facility/settings` (`#company`, `#address`, `#site-requirements`, `#short-code`); PRG back to the anchor with `in=<anchor>`. `/facility/settings/entrance` is the PARTIAL pin write (only `entrance_lat` / `entrance_lon` move; the rest of the Site Brief stays; signs `site_brief` from the row — never the whole-form `/facility/settings/site-brief`). The short code is permanent once assigned: a second claim answers the held code; a company rename follows the facility's registry row (`renameShortCodeCompany`, both stores) so its prefix stays its own. |
| GET `/facility/loads` · GET\|POST `/facility/loads/new` · GET `/facility/loads/{id}` · POST `/facility/loads/{id}/send` · `/email` · `/cancel` | facility session (clerk+) | **Simple Flow (SF-4; §18.1 #11, §18.3):** the shipper's ONE form — PO# or BOL# (`referenceKind` po \| bol \| other) · Deliver to (a short code typed in any spelling resolves exactly, no JavaScript needed; a typeahead pick carries the facility id, honoured only while the text still equals the label it was picked with — what a clerk overtypes wins with JavaScript off; a typed address of a verified facility books it at create by the adoption keys (street + ZIP, no HERE key needed); an unmatched address stays as the destination text until that facility finishes setup) · optional carrier short code · optional driver phone · optional delivery date → `lib/shipments.mjs` create → **303** to the code page: the four-character LOAD code, the handoff text (Copy), **Text to driver** through `lib/sms.mjs` when `TWILIO_*` is set (else the composed one-segment GSM-7 text is shown to copy), **E-mail** through `lib/email.mjs` when `RESEND_*` is set (else "not set up — copy the text"), **Cancel** (the receiver's appointment is cancelled with it — a signed `appointment.cancelled` on the receiver's chain with the shipper's actor; the code stops connecting and is released after the grace). A text or e-mail moves the load `created → sent` and writes a `load_messages` row with a keyed hash of the recipient (HMAC-SHA-256 under `SESSION_SECRET`) and the SHA-256 of the body only. Cancel answers **503** and leaves the load untouched when the receiver's live row could not be withdrawn. A receiver row already past the gate or departed is never cancelled (SF-13a, D5): a load whose status lags it is healed from the row (→ checked in / departed) and the page answers "This load is <its status now> — it cannot be cancelled from here." The list shows the loads THIS facility sent with status chips; another facility's id is **404** on every route; a viewer is **403**. The receiver's board lists the load as an Expected row (📦 CODE · PO/BOL · the shipper · the carrier · the day). |
| GET `/facility/destination-suggest?q=&scope=facility\|carrier` | facility session (clerk+); `api` rate class (SF-12a) | **Simple Flow (SF-4):** the "Deliver to" typeahead — `{suggestions: [{kind: "facility" \| "address" \| "carrier", label, facilityID, shortCode, name, companyName, city, state, line1, zip}]}`, ≤ 8 rows, `[]` below three characters; `facility`: the any-order short-code matches (verified, coded facilities, never this facility itself), then HERE rows (`lib/addresssuggest.mjs`, behind the server — the key never reaches the browser) joined to verified facilities by normalised street + ZIP (`verifiedFacilitiesByZip`), an unjoined address offered as text; `carrier`: the carrier short codes this facility used before that match `q`. Inserted as text nodes only; `Cache-Control: no-store`. |
| GET `/l/{code}` | — (public; the `api` rate class) | **Simple Flow (SF-4; §18.1 #13):** the texted load link's landing page for a FOUR-character load code (the N1 consignee link `/l/{16–128 hex}` keeps the rest of the prefix). HTML in the `Accept-Language` locale (en, es, pa, ru, pt-BR, zh-Hans; `Vary: Accept-Language`): the code in large type (tap to copy), the destination company + city (a destination not on Dyspash: its short code when one was typed, else nothing), the reference KIND only, **Open in Dyspash** (`dyspash://load/{code}`), **Get the app** (`APP_STORE_URL` / `PLAY_STORE_URL` + `&referrer=load%3D{code}` once the listings exist; `TESTFLIGHT_URL` / `PLAY_INTERNAL_URL` until then), "or type K7M3 in the app"; a cancelled or departed code → "no longer active — ask dispatch" (**200**, no Open button); an unknown or out-of-alphabet code → **404**. Never the reference number, the phone, the shipper or an address; `Cache-Control: no-store`, `noindex`. |
| GET `/.well-known/assetlinks.json` | — (public) | **Simple Flow (SF-4):** the Android Digital Asset Links statement for `com.dyspash.tripreporter` — `delegate_permission/common.handle_all_urls` with the fingerprints in `ANDROID_CERT_SHA256` (comma-separated, upper-cased) — so the installed app opens `https://<host>/l/{code}`; **404** until the env is set (the link then opens the landing page, which carries the code). The AASA (`/.well-known/apple-app-site-association`, with `APPLE_APP_ID`) gains the component `{"/": "/l/????"}` beside `/join/*` — four single-character wildcards, so N1's hex tokens keep opening in the browser. |
| GET `/carrier` · GET\|POST `/carrier/claim` · GET\|POST `/carrier/confirm/{token}` | — (public; `auth` rate class on the claim and the link's POST, `api` on the link's GET) | **Simple Flow (SF-9; §18.1 #15):** the dispatcher's portal. Claim the carrier's short code (`TX-TrnNun-001`) — or create one from the company name, the home state and six characters, the next number from the ONE `short_codes` namespace (owner_kind carrier) — with a work e-mail → a one-hour magic link (shown inline when e-mail is not configured — for a CREATE claim; a claim BY CODE answers everyone the uniform page and the member's pending link is on the admin's Settings, F-38). **The link is opened in two steps (F-27, SF-11a):** the GET renders one POST button and never signs in, sets no cookie and writes nothing; only `POST /carrier/confirm/{token}` signs in (a browser's cross-site POST — `Sec-Fetch-Site: cross-site`, or a foreign / `null` Origin — is **403**). Creating a code writes NOTHING before the link is opened — the create fields ride in a signed `carrierclaim.` token and `/carrier/confirm` creates the tenant, claims the number and makes the opener the admin (single-use; a taken code is **409** there). The link activates the `carrier_users` row (the first user is the admin; once a carrier has a user — pending or active — a stranger's claim by the public code answers the **same 200 page** a member gets and mints / mails nothing (F-12: no membership oracle — invites come from Settings); a pending link never revokes a session, only Disable does, and an admin's re-invite of a disabled user re-enables it when opened) and sets `dyspash_carrier={tenantID}.{userID}.{role}.{exp}.{hmac}` (HMAC over `carrier.…` — never a facility, board or worker session). It does **not** attach the loads shippers addressed to the code before the claim (F-01): each waits for ITS shipper's `POST /facility/loads/carrier-confirm {shortCode, decision}` (the banner on `/facility/loads`); the notice and the `carrier.claim` audit's `preClaimLoads` say how many are waiting; a shipper whose last answer about the holder was "not ours" has its NEXT typed load to that code held pre-claim too, the create notice naming the holder, until it confirms (R-01). Every mailed or printed link is built from `PUBLIC_BASE_URL`, never the request's Host header (F-02; since SF-12a the facility claim, team invite, worker sign-in, worker join poster, `/b/confirm` and SSO `redirect_uri` links too). Before migration 131 every `/carrier/*` page (the confirm landing included) and every `/c1/*` read answers **503** naming the migration (F-13). A facility's code is **400**, an unknown code **404** with the create fields pre-filled. |
| GET `/carrier/inbox` · GET `/carrier/loads/{id}` · POST `/carrier/loads/{id}/send` · `/email` · `/weights` · `/placard` (multipart) · GET\|POST `/carrier/drivers` · POST `/carrier/drivers/{phone}/placard` | carrier session (viewer reads; dispatcher+ writes) | **Simple Flow (SF-9):** the inbox (code · PO/BOL · destination · date · status) with one-click **Text** (the phone remembered per driver in `carrier_drivers`), **Copy** (the handoff text) and **Email**; the Load page adds the carrier's trailer weights and the optional placard: the weights write `shipments.trailer_*` / `weights_source` (carrier, or placard when a photo rides) and are signed on the RECEIVER's chain as `appointment.updated {action:"weights", weightsSource, emptyLbs, maxLbs, placardHash}` with `actor {kind:"carrier", id:<tenant>, role, label:<short code>}` — the placard bytes are a storage blob (`carrier/{tenant}/placards/{sha256}`), only the hash rides. A text / e-mail writes a hashes-only `load_messages` row and moves the load `created → sent`. The driver's own announced weights never show here (P5). Another carrier's load is **404**; a viewer's POST **403**. |
| GET\|POST `/carrier/integrations` · GET\|POST `/carrier/settings` | carrier session (admin) | **Simple Flow (SF-9):** API keys (phase-11 `api_keys` + migration-131 `scopes`: `loads:read loads:write drivers:write webhooks:manage`, shown once ON THE PAGE the POST answers — **201**, never a redirect's query string — revocable), webhooks (phase-11 `webhooks` by tenant, the `load.*` vocabulary; a minted signing secret is shown once the same way) with their outbox counts, the TMS field mapping (JSON `{theirField: canonicalField}`); the team: invite (magic link; an active member is refused, a disabled one is re-enabled when the new link is opened) / disable; the company and its code. |
| `/c1/*` — GET `/c1/me` · GET `/c1/loads?since=` · GET `/c1/loads/{id}` · POST `/c1/loads` · PATCH `/c1/loads/{id}` · POST `/c1/loads/{id}/send` · `/cancel` · GET\|POST `/c1/drivers` · GET\|PUT `/c1/field-mapping` · GET\|POST `/c1/webhooks` · DELETE `/c1/webhooks/{id}` · GET `/c1/webhooks/{id}/deliveries` · POST `/c1/webhooks/{id}/replay` · `/test` | carrier API key (`Authorization: Bearer`); scopes; `Idempotency-Key` on every write | **Simple Flow (SF-9; `Docs/DOCK-API.md` §4.9):** the carrier API — the same data as the portal for a TMS. Loads are the carrier's by its claimed tenant id or its short code; `POST /c1/loads` is a CARRIER-originated load (its own code, no shipper) that mints the four characters and books the receiver (a signed `appointment.created` with `actor.kind carrier` on the receiver's chain); the field mapping is applied inbound and inverted on every answer. Webhooks `{id, event, at, tenantID, replay, data:{load}, record:null}` — `load.assigned` · `load.sent` · `load.linked` · `load.checked_in` · `load.departed` · `load.cancelled` · `webhook.test` — through a SECOND durable outbox over `carrier_webhook_deliveries` (128's columns with `tenant_id`), the same four `X-Dyspash-*` headers and HMAC; replay rebuilds from the carrier's loads. Idempotency claims live in `carrier_idempotency_keys` (the (facility_id, key) PK of 128 is untouched). Outside the key's scopes **403** `{error:"scope", required}`; a non-carrier tenant's key **403**; another carrier's load **404**. Writes are the `auth` rate class, `GET /c1/loads` the `api` class. |
| GET `/facility/checkin-poster` | facility session (any verified role) | The printable "Driver check-in poster": the facility's name and its `/f/{id}` QR (zero-dependency `lib/qr.mjs`), linked from `/facility/settings`. |
| POST `/v1/capabilities` | device-signed probe `{keyID, ts, signatureDER}` over `{keyID, purpose:"capabilities", ts, ver:1}` (+ optional `facilityID`) | Phase 124 / P20: `{ver, generatedAt, ttlSeconds, modules[], policies{autoCheckIn, detentionThresholdMinutes, signatureRequired}, facilityID, policySource, thresholdSource}` — Wire `capabilities.schema.json` (1.1.0). Enrollment not required; unknown facility ⇒ safe defaults + `policySource:"default"`. Step 6 S7 (additive): `thresholdSource` (`facility` \| `default`) — the free time's own source; `default` for a known facility that never saved its free time. |
| GET/POST `/v1/admin/module-flags` · POST `/v1/admin/facility-policy` | `ADMIN_TOKEN` (`x-admin-token` or Bearer); `{scope: global\|tenant:<id>\|device:<keyID>, moduleID, enabled}` · `{facilityID, autoCheckIn?, signatureRequired?}` | Ops switches behind the capabilities read (404 when `ADMIN_TOKEN` unset). Base modules are never flaggable. |

## 5b. Network facility stats (Phase 18)

Anonymized, device-signed facility intelligence: dwell samples append, 1–5 truck
ratings upsert (one per device per facility). No PII travels — the facility key
(lowercased name), minutes, and the rating only.

| Endpoint | Body | Result |
| --- | --- | --- |
| POST `/v1/facilities/stats` | `{keyID, facilityKey, dwellMinutes?, rating?, signatureDER}` signed over sorted-key JSON `{dwellMinutes, facilityKey, rating, ver: 1}` | Stores sample/rating; returns the aggregate |
| GET `/v1/facilities/stats?key=` | — | `{dwellAvgMinutes, dwellSamples, ratingAvg, ratingCount}` |

## 5c. Broker live-share (Phase 19)

A driver mints a tokenized board link for a broker: live HOS-aware ETA, trip
progress, stop state, reefer set point, and 2-way messaging. All status math runs
on the phone and arrives device-signed; the server only displays it. Every share
minted for the same broker name lands on one grouped board. Brokers can re-share
a single truck as a read-only viewer link (no chat) — the driver is push-notified
when that happens, and viewer links for one recipient group onto one page.

| Endpoint | Body | Result |
| --- | --- | --- |
| POST `/v1/broker/share` | signed `{brokerName, destCity, destState, loadRef, ver: 1}` + trip fields, `kind` ("broker" grouped board with re-share \| "receiver" direct single-truck share, messaging only), and `apptDateOnly` (the appointment is a DAY, not an instant) | `{shareID, path: "/b/{token}"}` (expires 7 days). **Idempotent:** the same device re-sharing the same load to the same recipient board returns its live link instead of a second card |
| POST `/v1/broker/status` | signed `{etaAt, progressFraction, shareID, ver: 1}` + unsigned display fields (below) | Upserts the truck's live status |
| POST `/v1/broker/message` · GET `/v1/broker/messages?shareID=&keyID=` | signed send / capability read | Driver side of the thread |
| POST `/v1/broker/revoke` · GET `/v1/broker/mine?keyID=` | signed / capability | Manage the device's shares |
| GET `/b/{token}` | — | Broker board (grouped, chat + re-share) |
| POST `/b/{token}/message` · POST `/b/{token}/share` | form | Broker chat (pushes to the driver) / mint viewer link |
| GET `/bv/{token}` | — | Read-only grouped viewer board |

**Status display fields** (outside the signed canonical; the server sanitizes
and only displays them): `leg`, `pickupApptAt`, `provisionalEtaAt` (pickup-leg
HOS-aware delivery projection, rendered muted and labeled "projected, before
loading" — never as the live ETA), `currentPlace`, `moving`, `stoppedMinutes`
(a stop only counts after 5 stationary minutes), `endOfShift`, reefer fields,
`stops` (≤10 ordered stops, `{city, state, kind?, appointmentAt?, done}`),
`traffic` (≤4 congestion intervals `{start, end, level: slow|heavy, delayMin?}`
striped onto the bar), and `blocks`/`blocksTZ` — ≤480 classified 15-minute
trip time blocks `{s: ISO start, m: minutes, k: drive|traffic|load|unload|
break30|rest10|restart34|fuel|wait}` rendered as the board's day-row timeline
(solid = happened, hollow = the plan; a Timeline/Bar toggle persists per
browser).

**Appointments.** The share row's appointment updates from a status push only
when the push carries `apptEdited: true` alongside `appointmentAt` (+
`apptDateOnly`) — a deliberate guard so re-sent values can never silently
revert a board-side "Move appointment". Date-only appointments are stored as
the driver's local start-of-day, displayed as the date ("any time"), and
computed as **23:59 of that day** in every capacity/margin/scheduling
calculation.

## 5d. Auto-send documents (Phase 19b)

| Endpoint | Body | Result |
| --- | --- | --- |
| POST `/v1/documents/email` | signed `{filename, subject, to, ver: 1}` + `pdfBase64`, `note?` | Emails the PDF via Resend (503 when email isn't configured); nothing stored |

## 5e. Receiver smart scheduling (Phase 20)

The facility (receiver) sets its dock variables; the Inbound page charts every live
share destined to its city/state — using the same leg-aware truck cards as the
broker board — and, when a truck's phone-computed ETA runs ≥1 h ahead of its
appointment, suggests the earliest open, under-capacity dock slot that helps the
driver and the dock together. Proposing it reuses the appointment-move machinery:
the share updates, the thread gets a message, and the driver's phone gets the
alert push + in-app Update/Keep pop-up.

| Endpoint | Auth | Purpose |
| --- | --- | --- |
| GET `/facility/inbound` (`?format=json`) | facility session | Inbound chart + suggestions (HTML or JSON) |
| POST `/facility/scheduling` | facility session (admin) | Set `{openDays, openStart, openEnd, docksPerHour, minNoticeMinutes}` |
| POST `/facility/inbound/propose` | facility session (clerk+) | Propose a suggested appointment to the driver |
| GET `/v1/facilities/{id}/inbound` | API key (Bearer / X-API-Key) | Machine-readable inbound picture + suggestions |

| POST `/facility/dock-notice` · POST `/facility/dock-notice/cancel` | facility session (clerk+) | Live capacity exceptions: `pause` (incident, lunch) or `slowdown` (`override`/hr) for N minutes — presets + custom. Creating one reroutes suggestions, banners every board, and pushes + thread-messages every inbound driver; cancelling announces "back to normal". |

Engine (`lib/scheduling.mjs`, pure): slot grid = 60/docksPerHour minutes inside
open days/hours (facility-local via Intl, zero dependencies); candidate ≥
max(ETA + 30 min, now + minNoticeMinutes); capacity = booked appointments per
hour < docksPerHour; suggestion must be strictly earlier than the current
appointment.

## 5f. Pre-arrival check-in & dock audits (Phase 21)

One tap announces "inbound, ETA X" for the CURRENT leg — the shipper (outbound)
or receiver (inbound) — before the truck arrives. The facility board grows an
**Expected** section where a door can be pre-assigned (one-shot; first facility
wins); the real signed arrival links by device key + load ref and inherits the
door and facility binding, so the truck lands on the board already doored.
Drivers get queue transparency ("3 trucks ahead", one-shot "you're next" push)
and the dock's best arrival window. Facilities can mint read-only dock-audit
links (`/ba/{token}`) showing one visit's full timeline + dwell metrics — sent
to brokers so they can see what actually happened to their driver.

| Endpoint | Auth | Purpose |
| --- | --- | --- |
| POST `/v1/arrivals/precheckin` (+`/cancel`) | device-signed `{appointmentID?, destCity, destState, direction, etaAt, facilityID, loadRef, paperworkReady, sealIntact, ver: 1}` (`JSON.stringify` in that key order; `appointmentID` only when sent — Wire §7 `probes/precheckin.json`) | Upsert per (key, load, direction); 36 h ETA window. With `appointmentID` the later announce binds to that appointment (`via: "precheckin"`). Since Phase 1 Step 6 S9 both phones call it synchronously from Fast Check-In's "Find my appointment" (10 s, never queued) under the `loadRef` their arrival then signs. A declared `facilityID` that is not a UUID stays undeclared (a facility row is never read by it). |
| GET `/v1/precheckin/status?id&keyID` | keyID capability | `{status, door, facilityName, queueDepth, dockNotice, linkedRecordID}` |
| POST `/facility/precheckins/{id}/action` | facility session (clerk+) | `preassign` (one-shot door claim → driver push) / `dismiss` |
| POST `/facility/arrivals/{recordID}/action` | facility session (clerk+) | The board card's writes: `assign` (door; **Simple Flow SF-5** — the card's door is a CHIP ROW, one button per door, no confirm(): a reassign or an in-use door answers with a 10 s undo toast whose form posts the previous door back; the rail records every assign), the stage actions, `reject`, `release` (**SF-5**: one button from `door_assigned` on, no confirm(), no broker field — the recipients are the report rules; the `released`-trigger report rows are queued `next_attempt_at = now + RELEASE_UNDO_MINUTES` (default 10; 0 = due at once); the toast and the board's "Released — undo" strip carry the undo for the window; a second Release answers "already released" and sends nothing twice; a Release after the driver's own departure never overwrites the driver's `departedAt`) and **`release_undone`** (SF-5: within the window — status back to the stage the release found, `departedAt` cleared, the not-yet-sent `released` rows marked dead `release undone` and REPLACED by the next Release, a signed `appointment.updated {action:"release_undone", status}` moving the appointment back to its live status and the shipper's load back to `checked_in`, the status poll's `facilityRelease.undoneAt` set, the driver pushed; after the window → refused with a toast, the release stands). |
| POST `/facility/arrivals/{recordID}/audit-share` · GET `/ba/{token}` | clerk+ mint / token capability | Read-only dock-audit timeline + dwell metrics; driver is push-notified on mint |
| GET `/v1/facilities/window?keyID&facilityID\|city+state` | registered device key | Next open under-capacity dock slots (12 h horizon) |
| POST `/v1/admin/precheckins/cleanup` | ADMIN_TOKEN | Purge stale rows |

`/v1/yard_events` additionally accepts **driver-signed** posts (no API key):
`keyID` + verbatim `canonicalJSON`/`signatureDER` verified against the registered
device key; events attach to the existing load for that reference (the shipper
keeps ownership) or create a tenant-less load. Boards render per-leg timelines
("Pickup leg" / "Delivery leg") built from pre-checkins, the facility audit
trail, driver-signed yard events, dock notices, and appointment moves — rows
backed by a device signature are badged `driver-signed ✓`.

## 5g. Board-driven position pings (Phase 25, Location Push Service Extension)

When a board viewer is looking at a card whose live status has gone stale
(>5 min), the server sends an APNs push of type `location` (topic
`<bundle-id>.location-query`) to the device's registered **location-push
token** — a distinct token minted by iOS for the app's Location Push Service
Extension. The extension wakes even with the app terminated, takes one fix,
best-effort reverse-geocodes it, and reports it back. A raw fix refreshes the
card's position and "Near X" place only; the phone-computed ETA/progress/leg
fields are never touched (the extension can't run the HOS math, and a raw
position must not masquerade as a fresh ETA). Pings are throttled to one per
device per 6 minutes, inside Apple's ~360-events/day LPSE budget.

| Endpoint | Auth | Purpose |
| --- | --- | --- |
| POST `/v1/broker/location-token` | device-signed `{token, ver: 1}` | Files the LPSE APNs token (hex) on the device row |
| POST `/lp/fix` | one-shot `nonce` from the ping push (burned on use, 5 min expiry) | `{nonce, lat, lon, place?, at?}` → position merge onto every active share of that device |

A token that APNs reports `Unregistered`/`BadDeviceToken` (rotated by a
reinstall) is retired immediately; the app re-files its current token on every
launch. While no live location token exists, the server falls back to a
**silent background push** on the device's ordinary alert token — the app
wakes, pushes a full status, and re-files its location token, so a board never
goes dark waiting for the driver to open the app.

## 5h. Truck-legal route check (Phase 28)

MapKit routes cars, so route legality (bridge heights, weight-restricted
roads, truck bans) is answered by HERE Routing v8 with `transportMode=truck` —
reached only through the validation server, which holds the HERE credentials
and caches verdicts for 30 minutes. Advisory only: it colors the app's
traveling card, never gates a workflow. The phone asks once per trip leg, and
only when the rig runs a trailer AND the trip has a trailer # assigned.

| Endpoint | Body | Result |
| --- | --- | --- |
| POST `/v1/route/truck-check` | device-signed `{dest, origin, ver: 1}` — coordinates as pre-rounded `"lat,lng"` STRINGS (byte-stable canonicals) — plus an imperial `profile` (`heightIn, widthIn, lengthIn, weightLb, axleCount, trailerCount`; nonsense clamps to a 13'6" 5-axle 80,000 lb default) | `{available, legal, notices[], distanceMiles, durationMin, trafficDelayMin}`; `{available: false}` whenever HERE credentials are absent or unreachable — never an error |

## 5i. Detention rules & driver-submitted claims (Phase 55)

Detention math runs on the driver's device from the signed yard-event chain
(free time anchors at the later of arrival and the appointment; the clock
stops only when the trip is complete AND the truck has departed). The tenant's
dispatcher sets the RULES the phones compute with, and the driver files the
computed CLAIM; the office may layer an adjusted amount on top — the driver's
submitted figures are never rewritten, and the driver's device is pushed
(`detention_adjusted`) so a pay modification is reviewed, never silent.

Office endpoints authenticate with the tenant API key (Bearer); driver
endpoints use the device-signed canonical `{"keyID","purpose","ts","ver":1}`
(±5 min freshness), same as §5's driver reads.

| Endpoint | Auth | Body / Result |
| --- | --- | --- |
| PUT `/v1/detention/policy` | tenant key | `{freeTimeHours?, ratePerHour?, awaitingCargoBillable?}` — omitted/invalid fields clear to the federal baseline (2 h @ $50/hr) → `{policy}` |
| GET `/v1/detention/policy` | tenant key | → `{policy}` |
| POST `/v1/detention/policy/mine` | device-signed, purpose `detention.policy` | optional `tenantId` → `{tenantId, tenantName, policy}` |
| POST `/v1/detentions/submit` | device-signed, purpose `detention.submit` | `{loadRef, stop, billableHours, amount, freeTimeHours?, ratePerHour?, facilityName?, arrivedAt?, departedAt?, appointmentAt?, tripCompletedAt?}` — idempotent per (driver, loadRef, stop); a re-submit refreshes the figures and preserves any adjustment → `{id, status, episodeKey, visitCount}`. **The detention episode** (optional, additive): `visits: [{startedAt, endedAt?, release?, returnReasonCode?}]` plus `onPropertyHours?, continuousHours?, billableContinuousHours?, continuousAmount?`. One episode per stop: a driver who RETURNS to a stop re-submits the SAME row with a longer visit list — the anchor (first arrival) never moves and free time is never granted twice. `billableHours`/`amount` remain the ON-PROPERTY claim; the continuous pair is the alternative the office may choose instead, never billed silently. |
| GET `/v1/detentions` | tenant key | optional `?loadRef=` filter → `{detentions: [...]}`, newest first; each row carries `invoiceId`/`invoicedAt` once billed (phase 105) |
| POST `/v1/detentions/:id/adjust` | tenant key | `{amount, note?}` — sets `adjustedAmount`/`adjustmentNote`, pushes the driver (APNs category `DYSPASH_DETENTION`, FCM data `kind: detention_adjusted`) → `{detention}` |
| POST `/v1/detentions/mine` | device-signed, purpose `detention.read` | → `{detentions: [...]}` with adjustments layered on |

### Driver Passport (phase 106)

The one **driver-owned** document shelf: a medical card, MVR review, or training
certificate is about a person, not a load, so it travels with the driver between
carriers. The office contributes to it; the driver keeps it. Unlike every other
driver-facing endpoint, `/v1/passport/mine` derives no scope from memberships —
it is the only path that still answers when a driver is between carriers.

| Route | Auth | Notes |
|---|---|---|
| POST `/v1/passport/documents` | tenant key (not viewer) | multipart: `driverId`, `kind`, optional `title`/`issuedOn`/`expiresOn`/`note`/`supersedesId` + file → `{document}`. Driver must be an approved member of the calling tenant; idempotent on (driver, sha256, kind); a renewal's `supersedesId` must name a document on the SAME driver's shelf |
| GET `/v1/passport/documents?driverId=` | tenant key | → `{documents: [...]}` each with derived `status` (ok/expiring/expired/revoked) + `current`/`superseded`. An approved carrier sees the whole shelf; a former carrier sees only what it issued (§391.51 retention); a stranger sees `[]` |
| GET `/v1/passport/documents/:id/file` | tenant key | bytes, same visibility rule; 404 (never 403) when not visible |
| POST `/v1/passport/documents/:id/revoke` | tenant key, **issuer only** | `{reason?}` — withdraws a mistaken upload; never a delete, and the row stays on the driver's shelf marked `revoked` |
| POST `/v1/passport/mine` | device-signed, purpose `passport.read` | → `{documents: [...]}` — the driver's whole shelf, **no membership required** |
| POST `/v1/passport/mine/file` | device-signed, purpose `passport.file` | `{documentId}` → bytes, owner-checked |

### The employment record (phase 121)

The two-party work history (SPEC-BACK-OFFICE §6). `tenant_members` stays the
ACCESS gate — one row per (tenant, driver), never relaxed; the record itself is
DERIVED, never stored: episodes come from the append-only `member_stage_events`
(every approve/revoke/rejoin snapshots the state it replaces, so a rehire no
longer destroys the original hire timestamp), and agreed first/last days come
only from COMPLETED two-party HR forms (`first_day` / `termination_exit` —
manager + driver passkeys bound to the content hash, ledger-mirrored). Access
timestamps are served as labelled access facts, `attested:false` — an
auto-opened span has no human signer and never claims to be "your first day."

| Route | Auth | Notes |
|---|---|---|
| POST `/v1/employees/mine` | device-signed, purpose `employee.read` | → `{employments: [...]}` per tenant: `accessStatus`, derived `episodes`, `firstDay`/`lastDay` (`agreed` only from a completed form), labelled `accessFacts`. **No membership-status gate** — a revoked or former driver still owns their record |
| POST `/v1/join` with `rejoin: true` | device-signed | a REVOKED pair reopens as `pending` (same access row, new episode) — only with a fresh valid invite, and only when the rejoin intent is INSIDE the signed bytes (`{"code","keyID","rejoin":true,"ver":1}`, or its ver:2 form with `credentialHash` before `keyID`); a bare re-join stays a status check and never reopens |
| POST `/v1/join` with `ver: 2` | device-signed | binds the CDL credential draft into the signed bytes: `{"code","credentialHash","keyID","ver":2}` where `credentialHash` = sha256 of the canonical credential JSON, recomputed server-side from the ARRIVING credential — a captured body replayed with edited credential fields fails signature verification. ver:1 stays accepted for a deprecation window, but its unsigned credential is saved only on a membership-creating FIRST join and ignored on re-joins and rehires (`credentialIgnored: true` in the response) |

### OS&D exceptions — the secondary eBOL (phase 109, ADR-005 §5)

The consignee unloads against the carrier's **copy** (phase 108,
`/v1/ebol/copies`) and marks what did not go in. The result is a **secondary
eBOL**: a record of exactly what was NOT accepted, tied to that copy and that
load. Read the words literally — the shipper created and keeps the ORIGINAL, the
carrier holds a COPY, and this is an exception **record**, not an instrument. It
confers nothing and moves nothing.

Two facts govern the shape:

- **Facility-attested, not device-signed.** The lumper counting the freight is a
  facility worker with no device key, so the attestation is a verified worker
  session plus an audit row — the phase-85 pattern (`lib/workerreports.mjs`).
  Every response says so: `attestedBy`, `attestation`, `deviceSigned: false`.
  A worker session is scoped to freight **standing on their own yard** (yard
  inventory or an occupied door): this row lands in a *carrier's* account, so
  knowing a copy id or a trailer number is not entitlement to file against it.
- **Only the manifest hash is evidence-grade (P12).** The marked lines are
  store-only tender data, like the copy's line items
  (`NMFTA-CONFORMANCE.md` §1.1). The **manifest** — canonical JSON, recursive
  sorted keys, compact — is written to object storage and its SHA-256 stored on
  the row. Photos appear in the manifest as **hashes**, so the one digest covers
  the photographs too. `manifest.signed` is `false` today: the hash is the seam a
  signed event would carry, and it exists before the signature does.

Taxonomy: `over` · `short` · `damaged` · `refused`, per line, with quantity, unit,
reason, notes, and **multiple photos**. An unrecognised kind is refused, not
coerced.

| Route | Auth | Notes |
|---|---|---|
| POST `/v1/ebol/osd` | lumper worker session, **or** tenant key (not viewer) | multipart: `copyId` **or** `trailer` (+ optional `loadRef`), `exceptions` (JSON array of `{kind, quantity, unit?, lineRef?, description?, reason?, reasonText?, note?}`), optional `capturedAt`/`door`/`note`, plus file parts `photo_<line>` (repeatable; a bare `photo` is allowed only on a single-line report) → `{secondary}`. The tenant is inherited from the copy. 409 on a **voided** copy or an ambiguous trailer; 404 when the copy belongs to another carrier, or when a worker's yard is not where that trailer is standing. Idempotent on (copy, manifest hash) — a retry must resend the same `capturedAt`, and it re-writes any manifest/photo blob the first attempt failed to store |
| GET `/v1/ebol/osd` | tenant key | optional `?loadRef=`/`?copyId=`/`?equipmentId=` → `{secondaries: [...]}`, newest first, with `countsByKind`/`quantityByKind`/`summaryLines` |
| GET `/v1/ebol/osd/:id` | tenant key | → `{secondary}` including the marked lines |
| GET `/v1/ebol/osd/:id/manifest` | tenant key | the exact canonical bytes, `X-Dyspash-Manifest-Sha256` on the response |
| GET `/v1/ebol/osd/:id/photo?key=` | tenant key | photo bytes, scoped to that report's own storage prefix |

Capture fires the existing HMAC webhook `ebol.osd.created` (phase-11 rail,
`X-Dyspash-Signature`) and writes the audit row the activity ladder reads — per
ADR-005 §6 the carrier's alert rides existing channels, not a new one.

### Trailer lease & interchange (phase 110)

A driver hooks a box that is not the company's. Who owns it, on what terms, what
condition was it in when it left, how far did it go, how long was it out, and
what does that cost? This is that, and — unlike the eBOL work above — **"lease"
and "agreement" are the correct words**: possession of a chattel really does move
between two companies, for money. It is about the BOX. Nothing here touches the
freight, the bill of lading, or who may take delivery (ADR-005); there is no
`loadRef` anywhere in this surface.

**The agreement is BILATERAL, and that is enforced, not assumed.** The offers
flow (§ load offers) is one-sided by design — a carrier offers, a driver signs.
Here both companies must agree the rate, so:

- **Proposing is accepting your own terms.** Sending a rate sheet binds the
  sender; `POST /v1/leases` writes round 1 **and** the proposer's acceptance.
- **A counter is a new round with a new hash.** Acceptances are keyed by hash, so
  countering voids every acceptance of the old terms with no separate reset step.
- **`agreed` requires two acceptances, from different sides, of the same hash.**
  The caller's side is resolved from their credential and **never** from a
  request field. The database carries the same rule as a CHECK constraint
  (`lease_agreed_is_bilateral`), so one side cannot reach `agreed` even by
  hand-written UPDATE.
- **The owner's authorization is the lessor's acceptance** — mandatory for
  `agreed` whoever opened the conversation, and pointed at by `authorizationRef`.
- **The promotion is a compare-and-swap** on the status *and* the terms hash, so
  a `counter` arriving mid-`accept` cannot leave the row `agreed` at a rate only
  one side ever saw. A lost swap answers 409 (`re-read the terms`). The database
  carries the same rule as a trigger (`trailer_lease_agreed_bilateral`), which
  requires an acceptance row from **each side carrying the row's own terms
  hash** — the CHECK alone can only prove two timestamps exist.
- **`agreed` is not reversible by one side.** Decline and withdraw apply only
  while the terms are on the table; an agreed lease is closed with `/end`, which
  refuses while trailers are still out. This holds on the phone route too.

**Terms are pinned by hash**, the same discipline as `offerHash`: canonical JSON
with keys sorted at every level, plus `ver`, SHA-256 hex, with a `termsKind`
discriminator so a lease hash can never collide with a dispatch offer hash.
The digest covers the rate sheet **and the deal facts that decide money** —
`selectionMode`, the trailer unit (case-folded), the pool, and the entitlement
`unitCount`, because a bill is per possession and the count multiplies it.
Every acceptance names the hash it accepted; every interchange copies the hash it
was drawn under; and pricing re-derives the hash from the stored terms and
**refuses to produce a number** when the three disagree. Money in the terms is
**integer cents** throughout, so a bill is reproducible by hand.

**Two selection modes.** `specific` names a trailer. `pool` grants *N* boxes from
a pool at a facility without naming them. The count is an **entitlement**: each
hook draws one unit and pins that box. Over-allocation is impossible rather than
unlikely — two partial unique indexes (`equipment_key`, and
`(agreement_id, draw_index)`, both `where released_at is null`) mean one open
possession per physical box platform-wide and at most `unitCount` open per lease.
A lessee sees a pool's **availability count**, never its roster.

**The DVIR gate is a precondition.** An interchange cannot become `active`
without a pickup condition record — in app code *and* as a CHECK constraint — and
a reported defect without a photograph is refused. **The signed-DVIR seam is
named, not faked:** device-signed DVIR transmit does not exist yet, so what this
accepts is an **attested** condition report (a driver device signature over the
request envelope, or a tenant key) with photos committed by hash (P12).
`dvirSigned` is `false` on every row written today, a CHECK forbids claiming it
without a reference, and a client that sends `dvirRecordId` is **refused** with
`seam: "dvir.transmit"` rather than humoured.

**Usage → billing.** Pickup location + time, dropoff location + time, duration
from the possession window, and **miles from the existing phase-103
`trailer_mileage_log` accrual** — there is deliberately no second mileage
mechanism. Priced by the agreed rate: `units = ceil(billableMinutes / basis)`
(or miles, or 1 for `flat`), floored at `minimumUnits`, plus mileage overage past
`includedMilesPerUnit × units`, floored at `minimumChargeCents`.

**The clock is bounded, because the paying side holds it.** Only the lessee side
may file pickup and dropoff, and both timestamps arrive as form fields, so
`dropoffAt` earlier than the recorded pickup is refused (422) and neither stamp
may be more than 5 minutes in the future. A *backdated* pickup stays legal — a
phone capturing in a yard with no signal is normal, and it can only bill the
sender more.

**Retries are idempotent, and a dropped response is not a second DVIR.** Condition
reports are content-addressed on `(interchange, phase, manifest hash)`, so
resending the identical form returns **200** with the same `conditionId` rather
than 409. A *different* report on a possession that has already moved on is still
a 409.

**Cross-tenant posture.** A trailer in your yard is not a secret — VIN and owner
name are painted on it, so `identify` answers an **exact** match. The agreement
and the billing linkage are consent-backed: every read is scoped to a party, and
an off-platform counterparty (modelled as free text) can never be made to agree.

**Not shipped yet — the off-platform owner.** Because an off-platform lessor has
no principal to accept with, an agreement naming one never reaches `agreed`, and
the draw is gated on `agreed`. So a possession of a trailer belonging to a
non-Dyspash owner **cannot be recorded at all today**, which leaves the first
half of the requirement (record where it was hooked and dropped, its miles and
its time with the company, whoever owns it) unserved for the commonest case.
`GET /v1/interchanges/:id/billing` already carries the honest unpriced answer for
it and is currently unreachable. This is an open item, stated rather than
implied.

| Route | Auth | Notes |
|---|---|---|
| POST `/v1/trailer-pools` | tenant key (not viewer) | `{name, facilityId?, facilityLabel?, note?}` → `{pool}`; 409 on a duplicate name |
| GET `/v1/trailer-pools` | tenant key | the caller's own pools with `availableCount` |
| GET `/v1/trailer-pools/:id` | owner **or** a lessee with an agreed pool lease | the owner gets the roster with `onLease` per unit; a lessee gets `{id, name, facilityLabel, availableCount}` and **no unit list**; everyone else 404 |
| POST `/v1/trailer-pools/:id/units` | owner (not viewer) | `{add: [unit\|{trailerUnit, vin?}], remove: [unit]}` → `{pool, added, removed}`. 422 on a trailer number that fails the anti-wildcard predicate; 409 removing a box that is out on an open lease |
| POST `/v1/leases` | tenant key (not viewer), **must be a party** | `{lessorTenantId\|lessorName(+lessorMc), lesseeKind, lesseeTenantId\|lesseeDriverId\|lesseeName, selectionMode, trailerUnit\|poolId(+unitCount), terms, startsAt?, endsAt?, note?}` → `{agreement}` with `acceptedBy:["lessor"\|"lessee"]` and `bilateral:false`. 403 for a non-party, 422 for a self-lease |
| GET `/v1/leases` | tenant key | leases where the caller is **either** party, each with `yourSide`; optional `?status=`/`?side=` |
| GET `/v1/leases/:id` | party only | `{agreement (with rounds + acceptances), interchanges, drawn, remaining}`; 404 to anyone else |
| POST `/v1/leases/:id/counter` | party (not viewer) | `{terms, note?}` → new round, new hash, counter-proposer bound to it. 409 once `agreed` — open a new lease with `supersedesAgreementId` |
| POST `/v1/leases/:id/accept` | party (not viewer) | `{termsHash, note?}` — 409 `termsHash mismatch` on a stale hash, 422 when absent, 409 `the lease moved while you were accepting` when the swap is lost. Reaching two sides on one hash sets `agreed` + `authorizationRef` |
| POST `/v1/leases/:id/decline` · `/withdraw` | party (not viewer) | open statuses only — 409 once `agreed`. Withdraw is limited to the side whose terms are on the table |
| POST `/v1/leases/:id/end` | party (not viewer) | 409 while any box is still out, listing `openInterchangeIds` |
| POST `/v1/leases/:id/draw` | **lessee** side (not viewer) | `{trailerUnit?, assignedDriverId?, note?}` → `{interchange}` in `authorized`. 409 before `agreed`, 409 when the entitlement is spent or the box is already out. Retries on index conflict rather than locking |
| POST `/v1/leases/mine` | device-signed, purpose `lease.list` | → `{leases, assignments}`. An owner-operator sees their leases; a **company driver sees only assignments** (with `dvirRequired`) and never the rate |
| POST `/v1/leases/mine/decide` | device-signed, purpose `lease.decide` | `{leaseId, termsHash, decision?}` — owner-operator / lease operator only; 403 with the reason for a driver named on a company lease; 409 on `decision:"decline"` once the lease is agreed. **Device-authenticated, not device-signed over the terms** — see the note below |
| POST `/v1/interchanges/:id/pickup` | lessee tenant key **or** device-signed (envelope in the form fields), purpose `lease.pickup` | multipart: `defects` (JSON array of `{area, severity, description?, preExisting?}`) **or** `noDefects=true`, `pickupAt?`/`location?`/`facilityId?`/`lat?`/`lon?`/`note?`, file parts `photo_<line>` (per defect) and bare `photo` (general). → `{interchange}` now `active`. 422 without a stated condition, 422 for a defect with no photo, 422 for `dvirRecordId`, 422 for a future `pickupAt`. An identical resend → 200 with the same `conditionId` |
| POST `/v1/interchanges/:id/dropoff` | same | closes the possession, snapshots miles + duration, releases the box, returns `{interchange (with billing)}`. 422 when `dropoffAt` precedes the pickup or is in the future; an identical resend → 200 |
| GET `/v1/interchanges` | tenant key | possessions where the caller is either party; `?status=`/`?open=true` |
| GET `/v1/interchanges/:id` | party only | with both condition reports and the bill |
| GET `/v1/interchanges/:id/billing` | party only | `{billing}` — `billable:false` **with a reason** when the lease is not agreed, the pin does not hold, or the box is still out |
| GET `/v1/interchanges/:id/condition/:reportId/manifest` | party only | the exact canonical bytes, `X-Dyspash-Manifest-Sha256` on the response |
| GET `/v1/interchanges/:id/photo?key=` | party only | photo bytes, scoped to that possession's own storage prefix |
| POST `/v1/trailer-lease/identify` | tenant key **or** device-signed, purpose `lease.identify` | `{vin}` **or** `{ownerTenantId\|ownerName, trailerUnit}` → `{trailers: [{trailerUnit, vin, trailerType, owner, yourLease}]}`. Exact match only; `yourLease` is the CALLER's own coverage and never anybody else's. 404 carries the hint that an off-platform owner can still be named as free text |

**Two seams, named rather than glossed.** Neither is a TODO buried in a comment;
both are things the API declines to claim it has.

1. **The signed DVIR.** `dvirSigned` is `false` on every condition report, and
   `dvirRecordId` is refused on input. DVIR transmit is its own unit; when it
   ships the signed reference lands in that field and the gate is unchanged.
2. **A device-signed lease acceptance.** `POST /v1/leases/mine/decide` verifies a
   signature over the purpose envelope — proving the device and the freshness —
   and takes `termsHash` in the body, *outside* that signature. Compare
   `POST /v1/offers/:id/decide`, where the driver signs a canonical payload
   containing `offerID` and `offerHash`, so the decision is itself a verifiable
   artifact. Here the acceptance row is the server's word that a verified device
   sent that hash: enough to authorize the action, not enough to be evidence in
   a dispute. The fix is the offers pattern, and it is phone-side
   canonicalization, so it lands on both platforms with a shared vector or not
   at all.

Lease events ride the existing HMAC webhook rail (`X-Dyspash-Signature`) to
**both** companies: `trailer_lease.proposed` · `.countered` · `.agreed` ·
`.declined` · `.withdrawn` · `.ended`, and `trailer_interchange.drawn` ·
`.active` · `.closed` (the last carrying miles, duration and `totalCents`).

## 5j. Driver identity presentation & gate bridge (Phase 10)

A driver presents a **selective-disclosure identity** — a signed pointer that carries
**no PII**. The token is a COSE_Sign1 CWT with `presentationKind = "id"` committing to a
`(root, scope)` pair: `root` is the SHA-256 of the sorted set of per-attribute digests
`SHA-256(name ‖ 0x1f ‖ value ‖ 0x1f ‖ salt)`; `scope` is one of `gate | scale | dot | full`,
each an allow-list of attribute names. Disclosed attributes travel out-of-band as
`{name, value, salt}` triples; a verifier recomputes each digest and confirms it is a member
of `root`. The values themselves are never in the QR.

| Endpoint | Auth | Behavior |
|---|---|---|
| POST `/v1/present` | none (rate-limited) | `{token, disclosed[], siblingDigests[]}` → `parseToken` + COSE `verifyToken` against the registered device key + `exp` check + disclosure-membership against `root`. Returns `{valid, scope, deviceRegistered, keyClass, attributes:[{name,value,tier}]}`. `tier` ∈ `self | scan | issuer`. |
| GET `/id/{token}` | none (facility session optional) | Human viewer page: authenticity + freshness + signer trust tier. For an **enrolled** device the driver detail is re-resolved **server-side** (name/CDL from the identity, rig/load from the driver's latest arrival) so the page can show it while the QR stays PII-free. |
| POST `/facility/identity/checkin` | **verified facility (clerk)** | **Gate bridge.** `{token}` → re-verifies the presentation, re-resolves the driver detail server-side, and creates a prefilled **expected pre-check-in** (`source:"identity"`) declared + pre-assigned to the scanning facility. The driver's later device-signed arrival reconciles onto it by `keyID + loadRef`. Only offered when the presenting device is enrolled and the signature verifies. |

The gate bridge is the "never re-enter at the gate" step: the facility confirms a
prefilled row instead of re-typing carrier / truck / trailer / load. It changes no
canonicalization or claim layout — the presentation crypto is byte-identical to §2–§3.

## 6. Versioning

- The `DYSP1.` prefix and the `ver` claim (label -65541) are both **1**.
  Breaking changes increment both (`DYSP2.`); verifiers reject prefixes they
  don't implement with a clear "update required" message.
- New claims MAY be added within v1; verifiers MUST ignore unknown labels.
- The canonical entity contract (JSON Schemas, additive-versioning rules, and the
  cross-platform conformance suite) is **Dyspash Wire v1**: see
  `Docs/WIRE-PROTOCOL-V1.md` and the machine-readable source of truth in
  `Backend/wire/v1/`. This spec remains the published HTTP handbook; Wire v1
  formalizes it and governs all new cross-surface data flows.

## 7. License

This specification may be implemented by anyone, royalty-free. Interop feedback:
via the facility claim page on any Dyspash validation host.
