feat(booth): refusal snapshots, subscriber access medium, one-car-one-ticket entry

Three booth-integrity improvements that share the entry/exit flows and activity log.

Refusal snapshots: previously only an accepted open captured a camera image; now
every refusal/hold anomaly fires the directional camera too (a turned-away car is
exactly the evidence wanted) — entry refused-full/held, exit refused
closed/no-session/unpaid/grace-expired (booth + reader paths), refused subscription.
A refused entry has no ticket id, so a synthetic REFUSED- ref keys the anomaly + photo
together. Same fire-and-forget contract; failed captures still show as tiles.

Subscriber access medium: the subscription flow already signed `via`
(qr|card|plate) into entry/exit payloads; surface it as a typed LedgerPayload.via, a
cyan chip in the ticker, and an "Entry medium" modal row (sq+en). Display-only.

One car = one ticket: the entry button could be mashed to mint many tickets per car
(corrupting occupancy + enabling ticket-shopping at exit) — the old #inFlight guard
only blocked overlapping presses. Add a per-relay guard configured on the relay spec:
PRESENCE mode (presenceInput ties ticketing to a vehicle loop on a Dingtian input —
one ticket per car, re-armed when the loop clears) or COOLDOWN fallback
(entryCooldownSec) when there's no barrier feedback. A suppressed press is unsigned
device_events telemetry, not a signed anomaly. SetupWizard exposes both fields.
Fail-closed entry and barrier-is-not-a-door invariants untouched; guard state is
in-memory/rebuildable, starts armed after restart.

Wiki: new entry-double-press; updated entry-exit-points, booth-console, index.

Claude-Session: https://claude.ai/code/session_01Xcm6ikLgGoCxxHrxtjkk5V
This commit is contained in:
2026-06-19 12:54:54 +02:00
parent bfb6ab0b36
commit 30e7fe85de
14 changed files with 436 additions and 28 deletions
+158 -12
View File
@@ -1,5 +1,5 @@
import { randomInt } from "node:crypto";
import { eq, sessions, siteConfig, type Db, type DeviceRow } from "@parking/db";
import { randomInt, randomUUID } from "node:crypto";
import { deviceEvents as deviceEventsTable, eq, sessions, siteConfig, type Db, type DeviceRow } from "@parking/db";
import {
NoPrinterAvailableError,
printWithFailover,
@@ -15,7 +15,7 @@ import type { FastifyBaseLogger } from "fastify";
import type { DeviceInputEvent } from "./device-events.js";
import { getOccupancy } from "./occupancy.js";
import type { EventLog } from "./event-log.js";
import { devicesByDirection, relayForButton, type ResolvedRelay } from "./device-resolve.js";
import { devicesByDirection, relayForButton, relayForPresence, type ResolvedRelay } from "./device-resolve.js";
import { snapshotAsync } from "./snapshot.js";
// The transient ENTRY flow: a button press → print a ticket → sign a vehicle_entry
@@ -35,6 +35,31 @@ import { snapshotAsync } from "./snapshot.js";
//
// Ordering: print → (ok) sign vehicle_entry → pulseOpen → snapshot → cache session.
// (fail) sign anomaly, stop.
//
// ONE CAR = ONE TICKET (anti-double-press). The entry button can be physically held
// or mashed; without a guard each press mints a fresh ticket + signed vehicle_entry
// (corrupting occupancy and letting a transient shop the cheapest ticket at exit). The
// guard is per-relay and CONFIGURED on the relay spec (config.relays[]), chosen by what
// barrier feedback exists at the lane:
// - PRESENCE loop (preferred): `presenceInput` ties ticketing to a real vehicle. A
// press prints only while a car is present, and NO second ticket issues until the
// loop CLEARS (car drove in) and a new car re-occupies it. We observe the loop's
// input edges to track presence + "armed" per relay.
// - COOLDOWN (fallback, no feedback): `entryCooldownSec` suppresses repeat presses on
// the relay for N seconds after a ticket. A timer — mitigation, not a guarantee.
// A suppressed press is recorded as UNSIGNED telemetry (a no-op, not a fraud anomaly).
// See wiki/concepts/entry-double-press.md.
/** Per-relay anti-double-press state, keyed `controllerId:relay`. */
interface RelayGuardState {
/** Last successful ticket time (ms epoch) — drives the cooldown check. */
lastTicketAt: number;
/** PRESENCE mode: is a vehicle currently on the loop? (from loop input edges) */
present: boolean;
/** PRESENCE mode: ready to issue a ticket for a NEW car. Set false after a ticket
* prints; re-armed when the loop CLEARS (the car drove through). */
armed: boolean;
}
export class EntryFlow {
readonly #db: Db;
@@ -42,6 +67,8 @@ export class EntryFlow {
readonly #logger: FastifyBaseLogger;
/** Guard against double-fire from the same physical press (on edge only). */
readonly #inFlight = new Set<string>();
/** Per-relay one-car-one-ticket state (presence + cooldown), keyed controllerId:relay. */
readonly #guard = new Map<string, RelayGuardState>();
constructor(db: Db, log: EventLog, logger: FastifyBaseLogger) {
this.#db = db;
@@ -49,10 +76,20 @@ export class EntryFlow {
this.#logger = logger;
}
/** Handle a device input edge. Acts only on the rising ("on") edge of an entry
* button — an input terminal mapped to an entry relay on its controller. */
/** Handle a device input edge. Two kinds of edge matter to this flow:
* (1) an ENTRY BUTTON press (rising edge) → run entry, subject to the per-relay
* anti-double-press guard; (2) a PRESENCE LOOP edge (either direction) → update
* presence state so the guard knows when a car arrives/leaves. The same physical
* input is never both, so we resolve each independently. */
async onInput(e: DeviceInputEvent): Promise<void> {
if (e.edge !== "on") return; // release edge is just telemetry
// Presence-loop edge (both directions matter): keep the per-relay state current.
const presence = relayForPresence(this.#db, e.deviceId, e.input);
if (presence) {
this.#onPresenceEdge(presence, e.edge);
return; // a loop input is not a button — nothing else to do
}
if (e.edge !== "on") return; // for buttons, the release edge is just telemetry
// The firing device must be an access controller, and the pressed input terminal
// must map to an ENTRY (or both) relay — that's an entry button. Anything else
@@ -60,6 +97,14 @@ export class EntryFlow {
const resolved = relayForButton(this.#db, e.deviceId, e.input);
if (!resolved) return;
// ANTI-DOUBLE-PRESS: is this press allowed to issue a ticket? (presence/cooldown)
const suppressed = this.#suppressReason(resolved);
if (suppressed) {
this.#recordSuppressedPress(e, resolved, suppressed);
this.#logger.info(`entry press suppressed (${this.#relayKey(resolved)}): ${suppressed}`);
return;
}
const key = `${e.deviceId}:${e.input}`;
if (this.#inFlight.has(key)) return; // ignore re-fire while one is processing
this.#inFlight.add(key);
@@ -72,6 +117,88 @@ export class EntryFlow {
}
}
/** Stable per-relay key for the guard map. */
#relayKey(r: ResolvedRelay): string {
return `${r.controller.id}:${r.relay}`;
}
/** Lazily get (or create) the guard state for a relay. New relays start ARMED and
* with no car present, so the first press on a fresh lane works immediately. */
#guardState(r: ResolvedRelay): RelayGuardState {
const key = this.#relayKey(r);
let s = this.#guard.get(key);
if (!s) {
s = { lastTicketAt: 0, present: false, armed: true };
this.#guard.set(key, s);
}
return s;
}
/** Apply a presence-loop edge to a relay's state. The car ARRIVING re-arms ticketing;
* the car LEAVING the loop (after its entry) re-arms for the NEXT car. */
#onPresenceEdge(r: ResolvedRelay, edge: "on" | "off"): void {
const s = this.#guardState(r);
if (edge === "on") {
s.present = true; // a vehicle is at the barrier
} else {
// Loop cleared: the car drove through (or backed off). Re-arm for the next car —
// this is the gate that makes a *new* car necessary before another ticket.
s.present = false;
s.armed = true;
}
}
/** Why a press should be SUPPRESSED (no ticket), or null if it may proceed.
* PRESENCE mode is authoritative when a loop is wired; otherwise COOLDOWN; else no
* guard (legacy). The two can coexist — presence first, cooldown as a backstop. */
#suppressReason(r: ResolvedRelay): string | null {
const s = this.#guardState(r);
if (typeof r.presenceInput === "number") {
// Physical one-car-one-ticket: a car must be present AND we must be armed (no
// ticket already issued for this still-present car).
if (!s.present) return "no vehicle at the barrier (presence loop clear)";
if (!s.armed) return "ticket already issued for the car at the barrier";
return null;
}
if (typeof r.entryCooldownSec === "number" && r.entryCooldownSec > 0) {
const elapsed = Date.now() - s.lastTicketAt;
if (elapsed < r.entryCooldownSec * 1000) {
const remain = Math.ceil((r.entryCooldownSec * 1000 - elapsed) / 1000);
return `within ${r.entryCooldownSec}s entry cooldown (${remain}s left)`;
}
}
return null;
}
/** Record a suppressed (repeat/no-car) entry press as UNSIGNED telemetry — a no-op,
* not a fraud anomaly, so the signed ledger stays clean (the operator's choice). */
#recordSuppressedPress(e: DeviceInputEvent, r: ResolvedRelay, reason: string): void {
try {
this.#db
.insert(deviceEventsTable)
.values({
id: randomUUID(),
deviceId: e.deviceId,
category: "access",
kind: "input",
detail: {
driverId: e.driverId,
input: e.input,
edge: e.edge,
entrySuppressed: true,
relay: r.relay,
reason,
},
occurredAt: e.at,
})
.run();
} catch (err) {
this.#logger.error(`suppressed-press telemetry insert failed: ${(err as Error).message}`);
}
}
async #runEntry(resolved: ResolvedRelay): Promise<void> {
// CAPACITY GATE (transient only). When the lot is full, refuse transient entry:
// no ticket, no vehicle_entry, no open — sign an anomaly. Subscribers are NOT
@@ -80,14 +207,20 @@ export class EntryFlow {
// capacity later. See wiki/concepts/capacity-occupancy.md.
const occ = getOccupancy(this.#db);
if (occ.full) {
// No ticket id exists for a refused entry, so mint a synthetic ref to key the
// anomaly + its evidence snapshot together. The operator wants the photo of WHO
// was turned away (a fraud/dispute signal), so we still fire the entry camera.
const refusedRef = `REFUSED-${randomUUID().replace(/-/g, "").slice(0, 12)}`;
await this.#log.append({
type: "anomaly",
identity: refusedRef,
payload: {
...reasonPayload("entry.refused.full", { count: occ.count, capacity: occ.capacity ?? 0 }),
entryRefused: true,
full: true,
},
});
this.#fireSnapshot("entry", refusedRef);
this.#logger.warn(`transient entry REFUSED: full (${occ.count}/${occ.capacity})`);
return;
}
@@ -103,6 +236,13 @@ export class EntryFlow {
d.printTicket(ticket),
);
this.#logger.info(`entry ticket ${ticketId} printed on ${printedBy}`);
// ONE CAR = ONE TICKET: a ticket is now out for the car at this barrier. Disarm +
// stamp the cooldown so a repeat press (held button / mashing) issues no second
// ticket. PRESENCE mode re-arms when the loop clears (car drove in); COOLDOWN mode
// re-allows after entryCooldownSec. Done on the print success, NOT the open.
const guard = this.#guardState(resolved);
guard.lastTicketAt = Date.now();
guard.armed = false;
} catch (err) {
// HOLD: do not open, do not record a vehicle_entry. Sign an anomaly so the
// failed attempt is in the tamper-evident record for the operator.
@@ -113,6 +253,8 @@ export class EntryFlow {
identity: ticketId,
payload: { ...reasonPayload("entry.held.noTicket", { detail: reason }), ticketPrinted: false },
});
// Capture who is held at the barrier (evidence for the operator handling the car).
this.#fireSnapshot("entry", ticketId);
this.#logger.warn(`entry HELD: ${reason} (barrier NOT opened)`);
return;
}
@@ -146,12 +288,7 @@ export class EntryFlow {
// 3b. SNAPSHOT — fire the entry camera(s), never awaited (evidence, not a gate;
// a camera failure must not delay or block the already-open barrier).
void snapshotAsync({
db: this.#db,
direction: "entry",
identity: ticketId,
logger: this.#logger,
}).catch((err) => this.#logger.error(`entry snapshot error: ${(err as Error).message}`));
this.#fireSnapshot("entry", ticketId);
// 4. Update the session projection cache (rebuildable from the ledger; this is
// just a fast read-model, never the source of truth).
@@ -167,6 +304,15 @@ export class EntryFlow {
}
}
/** Fire the entry camera(s) for an identity; never awaited (evidence, not a gate).
* Used on both the OPEN path and the refused/held anomaly paths — a turned-away or
* held car is exactly when the operator wants the photo. */
#fireSnapshot(direction: "entry", identity: string): void {
void snapshotAsync({ db: this.#db, direction, identity, logger: this.#logger }).catch((err) =>
this.#logger.error(`entry snapshot error: ${(err as Error).message}`),
);
}
/** Build a live access adapter from a resolved controller row, or null. */
#buildAccess(row: DeviceRow): AccessControlDevice | null {
const driver = registry.get(row.driverId);