import { randomUUID } from "node:crypto"; import { devices, deviceEvents as deviceEventsTable, eq, type Db } from "@parking/db"; import type { FastifyBaseLogger } from "fastify"; import type { DeviceReadEvent, ReadOutcome } from "./device-events.js"; import type { ExitFlow } from "./exit-flow.js"; import { validateTicketCode } from "./entry-flow.js"; import type { SubscriptionFlow } from "./subscription-flow.js"; import { relayForDevice, type ResolvedRelay } from "./device-resolve.js"; // Routes a credential read (ticket scan / plate / card) to the right flow. A read // can mean a subscription entry/exit OR a transient exit, so we dispatch by WHAT the // credential is (decision 2026-06-15): // - matches a subscription (card/QR/bound plate) → SUBSCRIPTION flow, // - else → transient EXIT flow (open ticket session → exit, else reject+log). // // The reader is BOUND to a controller relay (config.controllerId + relay), so a read // resolves to exactly the barrier it sits at, and the direction is inherited from // that relay (see entry-exit-points.md). The resolved relay is handed to the flow so // it opens that exact barrier. An "entry" reader drives the entry side, an "exit" // reader the exit side; "both" defers to the flow's own inference (subscription: // session state; transient: exit). // // STRUCTURAL FILTER (2026-07-04, operator-requested). The DT-008's scan engine // false-decodes sunlight stripe patterns into short garbage codes (phantom reads — // see wiki/entities/dingtian-dt008-reader.md), and each one was reaching the exit // flow and signing an exit.refused.noSession anomaly: red "who is trying to exit?" // rows for NOBODY, training the operator to ignore the feed (alarm fatigue is the // adversary's friend). So a reader value that matched nothing AND cannot possibly be // a credential we issued is dropped to UNSIGNED telemetry (device_events, still // auditable) instead of the signed ledger. "Possibly ours" stays deliberately wide — // any of these still reaches the flows and signs the normal refusal anomaly: // - a Luhn-valid ticket shape (validateTicketCode — a forged/expired ticket is a // real probe), // - our issued-code prefixes (SUB- / SUBSESS-), // - ANY read on a CONFIRMED RF channel (a physically present card, enrolled or // not, is a real event — RF is never sun noise), // - plates (different population; never shape-filtered here). // // SAME-CODE DEBOUNCE (2026-10-11, park-2). The DT-008 reported one card TWICE 560 ms // apart; the permit flow opened two sessions on the same permit and pulsed the barrier // twice. Any reader can double-read (a card held a beat too long, a QR re-decoded while // the hand moves), and at exit a second scan of a ticket inside its grace period would // sign a noSession refusal for a car that just left. So the SAME value from the SAME // reader within the reader's `debounceMs` (Setup → reader; default 5000; 0 = off) is one // presentation: the first verdict is REPLAYED (same beep, no second decision, nothing // signed twice) and the repeat is kept as unsigned telemetry. Every lane, every kind // (card / QR / ticket / plate) — the ANPR bridge debounces plates itself, longer. /** Default same-code debounce when a reader's config has none (ms). */ export const DEFAULT_READ_DEBOUNCE_MS = 5000; /** Recent-reads map housekeeping: prune above the soft cap, never exceed the hard cap, and * treat any entry older than this as expired whatever the reader's configured window. */ const RECENT_READS_SOFT_CAP = 512; const RECENT_READS_HARD_CAP = 4096; const RECENT_READS_MAX_AGE_MS = 60_000; interface ReaderConfig { readonly debounceMs?: number | string | null; readonly [k: string]: unknown; } /** The reader's debounce window: its config value (the Setup form may store a string), * else the default; 0 (or a negative/garbage value coerced to 0) disables. */ export function readDebounceMs(config: unknown): number { const v = (config as ReaderConfig | null)?.debounceMs; if (v == null || v === "") return DEFAULT_READ_DEBOUNCE_MS; const n = Number(v); return Number.isFinite(n) && n > 0 ? n : 0; } export class ReadDispatcher { readonly #db: Db; readonly #exit: ExitFlow; readonly #subscription: SubscriptionFlow; readonly #logger: FastifyBaseLogger; /** Recent reads keyed `deviceId:kind:value` → when last seen + the FIRST verdict (a * promise, so a repeat arriving while the first is still deciding gets that same * decision). `at` slides on each repeat: a card held against the reader stays one * presentation for as long as it keeps re-reading. */ readonly #recent = new Map }>(); constructor(db: Db, exit: ExitFlow, subscription: SubscriptionFlow, logger: FastifyBaseLogger) { this.#db = db; this.#exit = exit; this.#subscription = subscription; this.#logger = logger; } async dispatch(e: DeviceReadEvent): Promise { const reader = this.#db.select().from(devices).where(eq(devices.id, e.deviceId)).get(); if (!reader || !reader.enabled) { return { accepted: false, reason: "read from unknown/disabled device" }; } const resolved = relayForDevice(this.#db, reader); if (!resolved) { return { accepted: false, reason: "reader not bound to a barrier (no relay to open)" }; } // Same code, same reader, inside the window → replay the first verdict. Checked // BEFORE matching so a repeat never reaches a flow (no second entry, no second exit, // no refusal anomaly for a car that was just admitted). const debounceMs = readDebounceMs(reader.config); const key = `${e.deviceId}:${e.kind}:${e.value}`; const now = Date.now(); const prev = this.#recent.get(key); if (debounceMs > 0 && prev && now - prev.at < debounceMs) { const sinceMs = now - prev.at; prev.at = now; this.#logger.info( `read debounced: '${e.value}' (${e.kind}) again on ${e.deviceId} after ${sinceMs}ms (window ${debounceMs}ms) — first verdict replayed`, ); prev.outcome.then( (o) => this.#recordDebounced(e, sinceMs, debounceMs, o), () => undefined, // the first decision failed: the caller gets that rejection, not us ); return prev.outcome; } const outcome = this.#decide(resolved, e); if (debounceMs > 0) { this.#recent.set(key, { at: now, outcome }); // A failed decision is NOT a verdict to replay — forget it so the next read retries. outcome.catch(() => this.#recent.delete(key)); this.#pruneRecent(now); } return outcome; } /** Keep the recent-reads map small: drop expired entries, and if a flood of distinct * values inside one window still leaves it over the cap, drop the oldest. Bounded * memory whatever a misbehaving (or hostile) reader sends. */ #pruneRecent(now: number): void { if (this.#recent.size <= RECENT_READS_SOFT_CAP) return; for (const [k, r] of this.#recent) if (now - r.at >= RECENT_READS_MAX_AGE_MS) this.#recent.delete(k); while (this.#recent.size > RECENT_READS_HARD_CAP) { const oldest = this.#recent.keys().next().value; // insertion order = oldest first if (oldest === undefined) break; this.#recent.delete(oldest); } } /** The actual routing of a FRESH read (not a debounced repeat). */ async #decide(resolved: ResolvedRelay, e: DeviceReadEvent): Promise { const sub = this.#subscription.match(e); if (sub) { return this.#subscription.run(resolved, e, sub); } // Matched nothing — if the value can't even BE one of ours, it's scanner noise // (phantom optical decode): refuse with unsigned telemetry, keep the signed feed // for events that involve an actual credential or an actual card. if ((e.kind === "qr" || e.kind === "card" || e.kind === "ticket") && !plausibleCredential(e)) { this.#recordUnrecognized(e); this.#logger.info(`read filtered (not a credential shape): '${e.value}' from ${e.deviceId}${e.channel ? ` ch=${e.channel}` : ""}`); return { accepted: false, direction: resolved.direction === "entry" ? "entry" : "exit", reason: "unrecognized code (no credential shape — telemetry only)", }; } // Not a subscription → transient ticket exit. An ENTRY reader can't produce a // transient exit (transient entry is the button flow, not a reader), so reject+log // rather than treat an entry scan as an exit. if (resolved.direction === "entry") { return { accepted: false, direction: "entry", reason: "entry reader: no transient entry via reader" }; } return this.#exit.handleAt(resolved, e); } /** Unsigned telemetry for a debounced repeat — auditable in device_events (the double * read is still a fact about the hardware), out of the signed feed. */ #recordDebounced(e: DeviceReadEvent, sinceMs: number, debounceMs: number, replayed: ReadOutcome): void { try { this.#db .insert(deviceEventsTable) .values({ id: randomUUID(), deviceId: e.deviceId, category: "reader", kind: "read", detail: { debounced: true, value: e.value, readKind: e.kind, ...(e.channel ? { channel: e.channel } : {}), sinceMs, debounceMs, replayedAccepted: replayed.accepted, }, occurredAt: e.at, }) .run(); } catch (err) { this.#logger.error(`debounced-read telemetry insert failed: ${(err as Error).message}`); } } /** Unsigned telemetry for a filtered read — auditable in device_events, out of the * signed feed. Mirrors the entry flow's suppressed-press pattern. */ #recordUnrecognized(e: DeviceReadEvent): void { try { this.#db .insert(deviceEventsTable) .values({ id: randomUUID(), deviceId: e.deviceId, category: "reader", kind: "read", detail: { unrecognizedRead: true, value: e.value, readKind: e.kind, ...(e.channel ? { channel: e.channel } : {}), reason: "no credential shape (phantom decode / garbage scan)", }, occurredAt: e.at, }) .run(); } catch (err) { this.#logger.error(`unrecognized-read telemetry insert failed: ${(err as Error).message}`); } } } /** Could this reader value possibly be a credential WE issued (or a real card)? * Deliberately WIDE — only shapes that can't be anything of ours are filtered. */ function plausibleCredential(e: DeviceReadEvent): boolean { if (e.channel === "rf") return true; // a physically present card — never sun noise if (validateTicketCode(e.value)) return true; // ticket shape (10–14 digits + Luhn) if (/^SUB(SESS)?-/.test(e.value)) return true; // our subscription QR / window-slip ids return false; }