Files
parking_solution/wiki/concepts/append-only-event-chain.md
T
julian 8a8e74561d wiki: design the business layer (session, tariff, permit, vision, shift, ops)
Pivot from the hardware/integrity layer to the parking operation. All
wiki-only; no code yet. Core principle throughout: business entities are
projections over the signed append-only event log, never mutable tables.

New concepts: parking-session, tariff (composable/versioned, FX-ready),
shift (manned-only Z-report), capacity-occupancy, validation-discounts,
reporting-analytics, clock-integrity, ticket-encoding, anti-passback.
New entities: permit, opencv-anpr-service, blocklist.
Decisions: session-model, vision-service (host-side ANPR + vehicle
verification; scoped AGPL exception for the isolated service).

Updates: append-only-event-chain (new event types + vision witness),
local-jwt-auth (drop 8h expiry -> until logout; code change pending),
lpr-camera (host-side recognition supersedes edge-AI), standing-decisions
(AGPL exception), open-questions (+FX, +pay-station money corners, backup).

Deferred + flagged: intercom/help-call, receipts/refunds/change, FX engine,
lane topology (#1).
2026-06-15 17:41:38 +02:00

113 lines
6.9 KiB
Markdown

---
type: concept
tags: [parking, security, integrity]
sources: [parking-system-architecture]
updated: 2026-06-15
---
# Append-Only Event Chain
The core integrity mechanism against operator fraud (see [[threat-model]]). (See
[[parking-system-architecture]] §3.)
Three layered properties:
1. **Append-only event model.** Entry/exit events are never edited or deleted, only appended. A
"void" is itself a **recorded event**, not an erasure.
2. **Tamper-evident chaining.** Each event stores the **hash of the previous event** (a hash
chain). Reordering or deleting **breaks the chain visibly**.
3. **Hardware-backed signing.** The **[[atecc608]]** secure element signs each event with a
non-extractable key. This is what makes the chain **unforgeable** rather than merely
self-consistent — someone who owns the machine still cannot forge a valid entry.
It only becomes trustworthy as an external fraud control when paired with [[reconciliation]]
against an authority the operator can't alter. Every device event — including those ingested
from the [[uhppote-controller]] via [[event-log-ingestion]] — should land in this host-side
chain.
## Implementation (apps/server)
> Implementation-derived. The schema (`packages/db` `events`) and types
> (`packages/shared` `ParkingEvent`) predate this; the writer/signer are new.
- **`EventLog`** (`apps/server/src/event-log.ts`) is the append primitive. `append()` reads the
latest row, sets `index = prev + 1`, `prevHash = sha256(canonical(prev))` (genesis = null),
signs the canonical form, and inserts. There are **no update/delete paths**.
- **Serialized appends.** SQLite is single-writer, but read-prev → compute-hash → insert is
multi-step, so `EventLog` also guards it with an in-process async lock — otherwise two near-
simultaneous events could claim the same `index` or chain off a stale `prevHash`. Verified:
5 concurrent appends produced indices 1..5 with an intact chain.
- **Canonical form** is a fixed-order JSON array (`index,type,direction,lane,source,identity,
occurredAt,prevHash`) — byte-stable, since the chain + signatures depend on it. The volatile
row `id` is excluded; chain identity is `index` + content.
- **`verifyChain()`** walks oldest→newest, recomputing hashes + signatures. Catches tampered
content (bad signature), reordering / a deleted row (`index` gap), and a `prevHash` mismatch.
Exposed at `GET /api/events/verify` (admin). Read access to the log: `GET /api/events`.
### The `Signer` abstraction (software now, ATECC608 later)
Signing goes through a **`Signer`** interface (`packages/shared`) — the abstraction over the
[[atecc608]]. Because the chip being wired is still [[open-questions|open-question #6]], the
server ships a **`SoftwareSigner`** (HMAC-SHA256, key from `EVENT_SIGNING_KEY`). Swapping to the
secure element is a new `Signer` impl with no `EventLog` change; each event stores its `keyId`
so old events stay verifiable.
> ⚠️ The software signer makes the chain **self-consistent + tamper-evident**, but **not
> unforgeable by someone who owns the host** — only the ATECC608's non-extractable key gives
> property (3) above. Until the chip is wired, the chain detects tampering by *outsiders* and
> *accidental* corruption, but an operator with the signing key + DB access could re-sign a
> forged chain. This is the central reason #6 matters.
### What currently feeds the log
Dingtian **input (button) pushes** → bus → `input_received` events (see [[device-input-flow]],
[[dingtian-relay]]). These are recorded faithfully as raw inputs, **not** as `vehicle_entry` —
the richer entry event waits for the entry flow (ticket print + barrier command).
**Business-layer event types (designed, not yet implemented — see [[session-model]]).** The
[[parking-session]] domain folds over these signed events, extending `input_received`:
- `vehicle_entry` / `vehicle_exit` — a stay's endpoints; `identity` carries the ticket id or plate.
- `payment` — a settled fee at the pay station, referencing the session it pays for (amount in
integer minor units; see [[tariff]]). Making "paid" a signed event — not a mutable row — is the
whole point: an operator can't forge it or silently delete it.
- `void` — a correction / lost-ticket write-off; like every other void here it is an **appended
event, never an erasure**.
A session is a **projection** over this chain, never a mutable table — the same anti-fraud reason
the chain exists. See [[parking-session]].
- **`lane`** is now resolved from the firing device. A `LaneMap` (`apps/server/src/lane-map.ts`)
caches `lane_devices.id → lane`, built at startup and refreshed by the setup routes on every
assign/unassign. Device events carry the device instance id, not a lane; the handler looks it
up. A device with no mapping (assigned without a lane, or a stale id) logs **`lane: -1`** and a
warning — never `0`, which is a real lane — and is still recorded (the chain is append-only;
nothing is dropped).
- **`source` stays `null`** for `input_received`, and deliberately so: `source` is an
`IdentitySource` (`wiegand | lpr | qr | ticket | manual`) — *how a vehicle was identified* — not
a device/IP field. A raw button push has no vehicle identity. The device provenance lives in
**`identity`** (e.g. `dingtian:<id> input:1/on`).
### ⚠️ Limitation: the log captures HOST-ORIGINATED actions only
The event log records what the **host** did (inputs it received, opens it commanded). It is
**blind to out-of-band relay actuation** — anything that fires a relay without going through the
host. **Proven on hardware**: a binary relay command sent directly to the device with the
(sniffable) `relay_pw` fired a relay and produced **zero** events. Out-of-band paths include:
- the **password-less string protocol** (until disabled — see [[dingtian-relay]]),
- a **sniffed/replayed `relay_pw`** binary command (plaintext UDP — relay control is
defence-in-depth, **not** a boundary),
- the device's own **`ip_watchdog`** (auto-toggles a relay on ping-failure — must stay disabled),
- a future **`barrier_open_command`** path is host-side and *would* log; these bypass it.
So the log alone does **not** detect operator/attacker fraud at the relay. That is **by design** —
the actual control is [[reconciliation]]: compare the host's signed *commanded* opens against an
**independent witness** of opens that physically happened (a door/loop sensor on a Dingtian input
→ which DOES push + log; the [[opencv-anpr-service|vision service]]'s plate **and vehicle** read;
payment/Z-report). **A physical open with no matching signed command is the fraud signal** — and,
with vehicle verification, **a plate that enters/exits on a different car** is too (the
plate-spoofing case). Both the witness sources and the reconciliation logic are **NOT yet built** —
this is the main open gap. Prevention (VLAN isolation so the attacker can't
reach UDP 60000) is the necessary first line; detection-via-reconciliation is the backstop.