server: permit entry/exit branch + read dispatcher

A credential read now routes by what the credential IS: matches a permit
(card/QR credential or a bound plate) -> permit flow; else -> transient exit
flow. Lane resolved once (readerLaneWithAccess); ExitFlow.onRead -> handleAt so
the dispatcher owns lane resolution.

Permit direction is inferred from session state for that car (the read value is
the per-car session key): no open session -> ENTRY (enforce maxConcurrent, sign
vehicle_entry, open); open -> EXIT (sign vehicle_exit, open, close). Fleet
permit = one session per car; anti-passback falls out naturally.

maxConcurrent enforced as a fold over the signed ledger (null = unbound).
Validity window + status + plate-OR-card identity as designed. No ticket/fee;
every use is a signed event carrying permitId. Refusals (revoked / out-of-window
/ at-capacity) are signed anomalies, barrier stays closed.

Verified against stubs: card entry -> inferred exit; fleet cap 2 (F3 rejected
at 2/2, then admitted after F1 exits); plate-bound opens; revoked rejects;
unknown credential falls through to exit reject; verifyChain ok.
This commit is contained in:
2026-06-15 19:47:01 +02:00
parent b4d0dfadd6
commit c24d99b0f4
8 changed files with 317 additions and 29 deletions
+3 -21
View File
@@ -44,12 +44,9 @@ export class ExitFlow {
this.#logger = logger;
}
/** Handle a credential read at an exit lane. */
async onRead(e: DeviceReadEvent): Promise<void> {
// Resolve which lane this reader belongs to, and that it's an exit reader.
const lane = await this.#exitLaneFor(e.deviceId);
if (lane == null) return; // not an exit-lane reader — ignore (other flows may handle)
/** Handle a transient-ticket read at a known exit lane (lane pre-resolved by the
* read dispatcher, which has already ruled out a permit match). */
async handleAt(lane: number, e: DeviceReadEvent): Promise<void> {
const key = `${e.deviceId}:${e.value}`;
if (this.#inFlight.has(key)) return;
this.#inFlight.add(key);
@@ -160,21 +157,6 @@ export class ExitFlow {
};
}
/** The lane this reader belongs to, IF that lane has an access (barrier) device
* to open. A read event is an identity/exit signal (entry is button-driven), so
* any read at an access-equipped lane is treated as an exit attempt for now.
* (Distinguishing entry vs. exit readers per lane is a later lane-direction model.) */
async #exitLaneFor(deviceId: string): Promise<number | null> {
const row = await this.#db.select().from(laneDevices).where(eq(laneDevices.id, deviceId)).get();
if (!row || !row.enabled) return null;
const access = await this.#db
.select()
.from(laneDevices)
.where(and(eq(laneDevices.category, "access"), eq(laneDevices.lane, row.lane)))
.get();
return access && access.enabled ? row.lane : null;
}
/** The lane's access device, to open the exit barrier. */
async #exitAccess(lane: number): Promise<AccessControlDevice | null> {
const row = await this.#db
+19 -1
View File
@@ -1,4 +1,4 @@
import { laneDevices, type Db } from "@parking/db";
import { and, eq, laneDevices, type Db } from "@parking/db";
// Resolves a device instance id (lane_devices.id) to its lane number.
//
@@ -28,3 +28,21 @@ export class LaneMap {
return this.#byDeviceId.get(deviceId) ?? null;
}
}
/**
* The lane a reader/scanner belongs to, IF that lane has an access (barrier)
* device to open — shared by the read-driven flows (exit + permit). A read is an
* identity signal; it only drives a barrier where there's one to drive. Returns
* the lane number or null. (Distinguishing entry- vs. exit-readers per lane is a
* later lane-direction model.)
*/
export async function readerLaneWithAccess(db: Db, deviceId: string): Promise<number | null> {
const row = await db.select().from(laneDevices).where(eq(laneDevices.id, deviceId)).get();
if (!row || !row.enabled) return null;
const access = await db
.select()
.from(laneDevices)
.where(and(eq(laneDevices.category, "access"), eq(laneDevices.lane, row.lane)))
.get();
return access && access.enabled ? row.lane : null;
}
+204
View File
@@ -0,0 +1,204 @@
import { and, eq, laneDevices, ledgerEvents, permitCredentials, permitPlates, permits, sessions, type Db } from "@parking/db";
import { registry, type AccessControlDevice } from "@parking/devices";
import type { FastifyBaseLogger } from "fastify";
import type { DeviceReadEvent } from "./device-events.js";
import type { EventLog } from "./event-log.js";
// PERMIT flow: a subscriber identified by card/QR/plate enters/exits without paying.
// Reached from the read dispatcher when a read matches a permit (not an open ticket).
// See wiki/entities/permit.md.
//
// Two optional, independent bindings:
// - car-count: `maxConcurrent` (default 1, null = unbound) — how many of the
// permit's cars may be inside at once; enforced over the session projection.
// - plate: optional `plates[]` — when set, a matching plate is an accepted identity
// too (card/QR OR plate). When unset, any car may use the permit's card/QR.
//
// Direction is inferred from session state for THAT car (the read credential value
// is the per-car session key): no open session → ENTRY; open session → EXIT. So a
// fleet permit can have several cars in at once, each its own session, and
// anti-passback falls out (a second "entry" on a car already in becomes its exit).
export interface PermitMatch {
readonly permitId: string;
/** The specific credential/plate value read — the per-car session key. */
readonly carKey: string;
readonly via: "card" | "qr" | "plate";
}
export class PermitFlow {
readonly #db: Db;
readonly #log: EventLog;
readonly #logger: FastifyBaseLogger;
readonly #inFlight = new Set<string>();
constructor(db: Db, log: EventLog, logger: FastifyBaseLogger) {
this.#db = db;
this.#log = log;
this.#logger = logger;
}
/** Resolve a read to a permit (by card/QR credential, or by a bound plate), or null. */
match(e: DeviceReadEvent): PermitMatch | null {
// Card / QR / generic credential value.
const cred = this.#db
.select()
.from(permitCredentials)
.where(eq(permitCredentials.value, e.value))
.get();
if (cred) {
return { permitId: cred.permitId, carKey: e.value, via: cred.kind === "qr" ? "qr" : "card" };
}
// Plate binding: a read plate that matches a permit's bound plate is an identity.
if (e.kind === "plate") {
const plate = this.#db.select().from(permitPlates).where(eq(permitPlates.plate, e.value)).get();
if (plate) return { permitId: plate.permitId, carKey: e.value, via: "plate" };
}
return null;
}
/** Run the permit entry/exit for a matched read at a lane. */
async run(lane: number, e: DeviceReadEvent, m: PermitMatch): Promise<void> {
const key = `${m.permitId}:${m.carKey}`;
if (this.#inFlight.has(key)) return;
this.#inFlight.add(key);
try {
await this.#run(lane, e, m);
} catch (err) {
this.#logger.error(`permit-flow failed (lane ${lane}): ${(err as Error).message}`);
} finally {
this.#inFlight.delete(key);
}
}
async #run(lane: number, e: DeviceReadEvent, m: PermitMatch): Promise<void> {
const permit = this.#db.select().from(permits).where(eq(permits.id, m.permitId)).get();
if (!permit) return;
// Validity: active + within the coverage window.
const now = new Date().toISOString();
const invalid =
permit.status !== "active" ||
(permit.validFrom != null && now < permit.validFrom) ||
(permit.validTo != null && now > permit.validTo);
if (invalid) {
await this.#reject(lane, m, `permit ${permit.status}/out-of-window`);
return;
}
const carOpen = this.#carHasOpenSession(m.carKey);
if (carOpen) {
// EXIT: this car is already inside → the read is its exit.
await this.#log.append({
type: "vehicle_exit",
lane,
direction: "exit",
source: m.via === "plate" ? "lpr" : m.via === "qr" ? "qr" : "wiegand",
identity: m.carKey,
payload: { sessionRef: m.carKey, permitId: m.permitId },
});
await this.#open(lane, m.carKey, "permit exit");
this.#closeCache(m.carKey);
return;
}
// ENTRY: enforce the car-count binding (maxConcurrent), then sign + open.
if (permit.maxConcurrent != null) {
const open = this.#permitOpenCount(m.permitId);
if (open >= permit.maxConcurrent) {
await this.#reject(lane, m, `permit at capacity (${open}/${permit.maxConcurrent} cars in)`);
return;
}
}
await this.#log.append({
type: "vehicle_entry",
lane,
direction: "entry",
source: m.via === "plate" ? "lpr" : m.via === "qr" ? "qr" : "wiegand",
identity: m.carKey,
// No ticket, no fee — the permit IS the authorization. Recorded for audit.
payload: { sessionRef: m.carKey, permitId: m.permitId, permit: true },
occurredAt: now,
});
await this.#open(lane, m.carKey, "permit entry");
try {
this.#db
.insert(sessions)
.values({ id: m.carKey, lane, identity: m.carKey, source: m.via === "plate" ? "lpr" : "wiegand", permitId: m.permitId, enteredAt: now, state: "open" })
.run();
} catch (err) {
this.#logger.error(`session-cache insert failed for ${m.carKey}: ${(err as Error).message}`);
}
}
/** Does this specific car (credential value) have an open session right now? */
#carHasOpenSession(carKey: string): boolean {
const rows = this.#db
.select()
.from(ledgerEvents)
.where(eq(ledgerEvents.identity, carKey))
.orderBy(ledgerEvents.index)
.all();
const entries = rows.filter((r) => r.type === "vehicle_entry").length;
const exits = rows.filter((r) => r.type === "vehicle_exit").length;
return entries > exits;
}
/** How many of this permit's cars are inside right now (fold over the ledger). */
#permitOpenCount(permitId: string): number {
const rows = this.#db
.select()
.from(ledgerEvents)
.where(and(eq(ledgerEvents.type, "vehicle_entry")))
.all()
.filter((r) => (r.payload as { permitId?: string } | null)?.permitId === permitId);
let open = 0;
for (const entry of rows) {
if (!this.#carHasOpenSession(entry.identity ?? "")) continue;
open += 1;
}
return open;
}
async #reject(lane: number, m: PermitMatch, reason: string): Promise<void> {
await this.#log.append({
type: "anomaly",
lane,
identity: m.carKey,
payload: { reason: `permit refused — ${reason}`, permitId: m.permitId, permitRefused: true },
});
this.#logger.warn(`permit refused (lane ${lane}, ${m.carKey}): ${reason}`);
}
async #open(lane: number, carKey: string, what: string): Promise<void> {
const access = await this.#access(lane);
if (access) await access.pulseOpen(1);
else this.#logger.warn(`${what} signed for ${carKey} but lane ${lane} has no access device`);
}
#closeCache(carKey: string): void {
try {
this.#db.update(sessions).set({ exitedAt: new Date().toISOString(), state: "closed" }).where(eq(sessions.id, carKey)).run();
} catch (err) {
this.#logger.error(`session-cache close failed for ${carKey}: ${(err as Error).message}`);
}
}
async #access(lane: number): Promise<AccessControlDevice | null> {
const row = await this.#db
.select()
.from(laneDevices)
.where(and(eq(laneDevices.category, "access"), eq(laneDevices.lane, lane)))
.get();
if (!row || !row.enabled) return null;
const driver = registry.get(row.driverId);
if (!driver) return null;
try {
return driver.create(row.config as never) as AccessControlDevice;
} catch {
return null;
}
}
}
+41
View File
@@ -0,0 +1,41 @@
import type { Db } from "@parking/db";
import type { FastifyBaseLogger } from "fastify";
import type { DeviceReadEvent } from "./device-events.js";
import type { ExitFlow } from "./exit-flow.js";
import type { PermitFlow } from "./permit-flow.js";
import { readerLaneWithAccess } from "./lane-map.js";
// Routes a credential read (ticket scan / plate / card) to the right flow. A read
// can mean a permit entry/exit OR a transient exit, so we dispatch by WHAT the
// credential is (decision 2026-06-15):
// - matches a permit (card/QR/bound plate) → PERMIT flow (direction inferred from
// the car's open-session state),
// - else → transient EXIT flow (open ticket session → exit, else reject+log).
// Lane is resolved once here; both flows act on a known access-equipped lane.
export class ReadDispatcher {
readonly #db: Db;
readonly #exit: ExitFlow;
readonly #permit: PermitFlow;
readonly #logger: FastifyBaseLogger;
constructor(db: Db, exit: ExitFlow, permit: PermitFlow, logger: FastifyBaseLogger) {
this.#db = db;
this.#exit = exit;
this.#permit = permit;
this.#logger = logger;
}
async dispatch(e: DeviceReadEvent): Promise<void> {
const lane = await readerLaneWithAccess(this.#db, e.deviceId);
if (lane == null) return; // reader not on an access-equipped lane — ignore
const permit = this.#permit.match(e);
if (permit) {
await this.#permit.run(lane, e, permit);
return;
}
// Not a permit → transient ticket exit (the exit flow rejects+logs if unknown).
await this.#exit.handleAt(lane, e);
}
}
+10 -6
View File
@@ -9,6 +9,8 @@ import { EntryFlow } from "./entry-flow.js";
import { EventLog } from "./event-log.js";
import { ExitFlow } from "./exit-flow.js";
import { PayStation } from "./pay-station.js";
import { PermitFlow } from "./permit-flow.js";
import { ReadDispatcher } from "./read-dispatch.js";
import { LaneMap } from "./lane-map.js";
import { PrinterMonitor } from "./printer-monitor.js";
import { buildSigner } from "./signer.js";
@@ -96,14 +98,16 @@ export async function buildServer(opts: BuildOptions = {}): Promise<FastifyInsta
});
app.addHook("onClose", async () => unsubscribeEntry());
// Exit flow: a credential read (ticket scan / plate) at an exit lane → validate
// the session is PAID + within grace → signed vehicle_exit → open. Pay-on-foot:
// the exit lane only validates; payment happens at the station. See parking-session.md.
// Read-driven flows: a credential read (ticket scan / plate / card) routes via the
// dispatcher to either the PERMIT flow (if it matches a permit) or the transient
// EXIT flow. See read-dispatch.ts, exit-flow.ts, permit-flow.ts, parking-session.md.
const exitFlow = new ExitFlow(db, eventLog, app.log);
const unsubscribeExit = deviceEvents.onRead((e) => {
void exitFlow.onRead(e);
const permitFlow = new PermitFlow(db, eventLog, app.log);
const readDispatcher = new ReadDispatcher(db, exitFlow, permitFlow, app.log);
const unsubscribeRead = deviceEvents.onRead((e) => {
void readDispatcher.dispatch(e);
});
app.addHook("onClose", async () => unsubscribeExit());
app.addHook("onClose", async () => unsubscribeRead());
// Pay station (pay-on-foot): quote an open session against the active tariff +
// take payment → signed `payment` event. See wiki/concepts/tariff.md.