Compare commits
40 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1efa77bf56 | |||
| 15d3e1ba08 | |||
| ff3b011fe0 | |||
| 5705098054 | |||
| 68d61f2d99 | |||
| 04135b27cf | |||
| 392d44d842 | |||
| f67c1ead87 | |||
| bf37106c5c | |||
| e579fe5b6e | |||
| 644bfa1462 | |||
| 3429642edb | |||
| c24d99b0f4 | |||
| b4d0dfadd6 | |||
| f18e28eeca | |||
| a8c6d6e714 | |||
| 2a36830880 | |||
| 2696d281ce | |||
| 648d3254d6 | |||
| 8c2cf93067 | |||
| 9a4c7ee27b | |||
| 8a8e74561d | |||
| 2ab5a39a57 | |||
| fa65b2df86 | |||
| 59bfe2013f | |||
| f5fd61984a | |||
| 7db5cfa0e4 | |||
| add5fc0166 | |||
| 39d4bac419 | |||
| b2a0471b08 | |||
| 2a86e578a8 | |||
| 382c32f2bc | |||
| 7fd407ac82 | |||
| 0375227a16 | |||
| 3294f188dd | |||
| 23919164ee | |||
| 355026dcf7 | |||
| 1b55e2034d | |||
| 4319fb86dc | |||
| dbf1fa17d7 |
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"hooks": {
|
||||
"PreToolUse": [
|
||||
{
|
||||
"matcher": "Bash",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "CMD=$(python3 -c \"import json,sys; d=json.load(sys.stdin); print(d.get('tool_input',d).get('command',''))\" 2>/dev/null || true); case \"$CMD\" in *grep*|*rg\\ *|*ripgrep*|*find\\ *|*fd\\ *|*ack\\ *|*ag\\ *) [ -f graphify-out/graph.json ] && echo '{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"additionalContext\":\"MANDATORY: graphify-out/graph.json exists. You MUST run `graphify query \\\"<question>\\\"` before grepping raw files. Only grep after graphify has oriented you, or to modify/debug specific lines.\"}}' || true ;; esac"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"matcher": "Read|Glob",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "HIT=$(python3 -c \"import json,sys;d=json.load(sys.stdin);t=d.get('tool_input',d);s=(str(t.get('file_path') or '')+' '+str(t.get('pattern') or '')+' '+str(t.get('path') or '')).lower().replace(chr(92),'/');exts=('.py','.js','.ts','.tsx','.jsx','.go','.rs','.java','.rb','.c','.h','.cpp','.hpp','.cc','.cs','.kt','.swift','.php','.scala','.lua','.sh','.md','.rst','.txt','.mdx');sys.stdout.write('1' if 'graphify-out/' not in s and any(e in s for e in exts) else '')\" 2>/dev/null || true); if [ \"$HIT\" = 1 ] && [ -f graphify-out/graph.json ]; then echo '{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"additionalContext\":\"MANDATORY: graphify-out/graph.json exists. You MUST run graphify before reading source files. Use: `graphify query \\\"<question>\\\"` (scoped subgraph), `graphify explain \\\"<concept>\\\"`, or `graphify path \\\"<A>\\\" \\\"<B>\\\"`. Only read raw files after graphify has oriented you, or to modify/debug specific lines. This rule applies to subagents too \u2014 include it in every subagent prompt involving code exploration.\"}}'; fi || true"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
+7
-1
@@ -17,4 +17,10 @@ dist/
|
||||
*:Zone.Identifier
|
||||
.playwright-mcp/
|
||||
# stray hardware/UI test screenshots
|
||||
/*.png
|
||||
/*.png
|
||||
# Vendor device SDKs (reference only — protocol captured in wiki, not committed)
|
||||
/dingtian/
|
||||
/QRCode_sdk*/
|
||||
|
||||
# Graphify knowledge-graph output (dev tool; generated, not committed)
|
||||
graphify-out/
|
||||
|
||||
@@ -86,3 +86,13 @@ For the full reasoning behind each, follow the links from `wiki/overview.md`.
|
||||
|
||||
- TypeScript throughout. Match the style of surrounding code.
|
||||
- Confirm before destructive or outward-facing actions. Commit/push only when asked.
|
||||
|
||||
## graphify
|
||||
|
||||
This project has a knowledge graph at graphify-out/ with god nodes, community structure, and cross-file relationships.
|
||||
|
||||
Rules:
|
||||
- For codebase questions, first run `graphify query "<question>"` when graphify-out/graph.json exists. Use `graphify path "<A>" "<B>"` for relationships and `graphify explain "<concept>"` for focused concepts. These return a scoped subgraph, usually much smaller than GRAPH_REPORT.md or raw grep output.
|
||||
- If graphify-out/wiki/index.md exists, use it for broad navigation instead of raw source browsing.
|
||||
- Read graphify-out/GRAPH_REPORT.md only for broad architecture review or when query/path/explain do not surface enough context.
|
||||
- After modifying code, run `graphify update .` to keep the graph current (AST-only, no API cost).
|
||||
|
||||
@@ -21,8 +21,7 @@
|
||||
"@parking/shared": "workspace:*",
|
||||
"bcrypt": "6.0.0",
|
||||
"fastify": "5.8.5",
|
||||
"fastify-plugin": "6.0.0",
|
||||
"uhppoted": "0.9.0"
|
||||
"fastify-plugin": "6.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bcrypt": "6.0.0",
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
// Dingtian relay+input hardware test.
|
||||
//
|
||||
// node apps/server/scripts/dingtian-test.mjs # status only (safe)
|
||||
// node apps/server/scripts/dingtian-test.mjs watch # live input/button monitor
|
||||
// node apps/server/scripts/dingtian-test.mjs pulse 1 # pulse relay 1 (prompts)
|
||||
//
|
||||
// Env: DINGTIAN_HOST (default 10.0.10.172), DINGTIAN_PORT (60001).
|
||||
//
|
||||
// SAFETY: `pulse` fires a relay → the barrier may move. It prompts first unless
|
||||
// YES=1. pulseOpen is momentary (the device self-releases).
|
||||
|
||||
import { createInterface } from "node:readline/promises";
|
||||
import { stdin, stdout } from "node:process";
|
||||
import { createRequire } from "node:module";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const { dingtianDriver } = require("@parking/devices");
|
||||
|
||||
const host = process.env.DINGTIAN_HOST ?? "10.0.10.172";
|
||||
const port = process.env.DINGTIAN_PORT ? Number(process.env.DINGTIAN_PORT) : 60001;
|
||||
const dev = dingtianDriver.create({ host, port, channels: 4 });
|
||||
|
||||
const mode = process.argv[2] ?? "status";
|
||||
console.log(`dingtian @ ${host}:${port}\n`);
|
||||
|
||||
async function showStatus() {
|
||||
const health = await dev.healthCheck();
|
||||
console.log("health:", JSON.stringify(health));
|
||||
const inputs = await dev.readInputs();
|
||||
console.log("inputs (active=pressed):", inputs.map((v, i) => `in${i + 1}=${v ? "ON" : "off"}`).join(" "));
|
||||
for (let ch = 1; ch <= 4; ch++) {
|
||||
console.log(`relay ${ch}:`, await dev.getDoorStatus(ch));
|
||||
}
|
||||
}
|
||||
|
||||
if (mode === "status") {
|
||||
await showStatus();
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (mode === "watch") {
|
||||
console.log("── press the buttons on the inputs — Ctrl-C to stop ──\n");
|
||||
const unsub = dev.onInput((e) => {
|
||||
console.log(`[${e.at}] input ${e.input} ${e.edge.toUpperCase()}`);
|
||||
});
|
||||
process.on("SIGINT", () => {
|
||||
unsub();
|
||||
console.log("\nstopped.");
|
||||
process.exit(0);
|
||||
});
|
||||
// keep alive
|
||||
await new Promise(() => {});
|
||||
}
|
||||
|
||||
if (mode === "pulse") {
|
||||
const ch = Number(process.argv[3] ?? 1);
|
||||
if (process.env.YES !== "1") {
|
||||
const rl = createInterface({ input: stdin, output: stdout });
|
||||
const ans = (await rl.question(`Pulse relay ${ch}? (barrier may move) [y/N] `)).trim();
|
||||
rl.close();
|
||||
if (ans.toLowerCase() !== "y") {
|
||||
console.log("aborted.");
|
||||
process.exit(0);
|
||||
}
|
||||
}
|
||||
await dev.pulseOpen(ch);
|
||||
console.log(`pulsed relay ${ch}.`);
|
||||
// show the relay state right after (likely back off — pulse is momentary)
|
||||
setTimeout(async () => {
|
||||
console.log(`relay ${ch} now:`, await dev.getDoorStatus(ch));
|
||||
process.exit(0);
|
||||
}, 300);
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
// Shared helpers for the UHPPOTE hardware test scripts.
|
||||
// Run directly against the device (independent of the HTTP server).
|
||||
//
|
||||
// node apps/server/scripts/uhppote-listen.mjs
|
||||
// node apps/server/scripts/uhppote-relay.mjs
|
||||
//
|
||||
// Env overrides:
|
||||
// UHPPOTE_SERIAL controller serial (default 225088491)
|
||||
// UHPPOTE_HOST controller IP (default 10.0.10.3)
|
||||
// UHPPOTE_BCAST Config broadcast (default derived from HOST subnet)
|
||||
// HOST_IP this host's IP the controller pushes events to
|
||||
// (default: auto-detected interface on the controller's subnet)
|
||||
|
||||
import { networkInterfaces } from "node:os";
|
||||
import { createRequire } from "node:module";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const uhppoted = require("uhppoted");
|
||||
|
||||
export const SERIAL = Number(process.env.UHPPOTE_SERIAL ?? 225088491);
|
||||
export const HOST = process.env.UHPPOTE_HOST ?? "10.0.10.3";
|
||||
|
||||
/** Subnet-directed broadcast for the interface that owns `ip`. */
|
||||
function broadcastForHost(ip) {
|
||||
const o = ip.split(".").map(Number);
|
||||
for (const ifaces of Object.values(networkInterfaces())) {
|
||||
for (const i of ifaces ?? []) {
|
||||
if (i.family !== "IPv4" || i.internal) continue;
|
||||
const a = i.address.split(".").map(Number);
|
||||
const m = i.netmask.split(".").map(Number);
|
||||
if (o.every((x, k) => (x & m[k]) === (a[k] & m[k]))) {
|
||||
return a.map((x, k) => (x & m[k]) | (~m[k] & 0xff)).join(".");
|
||||
}
|
||||
}
|
||||
}
|
||||
return "255.255.255.255";
|
||||
}
|
||||
|
||||
/** This host's own IP on the controller's subnet (where it should push events). */
|
||||
export function hostIpOnControllerSubnet(ip = HOST) {
|
||||
if (process.env.HOST_IP) return process.env.HOST_IP;
|
||||
const o = ip.split(".").map(Number);
|
||||
for (const ifaces of Object.values(networkInterfaces())) {
|
||||
for (const i of ifaces ?? []) {
|
||||
if (i.family !== "IPv4" || i.internal) continue;
|
||||
const a = i.address.split(".").map(Number);
|
||||
const m = i.netmask.split(".").map(Number);
|
||||
if (o.every((x, k) => (x & m[k]) === (a[k] & m[k]))) return i.address;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export const BCAST = process.env.UHPPOTE_BCAST ?? broadcastForHost(HOST);
|
||||
|
||||
export function makeCtx(timeoutMs = 5000) {
|
||||
return {
|
||||
config: new uhppoted.Config(
|
||||
"parking",
|
||||
"0.0.0.0",
|
||||
`${BCAST}:60000`,
|
||||
"0.0.0.0:60001",
|
||||
timeoutMs,
|
||||
[],
|
||||
false,
|
||||
),
|
||||
locale: "en-US",
|
||||
};
|
||||
}
|
||||
|
||||
export const controller = { id: SERIAL, address: HOST, protocol: "udp" };
|
||||
export { uhppoted };
|
||||
@@ -1,100 +0,0 @@
|
||||
// Live button/event listener for the UHPPOTE controller.
|
||||
//
|
||||
// Points the controller's event listener at THIS host, then prints each pushed
|
||||
// event in real time. Press the door buttons on the controller and watch them
|
||||
// appear. Ctrl-C to stop.
|
||||
//
|
||||
// node apps/server/scripts/uhppote-listen.mjs
|
||||
|
||||
import {
|
||||
controller,
|
||||
hostIpOnControllerSubnet,
|
||||
makeCtx,
|
||||
uhppoted,
|
||||
} from "./uhppote-common.mjs";
|
||||
|
||||
const ctx = makeCtx();
|
||||
|
||||
const hostIp = hostIpOnControllerSubnet();
|
||||
if (!hostIp) {
|
||||
console.error("Could not determine this host's IP on the controller's subnet.");
|
||||
console.error("Set HOST_IP=<your-ip-on-the-controller-LAN> and retry.");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(`controller : ${controller.id} @ ${controller.address}`);
|
||||
console.log(`this host : ${hostIp} (events will be pushed here on :60001)`);
|
||||
|
||||
// 0) Remember the controller's current listener so we can restore it on exit
|
||||
// (it was pointing somewhere else, e.g. 10.0.10.241).
|
||||
let prevListener = null;
|
||||
try {
|
||||
prevListener = await uhppoted.getListener(ctx, controller);
|
||||
console.log(`prior listener: ${prevListener.address}:${prevListener.port} (will restore on exit)`);
|
||||
} catch (e) {
|
||||
console.warn("getListener (non-fatal):", e.code ?? e.message);
|
||||
}
|
||||
|
||||
// 1) Tell the controller to push events to us.
|
||||
try {
|
||||
const r = await uhppoted.setListener(ctx, controller, hostIp, 60001);
|
||||
console.log("setListener:", JSON.stringify(r));
|
||||
} catch (e) {
|
||||
console.error("setListener failed:", e.code ?? e.message);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// 2) (Best-effort) ensure door open/close + button events are recorded.
|
||||
try {
|
||||
await uhppoted.recordSpecialEvents(ctx, controller, true);
|
||||
console.log("recordSpecialEvents: enabled");
|
||||
} catch (e) {
|
||||
console.warn("recordSpecialEvents (non-fatal):", e.code ?? e.message);
|
||||
}
|
||||
|
||||
console.log("\n── listening — press the door buttons on the controller ──\n");
|
||||
|
||||
function describe(ev) {
|
||||
const e = ev?.state?.event ?? ev?.event;
|
||||
const buttons = ev?.state?.buttons;
|
||||
const doors = ev?.state?.doors;
|
||||
const parts = [];
|
||||
if (e) {
|
||||
parts.push(
|
||||
`event#${e.index} type=${e.type?.event ?? e.type?.code} door=${e.door} granted=${e.granted} reason="${e.reason?.reason ?? e.reason?.code}" @${e.timestamp}`,
|
||||
);
|
||||
}
|
||||
if (buttons) {
|
||||
const pressed = Object.entries(buttons).filter(([, v]) => v).map(([k]) => k);
|
||||
parts.push(`buttons=[${pressed.join(",") || "none"}]`);
|
||||
}
|
||||
if (doors) {
|
||||
const open = Object.entries(doors).filter(([, v]) => v).map(([k]) => k);
|
||||
parts.push(`doorsOpen=[${open.join(",") || "none"}]`);
|
||||
}
|
||||
return parts.join(" ");
|
||||
}
|
||||
|
||||
uhppoted.listen(
|
||||
ctx,
|
||||
(event) => {
|
||||
console.log(`[${new Date().toISOString()}] ${describe(event)}`);
|
||||
},
|
||||
(err) => {
|
||||
console.error("listen error:", err?.message ?? err);
|
||||
},
|
||||
);
|
||||
|
||||
process.on("SIGINT", async () => {
|
||||
// Restore the controller's previous listener so we don't hijack it.
|
||||
if (prevListener && prevListener.address && prevListener.address !== "0.0.0.0") {
|
||||
try {
|
||||
await uhppoted.setListener(ctx, controller, prevListener.address, prevListener.port);
|
||||
console.log(`\nrestored listener -> ${prevListener.address}:${prevListener.port}`);
|
||||
} catch (e) {
|
||||
console.warn("\ncould not restore listener:", e.code ?? e.message);
|
||||
}
|
||||
}
|
||||
console.log("stopped.");
|
||||
process.exit(0);
|
||||
});
|
||||
@@ -1,44 +0,0 @@
|
||||
// Guarded relay (door-open) test for the UHPPOTE controller.
|
||||
//
|
||||
// Prompts before firing each relay so a door only opens when you're ready and
|
||||
// watching. This is a 2-door controller, so it tests doors 1 and 2 by default.
|
||||
//
|
||||
// node apps/server/scripts/uhppote-relay.mjs # doors 1,2 (prompted)
|
||||
// node apps/server/scripts/uhppote-relay.mjs 1 # only door 1
|
||||
// YES=1 node apps/server/scripts/uhppote-relay.mjs # no prompts (fires!)
|
||||
//
|
||||
// SAFETY: openDoor only expresses INTENT to open. The controller / barrier
|
||||
// operator owns the close timing and anti-crush — we never time a close.
|
||||
|
||||
import { createInterface } from "node:readline/promises";
|
||||
import { stdin, stdout } from "node:process";
|
||||
import { controller, makeCtx, uhppoted } from "./uhppote-common.mjs";
|
||||
|
||||
const ctx = makeCtx();
|
||||
const doors = process.argv.slice(2).map(Number).filter((n) => n >= 1 && n <= 4);
|
||||
const targets = doors.length ? doors : [1, 2];
|
||||
const autoYes = process.env.YES === "1";
|
||||
|
||||
console.log(`controller : ${controller.id} @ ${controller.address}`);
|
||||
console.log(`testing doors: ${targets.join(", ")}${autoYes ? " (auto, no prompts)" : ""}\n`);
|
||||
|
||||
const rl = autoYes ? null : createInterface({ input: stdin, output: stdout });
|
||||
|
||||
for (const door of targets) {
|
||||
if (rl) {
|
||||
const ans = await rl.question(`Open door ${door}? [y/N] `);
|
||||
if (ans.trim().toLowerCase() !== "y") {
|
||||
console.log(` skipped door ${door}`);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
try {
|
||||
const res = await uhppoted.openDoor(ctx, controller, door);
|
||||
console.log(` door ${door}: openDoor -> ${JSON.stringify(res)}`);
|
||||
} catch (e) {
|
||||
console.log(` door ${door}: ERROR ${e.code ?? e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
rl?.close();
|
||||
console.log("\ndone.");
|
||||
+11
-5
@@ -18,9 +18,15 @@ export const TOKEN_COOKIE = "parking_token";
|
||||
export const CSRF_COOKIE = "parking_csrf";
|
||||
export const CSRF_HEADER = "x-csrf-token";
|
||||
|
||||
/** Token lifetime, also used as the cookie maxAge. */
|
||||
export const TOKEN_TTL = "8h";
|
||||
export const TOKEN_TTL_SECONDS = 8 * 60 * 60;
|
||||
// Session lifetime: the JWT has NO expiry — a login is valid until explicit
|
||||
// logout. Booth reality breaks any fixed clock (relief late/absent, forced double
|
||||
// shifts), and a shift is a separate explicit boundary, not the token's lifetime.
|
||||
// See wiki/entities/local-jwt-auth.md + wiki/concepts/shift.md.
|
||||
//
|
||||
// The cookie still needs a maxAge so it survives a browser restart (a session
|
||||
// cookie would log out an active operator on browser close — the opposite of
|
||||
// "until logout"). Use a long fixed window; the server clears it on logout.
|
||||
export const COOKIE_MAX_AGE_SECONDS = 30 * 24 * 60 * 60; // 30 days
|
||||
|
||||
/**
|
||||
* Resolve the JWT signing secret, refusing to start without a strong one.
|
||||
@@ -55,7 +61,7 @@ export function setAuthCookies(reply: FastifyReply, jwt: string, csrf: string):
|
||||
sameSite: "strict",
|
||||
secure,
|
||||
path: "/",
|
||||
maxAge: TOKEN_TTL_SECONDS,
|
||||
maxAge: COOKIE_MAX_AGE_SECONDS,
|
||||
});
|
||||
// Readable by JS so the SPA can echo it back in the CSRF header (double-submit).
|
||||
reply.setCookie(CSRF_COOKIE, csrf, {
|
||||
@@ -63,7 +69,7 @@ export function setAuthCookies(reply: FastifyReply, jwt: string, csrf: string):
|
||||
sameSite: "strict",
|
||||
secure,
|
||||
path: "/",
|
||||
maxAge: TOKEN_TTL_SECONDS,
|
||||
maxAge: COOKIE_MAX_AGE_SECONDS,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import type { PrinterStatus } from "@parking/devices";
|
||||
|
||||
// Internal event bus for device-originated events (button presses, etc.).
|
||||
// Hardware drivers / inbound device pushes emit here; business logic (entry
|
||||
// flow, event-log) subscribes — keeping the HTTP/transport layer thin and the
|
||||
// app device-agnostic. See wiki/entities/fastify.md.
|
||||
|
||||
export interface DeviceInputEvent {
|
||||
readonly driverId: string; // e.g. "dingtian"
|
||||
readonly deviceId: string; // which configured device (devices id)
|
||||
readonly input: number; // 1-based input/channel
|
||||
readonly edge: "on" | "off"; // active / inactive
|
||||
readonly at: string; // ISO-8601 (server receive time)
|
||||
readonly source: "push" | "poll";
|
||||
}
|
||||
|
||||
// A credential read: a ticket scanned at exit, a plate from LPR, a card at a reader.
|
||||
// Drives identity-based flows (exit validation, permits, pay-station lookup). `kind`
|
||||
// mirrors IdentitySource. See parking-session.md.
|
||||
export interface DeviceReadEvent {
|
||||
readonly driverId: string;
|
||||
readonly deviceId: string; // devices id of the reader/scanner/camera
|
||||
readonly value: string; // the ticket id / plate / card number
|
||||
readonly kind: "ticket" | "plate" | "qr" | "card";
|
||||
readonly at: string; // ISO-8601
|
||||
}
|
||||
|
||||
/**
|
||||
* The decision a read produced. Returned by the read flows so a SYNCHRONOUS reader
|
||||
* (e.g. the QR reader, whose HTTP reply drives its beep + output) can answer the
|
||||
* device. A fire-and-forget reader simply ignores it. See wiki/entities/gee-qr-er80.md.
|
||||
*/
|
||||
export interface ReadOutcome {
|
||||
/** Was the vehicle admitted/exited (barrier opened)? Drives the reader's beep. */
|
||||
readonly accepted: boolean;
|
||||
/** Which way it went, when known (permit/exit infer this). */
|
||||
readonly direction?: "entry" | "exit";
|
||||
/** Human-readable reason (for logs / the reader UI), esp. on reject. */
|
||||
readonly reason?: string;
|
||||
}
|
||||
|
||||
/** A printer's status as tracked by the live monitor (status + identity). */
|
||||
export interface PrinterStatusEvent {
|
||||
readonly deviceId: string; // devices id
|
||||
readonly driverId: string;
|
||||
readonly role?: string; // entry-dispenser | booth-receipt
|
||||
readonly status: PrinterStatus;
|
||||
}
|
||||
|
||||
class DeviceEventBus extends EventEmitter {
|
||||
emitInput(event: DeviceInputEvent): void {
|
||||
this.emit("input", event);
|
||||
}
|
||||
onInput(cb: (event: DeviceInputEvent) => void): () => void {
|
||||
this.on("input", cb);
|
||||
return () => this.off("input", cb);
|
||||
}
|
||||
|
||||
/** A credential read (ticket scan, plate, card). */
|
||||
emitRead(event: DeviceReadEvent): void {
|
||||
this.emit("read", event);
|
||||
}
|
||||
onRead(cb: (event: DeviceReadEvent) => void): () => void {
|
||||
this.on("read", cb);
|
||||
return () => this.off("read", cb);
|
||||
}
|
||||
|
||||
/** Emitted by the printer monitor whenever a printer's status CHANGES. */
|
||||
emitPrinterStatus(event: PrinterStatusEvent): void {
|
||||
this.emit("printer-status", event);
|
||||
}
|
||||
onPrinterStatus(cb: (event: PrinterStatusEvent) => void): () => void {
|
||||
this.on("printer-status", cb);
|
||||
return () => this.off("printer-status", cb);
|
||||
}
|
||||
}
|
||||
|
||||
/** Process-wide device event bus. */
|
||||
export const deviceEvents = new DeviceEventBus();
|
||||
@@ -0,0 +1,155 @@
|
||||
import { and, eq, devices, type Db, type DeviceRow } from "@parking/db";
|
||||
|
||||
// Device resolution for the pool-of-spaces model — NO lane. A parking lot is one
|
||||
// pool with a flexible set of entry/exit points. Direction lives on each RELAY
|
||||
// inside an access controller, and readers/cameras BIND to a (controller, relay).
|
||||
// See wiki/concepts/entry-exit-points.md.
|
||||
|
||||
/** A flow direction. "both" = one relay/barrier serving entry AND exit. */
|
||||
export type Direction = "entry" | "exit" | "both";
|
||||
/** A concrete flow a credential/button drives (never "both"). */
|
||||
export type FlowDirection = "entry" | "exit";
|
||||
|
||||
/** One relay on an access controller: which barrier it opens, in which direction,
|
||||
* and (optionally) the input terminal its entry button is wired to. */
|
||||
export interface RelaySpec {
|
||||
/** 1-based relay channel on the board (the driver's pulseOpen(doorId)). */
|
||||
readonly relay: number;
|
||||
readonly direction: Direction;
|
||||
/** 1-based input terminal of the entry button that fires this relay (transient
|
||||
* entry). Absent = no button at this barrier (subscriber/reader-driven only). */
|
||||
readonly button?: number;
|
||||
}
|
||||
|
||||
/** Access controller config (the `relays[]` map + connection fields). */
|
||||
interface AccessConfig {
|
||||
readonly relays?: RelaySpec[];
|
||||
readonly [k: string]: unknown;
|
||||
}
|
||||
|
||||
/** Reader/camera config: optional binding to a controller relay. */
|
||||
interface BoundConfig {
|
||||
/** The access `devices.id` this reader/camera sits at. */
|
||||
readonly controllerId?: string;
|
||||
/** The relay on that controller it opens. */
|
||||
readonly relay?: number;
|
||||
/** Fallback direction when not bound to a relay. */
|
||||
readonly direction?: Direction;
|
||||
readonly [k: string]: unknown;
|
||||
}
|
||||
|
||||
/** A resolved barrier: the controller row + the specific relay to pulse. */
|
||||
export interface ResolvedRelay {
|
||||
readonly controller: DeviceRow;
|
||||
readonly relay: number;
|
||||
readonly direction: Direction;
|
||||
}
|
||||
|
||||
/** All enabled access controller rows. */
|
||||
function accessRows(db: Db): DeviceRow[] {
|
||||
return db
|
||||
.select()
|
||||
.from(devices)
|
||||
.where(eq(devices.category, "access"))
|
||||
.all()
|
||||
.filter((r) => r.enabled);
|
||||
}
|
||||
|
||||
/** The relay specs declared on an access controller (defaults to none). */
|
||||
export function relaysOf(row: DeviceRow): RelaySpec[] {
|
||||
const cfg = row.config as AccessConfig;
|
||||
return Array.isArray(cfg.relays) ? cfg.relays : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a button press to the relay it fires: the access controller with this
|
||||
* deviceId, and the relay whose `button` terminal matches the pressed input. Only
|
||||
* an ENTRY (or both) relay is a transient-entry trigger. Returns null otherwise.
|
||||
*/
|
||||
export function relayForButton(db: Db, controllerId: string, terminal: number): ResolvedRelay | null {
|
||||
const row = db
|
||||
.select()
|
||||
.from(devices)
|
||||
.where(and(eq(devices.id, controllerId), eq(devices.category, "access")))
|
||||
.get();
|
||||
if (!row || !row.enabled) return null;
|
||||
const spec = relaysOf(row).find((r) => r.button === terminal);
|
||||
if (!spec) return null;
|
||||
if (spec.direction !== "entry" && spec.direction !== "both") return null;
|
||||
return { controller: row, relay: spec.relay, direction: spec.direction };
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a reader/camera to the relay it opens. Preferred: its config binding
|
||||
* (controllerId + relay) → exactly that barrier, direction inherited from the relay
|
||||
* spec. Fallback (unbound): the device's config.direction + the first relay site-
|
||||
* wide matching that direction — keeps the single-barrier case trivial. Null if
|
||||
* nothing resolves (no barrier to open).
|
||||
*/
|
||||
export function relayForDevice(db: Db, deviceRow: DeviceRow): ResolvedRelay | null {
|
||||
const cfg = deviceRow.config as BoundConfig;
|
||||
|
||||
// Bound: follow controllerId + relay to the exact barrier.
|
||||
if (cfg.controllerId && typeof cfg.relay === "number") {
|
||||
const controller = db
|
||||
.select()
|
||||
.from(devices)
|
||||
.where(and(eq(devices.id, cfg.controllerId), eq(devices.category, "access")))
|
||||
.get();
|
||||
if (controller && controller.enabled) {
|
||||
const spec = relaysOf(controller).find((r) => r.relay === cfg.relay);
|
||||
if (spec) return { controller, relay: spec.relay, direction: spec.direction };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Unbound: fall back to the device's declared direction + first matching relay.
|
||||
const want = cfg.direction;
|
||||
if (want === "entry" || want === "exit" || want === "both") {
|
||||
return firstRelayByDirection(db, want === "both" ? "entry" : want);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The first relay site-wide serving a direction ("both" relays match either).
|
||||
* Used as the unbound fallback and where a flow only needs "an exit barrier".
|
||||
*/
|
||||
export function firstRelayByDirection(db: Db, direction: FlowDirection): ResolvedRelay | null {
|
||||
for (const controller of accessRows(db)) {
|
||||
const spec = relaysOf(controller).find(
|
||||
(r) => r.direction === direction || r.direction === "both",
|
||||
);
|
||||
if (spec) return { controller, relay: spec.relay, direction: spec.direction };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Enabled devices of a category whose direction matches `want` (or is "both").
|
||||
* Direction is inherited from each device's bound relay, else its config fallback.
|
||||
* Used for snapshots: every entry/exit camera fires on an entry/exit. */
|
||||
export function devicesByDirection(
|
||||
db: Db,
|
||||
category: DeviceRow["category"],
|
||||
want: FlowDirection,
|
||||
): DeviceRow[] {
|
||||
return db
|
||||
.select()
|
||||
.from(devices)
|
||||
.where(eq(devices.category, category))
|
||||
.all()
|
||||
.filter((r) => {
|
||||
if (!r.enabled) return false;
|
||||
const d = directionOf(db, r);
|
||||
return d === want || d === "both";
|
||||
});
|
||||
}
|
||||
|
||||
/** The direction a reader/camera operates in (inherited from its bound relay, or
|
||||
* its config fallback). "both" when undetermined → the flow infers. */
|
||||
export function directionOf(db: Db, deviceRow: DeviceRow): Direction {
|
||||
const resolved = relayForDevice(db, deviceRow);
|
||||
if (resolved) return resolved.direction;
|
||||
const cfg = deviceRow.config as BoundConfig;
|
||||
return cfg.direction === "entry" || cfg.direction === "exit" ? cfg.direction : "both";
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import type { FastifyReply, FastifyRequest } from "fastify";
|
||||
|
||||
// HTTP Digest auth (RFC 2617, MD5, qop=auth) — verified against the Dingtian
|
||||
// device, which CAN do Digest but CANNOT do HTTPS to a self-signed cert. On
|
||||
// this flat network Digest is the strongest available push auth: the password
|
||||
// is never sent (only a nonce-keyed hash). It is defence-in-depth; the signed
|
||||
// event log is the real anti-fraud guarantee. See wiki/concepts/device-input-flow.md.
|
||||
|
||||
export const DIGEST_REALM = "parking";
|
||||
|
||||
const md5 = (s: string) => createHash("md5").update(s).digest("hex");
|
||||
|
||||
/** Nonces we've issued and not yet consumed (single-use → replay resistance). */
|
||||
const issuedNonces = new Map<string, number>(); // nonce → issuedAt (ms epoch is unavailable in scripts but fine at runtime)
|
||||
const NONCE_TTL_MS = 5 * 60_000;
|
||||
|
||||
function issueNonce(): string {
|
||||
const nonce = randomBytes(16).toString("hex");
|
||||
issuedNonces.set(nonce, Date.now());
|
||||
// opportunistic cleanup
|
||||
if (issuedNonces.size > 1000) {
|
||||
const cutoff = Date.now() - NONCE_TTL_MS;
|
||||
for (const [n, t] of issuedNonces) if (t < cutoff) issuedNonces.delete(n);
|
||||
}
|
||||
return nonce;
|
||||
}
|
||||
|
||||
function parseDigest(header: string): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
const re = /(\w+)=(?:"([^"]*)"|([^,]*))/g;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = re.exec(header))) out[m[1]!] = (m[2] ?? m[3] ?? "").trim();
|
||||
return out;
|
||||
}
|
||||
|
||||
function eq(a: string, b: string): boolean {
|
||||
const ab = Buffer.from(a);
|
||||
const bb = Buffer.from(b);
|
||||
return ab.length === bb.length && timingSafeEqual(ab, bb);
|
||||
}
|
||||
|
||||
export interface DigestCreds {
|
||||
readonly user: string;
|
||||
readonly password: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify a Digest Authorization header. Returns true on success. On failure (or
|
||||
* a missing/expired header) sets a 401 challenge on `reply` and returns false —
|
||||
* the caller should stop. `creds` is the device's stored push credentials.
|
||||
*/
|
||||
export function verifyDigest(
|
||||
req: FastifyRequest,
|
||||
reply: FastifyReply,
|
||||
creds: DigestCreds,
|
||||
): boolean {
|
||||
const header = req.headers["authorization"];
|
||||
|
||||
if (!header || !/^Digest /i.test(header)) {
|
||||
challenge(reply);
|
||||
return false;
|
||||
}
|
||||
|
||||
const p = parseDigest(header.replace(/^Digest /i, ""));
|
||||
// Nonce must be one we issued and not yet consumed (single-use).
|
||||
const issuedAt = p.nonce ? issuedNonces.get(p.nonce) : undefined;
|
||||
if (!p.nonce || issuedAt === undefined || Date.now() - issuedAt > NONCE_TTL_MS) {
|
||||
challenge(reply, true);
|
||||
return false;
|
||||
}
|
||||
|
||||
const ha1 = md5(`${creds.user}:${DIGEST_REALM}:${creds.password}`);
|
||||
const ha2 = md5(`${req.method}:${p.uri ?? req.url}`);
|
||||
const expected =
|
||||
p.qop === "auth"
|
||||
? md5(`${ha1}:${p.nonce}:${p.nc}:${p.cnonce}:${p.qop}:${ha2}`)
|
||||
: md5(`${ha1}:${p.nonce}:${ha2}`);
|
||||
|
||||
if (!p.response || !eq(expected, p.response) || !eq(p.username ?? "", creds.user)) {
|
||||
challenge(reply);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Consume the nonce so it can't be replayed.
|
||||
issuedNonces.delete(p.nonce);
|
||||
return true;
|
||||
}
|
||||
|
||||
function challenge(reply: FastifyReply, stale = false): void {
|
||||
const nonce = issueNonce();
|
||||
reply.header(
|
||||
"www-authenticate",
|
||||
`Digest realm="${DIGEST_REALM}", qop="auth", nonce="${nonce}", algorithm=MD5${stale ? ", stale=true" : ""}`,
|
||||
);
|
||||
reply.code(401).send("authentication required");
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { sessions, type Db, type DeviceRow } from "@parking/db";
|
||||
import {
|
||||
NoPrinterAvailableError,
|
||||
printWithFailover,
|
||||
registry,
|
||||
type AccessControlDevice,
|
||||
type PrinterDevice,
|
||||
type PrinterInstance,
|
||||
type TicketData,
|
||||
} from "@parking/devices";
|
||||
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 { snapshotAsync } from "./snapshot.js";
|
||||
|
||||
// The transient ENTRY flow: a button press → print a ticket → sign a vehicle_entry
|
||||
// → open the barrier. The button is wired into an access controller's input; the
|
||||
// admin maps that input terminal to a relay (config.relays[].button), so a press
|
||||
// resolves to exactly the entry relay it should open. See entry-exit-points.md.
|
||||
//
|
||||
// Two invariants from the threat model + safety analysis:
|
||||
// 1. SIGNED BEFORE OPEN — the vehicle_entry is appended to the signed ledger
|
||||
// BEFORE pulseOpen fires; an open with no matching signed event is the fraud
|
||||
// signal (wiki/concepts/append-only-event-chain.md).
|
||||
// 2. HOLD ON PRINT FAILURE — a transient with no ticket can't pay on exit, so if
|
||||
// all printers are down we do NOT open. We sign an `anomaly` (attempt, ticket
|
||||
// unprinted) and leave the barrier closed; the operator handles the held car.
|
||||
// Crucially, NO vehicle_entry is written in that case — we never record an
|
||||
// "entered" event for a car that didn't get in (decision 2026-06-15).
|
||||
//
|
||||
// Ordering: print → (ok) sign vehicle_entry → pulseOpen → snapshot → cache session.
|
||||
// (fail) sign anomaly, stop.
|
||||
|
||||
export class EntryFlow {
|
||||
readonly #db: Db;
|
||||
readonly #log: EventLog;
|
||||
readonly #logger: FastifyBaseLogger;
|
||||
/** Guard against double-fire from the same physical press (on edge only). */
|
||||
readonly #inFlight = new Set<string>();
|
||||
|
||||
constructor(db: Db, log: EventLog, logger: FastifyBaseLogger) {
|
||||
this.#db = db;
|
||||
this.#log = log;
|
||||
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. */
|
||||
async onInput(e: DeviceInputEvent): Promise<void> {
|
||||
if (e.edge !== "on") return; // 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
|
||||
// (reader/printer edge, exit-only relay's input) is not a transient-entry trigger.
|
||||
const resolved = relayForButton(this.#db, e.deviceId, e.input);
|
||||
if (!resolved) return;
|
||||
|
||||
const key = `${e.deviceId}:${e.input}`;
|
||||
if (this.#inFlight.has(key)) return; // ignore re-fire while one is processing
|
||||
this.#inFlight.add(key);
|
||||
try {
|
||||
await this.#runEntry(resolved);
|
||||
} catch (err) {
|
||||
this.#logger.error(`entry-flow failed: ${(err as Error).message}`);
|
||||
} finally {
|
||||
this.#inFlight.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
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. Permit holders are NOT
|
||||
// gated here (their flow ignores site-full; their own maxConcurrent applies), so
|
||||
// subscribers aren't locked out. "Full" is a soft policy seam for valet over-
|
||||
// capacity later. See wiki/concepts/capacity-occupancy.md.
|
||||
const occ = getOccupancy(this.#db);
|
||||
if (occ.full) {
|
||||
await this.#log.append({
|
||||
type: "anomaly",
|
||||
payload: { reason: `transient entry refused — lot full (${occ.count}/${occ.capacity})`, entryRefused: true, full: true },
|
||||
});
|
||||
this.#logger.warn(`transient entry REFUSED: full (${occ.count}/${occ.capacity})`);
|
||||
return;
|
||||
}
|
||||
|
||||
const ticketId = newTicketId();
|
||||
const issuedAt = new Date().toISOString();
|
||||
const printers = this.#loadPrinters();
|
||||
|
||||
// 1. PRINT FIRST. The ticket is the transient's session key — no ticket, no entry.
|
||||
const ticket: TicketData = { ticketId, issuedAt };
|
||||
try {
|
||||
const printedBy = await printWithFailover(printers, "entry-dispenser", (d: PrinterDevice) =>
|
||||
d.printTicket(ticket),
|
||||
);
|
||||
this.#logger.info(`entry ticket ${ticketId} printed on ${printedBy}`);
|
||||
} 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.
|
||||
const reason =
|
||||
err instanceof NoPrinterAvailableError ? err.message : (err as Error).message;
|
||||
await this.#log.append({
|
||||
type: "anomaly",
|
||||
identity: ticketId,
|
||||
payload: { reason: `entry held — ticket not printed: ${reason}`, ticketPrinted: false },
|
||||
});
|
||||
this.#logger.warn(`entry HELD: ${reason} (barrier NOT opened)`);
|
||||
return;
|
||||
}
|
||||
|
||||
// 2. SIGN the vehicle_entry — BEFORE the relay fires (the core invariant).
|
||||
await this.#log.append({
|
||||
type: "vehicle_entry",
|
||||
direction: "entry",
|
||||
source: "ticket",
|
||||
identity: ticketId,
|
||||
payload: { sessionRef: ticketId, ticketPrinted: true },
|
||||
occurredAt: issuedAt,
|
||||
});
|
||||
|
||||
// 3. OPEN the resolved entry barrier (intent only; the barrier owns the close).
|
||||
const access = this.#buildAccess(resolved.controller);
|
||||
if (access) await access.pulseOpen(resolved.relay);
|
||||
else this.#logger.warn(`entry signed for ${ticketId} but the entry relay won't build`);
|
||||
|
||||
// 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}`));
|
||||
|
||||
// 4. Update the session projection cache (rebuildable from the ledger; this is
|
||||
// just a fast read-model, never the source of truth).
|
||||
try {
|
||||
this.#db
|
||||
.insert(sessions)
|
||||
.values({ id: ticketId, identity: ticketId, source: "ticket", enteredAt: issuedAt, state: "open" })
|
||||
.run();
|
||||
} catch (err) {
|
||||
// Cache miss is non-fatal — the ledger is authoritative and the projection
|
||||
// can be rebuilt. Log it; don't fail the (already-open) entry.
|
||||
this.#logger.error(`session-cache insert failed for ${ticketId}: ${(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);
|
||||
if (!driver) return null;
|
||||
try {
|
||||
return driver.create(row.config as never) as AccessControlDevice;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Build live ENTRY printer instances (for failover selection). */
|
||||
#loadPrinters(): PrinterInstance[] {
|
||||
const rows = devicesByDirection(this.#db, "printer", "entry"); // already enabled-filtered
|
||||
const out: PrinterInstance[] = [];
|
||||
for (const row of rows) {
|
||||
const driver = registry.get(row.driverId);
|
||||
if (!driver) continue;
|
||||
const cfg = row.config as Record<string, unknown>;
|
||||
const role = cfg.role === "booth-receipt" ? "booth-receipt" : "entry-dispenser";
|
||||
try {
|
||||
out.push({
|
||||
id: row.id,
|
||||
role,
|
||||
failoverRank: typeof cfg.failoverRank === "number" ? cfg.failoverRank : 0,
|
||||
device: driver.create(cfg as never) as PrinterDevice,
|
||||
});
|
||||
} catch {
|
||||
// skip a printer whose config won't build
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
/** Opaque, unguessable transient ticket id (wiki/concepts/ticket-encoding.md). */
|
||||
function newTicketId(): string {
|
||||
return `T-${randomUUID()}`;
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { desc, ledgerEvents, type Db, type LedgerEventRow } from "@parking/db";
|
||||
import type { Direction, IdentitySource, LedgerEventType, LedgerPayload, Signer } from "@parking/shared";
|
||||
|
||||
// The append-only, hash-chained, signed event log — the system's core anti-fraud
|
||||
// primitive (see wiki/concepts/append-only-event-chain.md). Entry/exit and device
|
||||
// events are NEVER edited or deleted; a correction/void is a new appended row.
|
||||
//
|
||||
// Integrity rules enforced here:
|
||||
// - monotonic `index` (prev + 1; the unique constraint is the backstop),
|
||||
// - `prevHash` = hash of the previous row's canonical form (genesis = null),
|
||||
// - `signature` = signer.sign(canonical) over a STABLE field ordering,
|
||||
// - appends are SERIALIZED: read-prev -> compute-hash -> insert must not
|
||||
// interleave, or two events could claim the same index / chain off a stale
|
||||
// prev. SQLite is single-writer, but the read+compute+insert is multi-step,
|
||||
// so we guard it with an in-process async lock as well.
|
||||
|
||||
export interface AppendInput {
|
||||
readonly type: LedgerEventType;
|
||||
readonly direction?: Direction | null;
|
||||
readonly source?: IdentitySource | null;
|
||||
readonly identity?: string | null;
|
||||
/** Type-specific business data (amount, tariffVersionId, sessionRef…). Signed. */
|
||||
readonly payload?: LedgerPayload | null;
|
||||
/** Event time (ISO-8601). Defaults to now. */
|
||||
readonly occurredAt?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Canonical serialization of an event's signed/hashed content. Order is FIXED
|
||||
* and explicit — the hash chain and signatures depend on byte-stable output, so
|
||||
* this must never change for already-written events (versioned via keyId if it
|
||||
* ever must). The volatile DB row id is deliberately excluded; identity in the
|
||||
* chain is `index` + content.
|
||||
*/
|
||||
export function canonicalize(e: {
|
||||
index: number;
|
||||
type: string;
|
||||
direction: string | null;
|
||||
source: string | null;
|
||||
identity: string | null;
|
||||
payload: Record<string, unknown> | null;
|
||||
occurredAt: string;
|
||||
prevHash: string | null;
|
||||
}): string {
|
||||
return JSON.stringify([
|
||||
e.index,
|
||||
e.type,
|
||||
e.direction ?? null,
|
||||
e.source ?? null,
|
||||
e.identity ?? null,
|
||||
// Payload is part of the signed form so business data is tamper-evident.
|
||||
// Serialize with sorted keys for byte-stability (object key order must not
|
||||
// change a signature). null when the event type carries no payload.
|
||||
canonicalPayload(e.payload),
|
||||
e.occurredAt,
|
||||
e.prevHash ?? null,
|
||||
]);
|
||||
}
|
||||
|
||||
/** Deterministic (key-sorted, recursive) JSON for the payload slot. */
|
||||
function canonicalPayload(p: Record<string, unknown> | null | undefined): unknown {
|
||||
if (p == null) return null;
|
||||
const sort = (v: unknown): unknown => {
|
||||
if (Array.isArray(v)) return v.map(sort);
|
||||
if (v && typeof v === "object") {
|
||||
return Object.keys(v as Record<string, unknown>)
|
||||
.sort()
|
||||
.reduce<Record<string, unknown>>((o, k) => {
|
||||
o[k] = sort((v as Record<string, unknown>)[k]);
|
||||
return o;
|
||||
}, {});
|
||||
}
|
||||
return v;
|
||||
};
|
||||
return sort(p);
|
||||
}
|
||||
|
||||
/** SHA-256 of an event's canonical form (hex) — what the NEXT event chains to. */
|
||||
export function hashEvent(canonical: string): string {
|
||||
return createHash("sha256").update(canonical, "utf8").digest("hex");
|
||||
}
|
||||
|
||||
export class EventLog {
|
||||
readonly #db: Db;
|
||||
readonly #signer: Signer;
|
||||
/** Serialize appends: each waits for the previous to finish. */
|
||||
#tail: Promise<unknown> = Promise.resolve();
|
||||
|
||||
constructor(db: Db, signer: Signer) {
|
||||
this.#db = db;
|
||||
this.#signer = signer;
|
||||
}
|
||||
|
||||
/** Append one event to the chain. Returns the persisted row. Serialized. */
|
||||
append(input: AppendInput): Promise<LedgerEventRow> {
|
||||
const run = this.#tail.then(() => this.#appendNow(input));
|
||||
// Keep the chain going even if one append rejects (don't wedge the lock).
|
||||
this.#tail = run.catch(() => undefined);
|
||||
return run;
|
||||
}
|
||||
|
||||
#appendNow(input: AppendInput): LedgerEventRow {
|
||||
const prev = this.#db
|
||||
.select()
|
||||
.from(ledgerEvents)
|
||||
.orderBy(desc(ledgerEvents.index))
|
||||
.limit(1)
|
||||
.get();
|
||||
|
||||
const index = (prev?.index ?? 0) + 1;
|
||||
const prevHash = prev ? hashEvent(canonicalize(prev)) : null;
|
||||
const occurredAt = input.occurredAt ?? new Date().toISOString();
|
||||
const payload = input.payload ?? null;
|
||||
|
||||
const canonical = canonicalize({
|
||||
index,
|
||||
type: input.type,
|
||||
direction: input.direction ?? null,
|
||||
source: input.source ?? null,
|
||||
identity: input.identity ?? null,
|
||||
payload,
|
||||
occurredAt,
|
||||
prevHash,
|
||||
});
|
||||
|
||||
const row = {
|
||||
id: randomUUID(),
|
||||
index,
|
||||
type: input.type,
|
||||
direction: input.direction ?? null,
|
||||
source: input.source ?? null,
|
||||
identity: input.identity ?? null,
|
||||
payload,
|
||||
occurredAt,
|
||||
prevHash,
|
||||
signature: this.#signer.sign(canonical),
|
||||
keyId: this.#signer.keyId,
|
||||
};
|
||||
|
||||
this.#db.insert(ledgerEvents).values(row).run();
|
||||
return row as LedgerEventRow;
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk the chain oldest→newest and recompute hashes + signatures. Returns the
|
||||
* first detected break, or { ok: true }. This is what reconciliation and an
|
||||
* integrity self-check call. Catches: tampered content, reordering, a deleted
|
||||
* row (index gap), and a forged/invalid signature.
|
||||
*/
|
||||
verifyChain(): { ok: true } | { ok: false; index: number; reason: string } {
|
||||
const rows = this.#db.select().from(ledgerEvents).orderBy(ledgerEvents.index).all();
|
||||
let expectedIndex = 1;
|
||||
let prevHash: string | null = null;
|
||||
for (const row of rows) {
|
||||
if (row.index !== expectedIndex) {
|
||||
return { ok: false, index: row.index, reason: `index gap: expected ${expectedIndex}` };
|
||||
}
|
||||
if ((row.prevHash ?? null) !== prevHash) {
|
||||
return { ok: false, index: row.index, reason: "prevHash does not match chain" };
|
||||
}
|
||||
const canonical = canonicalize(row);
|
||||
if (!this.#signer.verify(canonical, row.signature)) {
|
||||
return { ok: false, index: row.index, reason: "signature invalid (content tampered or wrong key)" };
|
||||
}
|
||||
prevHash = hashEvent(canonical);
|
||||
expectedIndex += 1;
|
||||
}
|
||||
return { ok: true };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
import { eq, ledgerEvents, sessions, type Db, type DeviceRow } from "@parking/db";
|
||||
import { registry, type AccessControlDevice } from "@parking/devices";
|
||||
import type { ResolvedRelay } from "./device-resolve.js";
|
||||
import { snapshotAsync } from "./snapshot.js";
|
||||
import type { LedgerPayload } from "@parking/shared";
|
||||
import type { FastifyBaseLogger } from "fastify";
|
||||
import type { DeviceReadEvent, ReadOutcome } from "./device-events.js";
|
||||
import type { EventLog } from "./event-log.js";
|
||||
|
||||
// The EXIT flow (pay-on-foot model): a credential read at the exit lane → look up
|
||||
// the session → validate it is PAID and within the walk-back grace → sign a
|
||||
// vehicle_exit → open. Payment is decoupled from exit (it happens earlier at the
|
||||
// pay station); the exit lane only VALIDATES. See wiki/concepts/parking-session.md.
|
||||
//
|
||||
// Validation is a fold over the SIGNED ledger (the authoritative record), not the
|
||||
// projection cache: find the open vehicle_entry for this identity, then a covering
|
||||
// payment within grace. The cache is updated after, for fast reads.
|
||||
//
|
||||
// REJECT (barrier stays closed) when unpaid / over grace — this is correct business
|
||||
// logic, NOT a fail-state. "Exit fails OPEN" (fail-state-safety) is about the SYSTEM
|
||||
// being unable to decide (power/host loss), not about an unpaid car; an unpaid driver
|
||||
// is sent back to the pay station, the rejection is logged.
|
||||
//
|
||||
// NOTE: payments / the pay station don't exist yet, so no session is ever PAID — every
|
||||
// transient exit currently REJECTS (logged). That's the correct end-state; it becomes
|
||||
// passable once the pay-station + `payment` events land.
|
||||
|
||||
interface SessionView {
|
||||
readonly identity: string;
|
||||
readonly enteredAt: string;
|
||||
readonly open: boolean; // no vehicle_exit yet
|
||||
readonly paidAt: string | null; // latest payment time, if any
|
||||
readonly graceExitMin: number | null; // from the payment's tariff context, if known
|
||||
}
|
||||
|
||||
export class ExitFlow {
|
||||
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;
|
||||
}
|
||||
|
||||
/** Handle a transient-ticket read at an exit barrier (the relay pre-resolved by the
|
||||
* read dispatcher from the reader's binding, which has ruled out a permit match). */
|
||||
async handleAt(resolved: ResolvedRelay, e: DeviceReadEvent): Promise<ReadOutcome> {
|
||||
const key = `${e.deviceId}:${e.value}`;
|
||||
if (this.#inFlight.has(key)) return { accepted: false, reason: "duplicate read in flight" };
|
||||
this.#inFlight.add(key);
|
||||
try {
|
||||
return await this.#runExit(resolved, e);
|
||||
} catch (err) {
|
||||
this.#logger.error(`exit-flow failed: ${(err as Error).message}`);
|
||||
return { accepted: false, reason: (err as Error).message };
|
||||
} finally {
|
||||
this.#inFlight.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
async #runExit(resolved: ResolvedRelay, e: DeviceReadEvent): Promise<ReadOutcome> {
|
||||
const view = this.#sessionFor(e.value);
|
||||
|
||||
// No matching open session — unknown/duplicate ticket. Reject + log.
|
||||
if (!view || !view.open) {
|
||||
const reason = view ? "exit refused — session already closed" : "exit refused — no open session for credential";
|
||||
await this.#log.append({
|
||||
type: "anomaly",
|
||||
identity: e.value,
|
||||
payload: { reason, exitRefused: true },
|
||||
});
|
||||
this.#logger.warn(`exit refused: no open session for ${e.value}`);
|
||||
return { accepted: false, direction: "exit", reason };
|
||||
}
|
||||
|
||||
// PAID + within walk-back grace?
|
||||
const paid = view.paidAt != null;
|
||||
const withinGrace =
|
||||
paid &&
|
||||
view.graceExitMin != null &&
|
||||
Date.now() - Date.parse(view.paidAt!) <= view.graceExitMin * 60_000;
|
||||
|
||||
if (!paid || !withinGrace) {
|
||||
const reason = !paid
|
||||
? "exit refused — not paid (pay at the station)"
|
||||
: "exit refused — walk-back grace expired (top-up required)";
|
||||
await this.#log.append({
|
||||
type: "anomaly",
|
||||
identity: e.value,
|
||||
payload: { reason, exitRefused: true, sessionRef: e.value },
|
||||
});
|
||||
this.#logger.warn(`exit refused (${e.value}): ${reason}`);
|
||||
return { accepted: false, direction: "exit", reason };
|
||||
}
|
||||
|
||||
// Valid: sign the exit BEFORE opening, then open, then update the cache.
|
||||
await this.#log.append({
|
||||
type: "vehicle_exit",
|
||||
direction: "exit",
|
||||
source: e.kind === "plate" ? "lpr" : "ticket",
|
||||
identity: e.value,
|
||||
payload: { sessionRef: e.value },
|
||||
});
|
||||
|
||||
const access = this.#buildAccess(resolved.controller);
|
||||
if (access) await access.pulseOpen(resolved.relay);
|
||||
else this.#logger.warn(`exit signed for ${e.value} but the exit relay won't build`);
|
||||
|
||||
// SNAPSHOT — fire the exit camera(s), never awaited (evidence, not a gate).
|
||||
void snapshotAsync({
|
||||
db: this.#db,
|
||||
direction: "exit",
|
||||
identity: e.value,
|
||||
logger: this.#logger,
|
||||
}).catch((err) => this.#logger.error(`exit snapshot error: ${(err as Error).message}`));
|
||||
|
||||
try {
|
||||
this.#db
|
||||
.update(sessions)
|
||||
.set({ exitedAt: new Date().toISOString(), state: "closed" })
|
||||
.where(eq(sessions.id, e.value))
|
||||
.run();
|
||||
} catch (err) {
|
||||
this.#logger.error(`session-cache close failed for ${e.value}: ${(err as Error).message}`);
|
||||
}
|
||||
return { accepted: true, direction: "exit" };
|
||||
}
|
||||
|
||||
/** Fold the signed ledger into a session view for one identity (authoritative). */
|
||||
#sessionFor(identity: string): SessionView | null {
|
||||
const rows = this.#db
|
||||
.select()
|
||||
.from(ledgerEvents)
|
||||
.where(eq(ledgerEvents.identity, identity))
|
||||
.orderBy(ledgerEvents.index)
|
||||
.all();
|
||||
if (rows.length === 0) return null;
|
||||
|
||||
const entry = rows.find((r) => r.type === "vehicle_entry");
|
||||
if (!entry) return null;
|
||||
const exited = rows.some((r) => r.type === "vehicle_exit");
|
||||
|
||||
let paidAt: string | null = null;
|
||||
let graceExitMin: number | null = null;
|
||||
for (const r of rows) {
|
||||
if (r.type === "payment") {
|
||||
paidAt = r.occurredAt;
|
||||
const p = (r.payload ?? {}) as LedgerPayload & { graceExitMin?: number };
|
||||
if (typeof p.graceExitMin === "number") graceExitMin = p.graceExitMin;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
identity,
|
||||
enteredAt: entry.occurredAt,
|
||||
open: !exited,
|
||||
paidAt,
|
||||
graceExitMin,
|
||||
};
|
||||
}
|
||||
|
||||
/** Build a live access adapter from a resolved controller row, or null. */
|
||||
#buildAccess(row: DeviceRow): AccessControlDevice | null {
|
||||
const driver = registry.get(row.driverId);
|
||||
if (!driver) return null;
|
||||
try {
|
||||
return driver.create(row.config as never) as AccessControlDevice;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { networkInterfaces } from "node:os";
|
||||
|
||||
// Figure out which local IP a device should call back on. For input-push, the
|
||||
// device needs OUR address on ITS subnet — pick the local IPv4 interface whose
|
||||
// network contains the device's IP. Override with BACKEND_HOST_IP if the
|
||||
// auto-pick is wrong (e.g. multi-homed host). See wiki/concepts/device-input-flow.md.
|
||||
|
||||
export function backendIpForDevice(deviceHost: string): string | null {
|
||||
if (process.env.BACKEND_HOST_IP) return process.env.BACKEND_HOST_IP;
|
||||
|
||||
const ip = deviceHost.split(".").map(Number);
|
||||
if (ip.length !== 4 || ip.some((o) => Number.isNaN(o))) return null;
|
||||
|
||||
for (const ifaces of Object.values(networkInterfaces())) {
|
||||
for (const i of ifaces ?? []) {
|
||||
if (i.family !== "IPv4" || i.internal) continue;
|
||||
const addr = i.address.split(".").map(Number);
|
||||
const mask = i.netmask.split(".").map(Number);
|
||||
if (addr.length !== 4 || mask.length !== 4) continue;
|
||||
const sameNet = ip.every((o, k) => (o & mask[k]!) === (addr[k]! & mask[k]!));
|
||||
if (sameNet) return i.address;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Backend port the device should call (the server's listen port). */
|
||||
export function backendPort(): number {
|
||||
return Number(process.env.PORT ?? 3000);
|
||||
}
|
||||
|
||||
export interface BackendIpCandidate {
|
||||
ip: string;
|
||||
iface: string;
|
||||
/** True if this interface's subnet contains the device IP (the likely one). */
|
||||
onDeviceSubnet: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* List local IPv4 addresses the device could call back on, with the ones on the
|
||||
* device's own subnet flagged + sorted first. Lets the admin see/override the
|
||||
* auto-pick (important on multi-NIC hosts). BACKEND_HOST_IP, if set, is the only
|
||||
* candidate (the deterministic override).
|
||||
*/
|
||||
export function backendIpCandidates(deviceHost: string): BackendIpCandidate[] {
|
||||
if (process.env.BACKEND_HOST_IP) {
|
||||
return [{ ip: process.env.BACKEND_HOST_IP, iface: "BACKEND_HOST_IP", onDeviceSubnet: true }];
|
||||
}
|
||||
|
||||
const dev = deviceHost.split(".").map(Number);
|
||||
const validDev = dev.length === 4 && !dev.some((o) => Number.isNaN(o));
|
||||
const out: BackendIpCandidate[] = [];
|
||||
|
||||
for (const [iface, ifaces] of Object.entries(networkInterfaces())) {
|
||||
for (const i of ifaces ?? []) {
|
||||
if (i.family !== "IPv4" || i.internal) continue;
|
||||
const addr = i.address.split(".").map(Number);
|
||||
const mask = i.netmask.split(".").map(Number);
|
||||
const onDeviceSubnet =
|
||||
validDev &&
|
||||
addr.length === 4 &&
|
||||
mask.length === 4 &&
|
||||
dev.every((o, k) => (o & mask[k]!) === (addr[k]! & mask[k]!));
|
||||
out.push({ ip: i.address, iface, onDeviceSubnet });
|
||||
}
|
||||
}
|
||||
// On-subnet candidates first.
|
||||
return out.sort((a, b) => Number(b.onDeviceSubnet) - Number(a.onDeviceSubnet));
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { eq, ledgerEvents, siteConfig, type Db } from "@parking/db";
|
||||
|
||||
// Occupancy = a FOLD over the signed ledger: the count of vehicle_entry events
|
||||
// with no matching vehicle_exit. Never a hand-maintained counter (which is
|
||||
// editable + drifts) — the chain is the truth. See wiki/concepts/capacity-occupancy.md.
|
||||
|
||||
export interface Occupancy {
|
||||
/** Cars currently inside (open sessions). */
|
||||
readonly count: number;
|
||||
/** Admin-set nominal capacity, or null = no limit. */
|
||||
readonly capacity: number | null;
|
||||
/** capacity − count, or null when uncapped. Can read 0 (or below) when full. */
|
||||
readonly free: number | null;
|
||||
/** True when count ≥ capacity (always false when uncapped). */
|
||||
readonly full: boolean;
|
||||
}
|
||||
|
||||
/** Count cars inside: entries minus exits, per identity, over the ledger. */
|
||||
export function occupancyCount(db: Db): number {
|
||||
const rows = db
|
||||
.select({ type: ledgerEvents.type, identity: ledgerEvents.identity })
|
||||
.from(ledgerEvents)
|
||||
.all();
|
||||
const balance = new Map<string, number>();
|
||||
for (const r of rows) {
|
||||
if (r.type === "vehicle_entry") balance.set(r.identity ?? "", (balance.get(r.identity ?? "") ?? 0) + 1);
|
||||
else if (r.type === "vehicle_exit") balance.set(r.identity ?? "", (balance.get(r.identity ?? "") ?? 0) - 1);
|
||||
}
|
||||
let open = 0;
|
||||
for (const v of balance.values()) if (v > 0) open += 1;
|
||||
return open;
|
||||
}
|
||||
|
||||
/** Admin-set capacity (null = uncapped). */
|
||||
export function siteCapacity(db: Db): number | null {
|
||||
const row = db.select().from(siteConfig).where(eq(siteConfig.id, 1)).get();
|
||||
return row?.capacity ?? null;
|
||||
}
|
||||
|
||||
export function getOccupancy(db: Db): Occupancy {
|
||||
const count = occupancyCount(db);
|
||||
const capacity = siteCapacity(db);
|
||||
return {
|
||||
count,
|
||||
capacity,
|
||||
free: capacity == null ? null : capacity - count,
|
||||
full: capacity != null && count >= capacity,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import { desc, eq, ledgerEvents, sessions, tariffVersions, tariffs, type Db } from "@parking/db";
|
||||
import { computeFee, type TariffStructure, type Tender } from "@parking/shared";
|
||||
import type { FastifyBaseLogger } from "fastify";
|
||||
import type { EventLog } from "./event-log.js";
|
||||
|
||||
// The PAY STATION: a customer pays for an open session BEFORE walking back to the
|
||||
// car (pay-on-foot — payment is decoupled from exit). Two steps:
|
||||
// 1. quote(identity) → look up the open session, price it against the tariff in
|
||||
// force at entry, return the amount due (no side effect).
|
||||
// 2. pay(identity, tender) → re-price, append a SIGNED `payment` event carrying
|
||||
// the amount, currency, tender, tariffVersionId, and graceExitMin (so the exit
|
||||
// flow can validate paid + within walk-back grace). Payment is a signed ledger
|
||||
// event, never a mutable "paid" flag — an operator can't forge or delete it.
|
||||
// See wiki/concepts/tariff.md, parking-session.md.
|
||||
|
||||
export class NoOpenSessionError extends Error {
|
||||
constructor(identity: string) {
|
||||
super(`no open session for ${identity}`);
|
||||
this.name = "NoOpenSessionError";
|
||||
}
|
||||
}
|
||||
export class NoTariffError extends Error {
|
||||
constructor() {
|
||||
super("no active tariff configured");
|
||||
this.name = "NoTariffError";
|
||||
}
|
||||
}
|
||||
|
||||
export interface Quote {
|
||||
readonly identity: string;
|
||||
readonly enteredAt: string;
|
||||
readonly amountMinor: number;
|
||||
readonly currency: string;
|
||||
readonly tariffVersionId: string;
|
||||
readonly graceExitMin: number;
|
||||
}
|
||||
|
||||
export class PayStation {
|
||||
readonly #db: Db;
|
||||
readonly #log: EventLog;
|
||||
readonly #logger: FastifyBaseLogger;
|
||||
|
||||
constructor(db: Db, log: EventLog, logger: FastifyBaseLogger) {
|
||||
this.#db = db;
|
||||
this.#log = log;
|
||||
this.#logger = logger;
|
||||
}
|
||||
|
||||
/** Price an open session against the tariff in force at its entry. No side effect. */
|
||||
quote(identity: string): Quote {
|
||||
const entry = this.#openEntry(identity);
|
||||
if (!entry) throw new NoOpenSessionError(identity);
|
||||
|
||||
const tv = this.#tariffVersionFor(entry.occurredAt);
|
||||
if (!tv) throw new NoTariffError();
|
||||
const structure = tv.structure as unknown as TariffStructure;
|
||||
|
||||
const amountMinor = computeFee(entry.occurredAt, new Date().toISOString(), structure);
|
||||
return {
|
||||
identity,
|
||||
enteredAt: entry.occurredAt,
|
||||
amountMinor,
|
||||
currency: tv.currency,
|
||||
tariffVersionId: tv.id,
|
||||
graceExitMin: structure.gracePeriodExitMin,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Take payment for a session and append the signed `payment` event. Re-quotes at
|
||||
* the moment of payment (the customer pays for time parked SO FAR). For an
|
||||
* overstay top-up the same call re-prices entry→now and the exit flow's
|
||||
* grace-window restarts from this payment. `overrideMinor` lets the operator set
|
||||
* an arbitrary amount (lost ticket / dispute) — recorded as the charged amount.
|
||||
*/
|
||||
async pay(
|
||||
identity: string,
|
||||
tender: Tender,
|
||||
overrideMinor?: number,
|
||||
): Promise<{ amountMinor: number; currency: string }> {
|
||||
const q = this.quote(identity);
|
||||
const amountMinor = overrideMinor ?? q.amountMinor;
|
||||
|
||||
await this.#log.append({
|
||||
type: "payment",
|
||||
source: "manual",
|
||||
identity,
|
||||
payload: {
|
||||
sessionRef: identity,
|
||||
amountMinor,
|
||||
currency: q.currency,
|
||||
tender,
|
||||
tariffVersionId: q.tariffVersionId,
|
||||
// The exit flow reads graceExitMin off the payment to validate the
|
||||
// walk-back window without re-resolving the tariff.
|
||||
graceExitMin: q.graceExitMin,
|
||||
...(overrideMinor != null ? { reason: "operator-set amount", quotedMinor: q.amountMinor } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
// Update the projection cache (rebuildable; not the source of truth).
|
||||
try {
|
||||
this.#db.update(sessions).set({ state: "paid" }).where(eq(sessions.id, identity)).run();
|
||||
} catch (err) {
|
||||
this.#logger.error(`session-cache mark-paid failed for ${identity}: ${(err as Error).message}`);
|
||||
}
|
||||
|
||||
this.#logger.info(`payment ${amountMinor} ${q.currency} (${tender}) for ${identity}`);
|
||||
return { amountMinor, currency: q.currency };
|
||||
}
|
||||
|
||||
/** The vehicle_entry of an OPEN session for this identity (no later exit), or null. */
|
||||
#openEntry(identity: string) {
|
||||
const rows = this.#db
|
||||
.select()
|
||||
.from(ledgerEvents)
|
||||
.where(eq(ledgerEvents.identity, identity))
|
||||
.orderBy(ledgerEvents.index)
|
||||
.all();
|
||||
const entry = rows.find((r) => r.type === "vehicle_entry");
|
||||
if (!entry) return null;
|
||||
if (rows.some((r) => r.type === "vehicle_exit")) return null; // already closed
|
||||
return entry;
|
||||
}
|
||||
|
||||
/** The tariff version in force at `at` — latest effectiveFrom ≤ at, for the
|
||||
* (single, for now) active site tariff. */
|
||||
#tariffVersionFor(at: string) {
|
||||
const tariff = this.#db.select().from(tariffs).where(eq(tariffs.scope, "site")).get();
|
||||
if (!tariff) return null;
|
||||
const versions = this.#db
|
||||
.select()
|
||||
.from(tariffVersions)
|
||||
.where(eq(tariffVersions.tariffId, tariff.id))
|
||||
.orderBy(desc(tariffVersions.effectiveFrom))
|
||||
.all();
|
||||
return versions.find((v) => v.effectiveFrom <= at) ?? null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
import { eq, ledgerEvents, permitCredentials, permitPlates, permits, sessions, type Db, type DeviceRow } from "@parking/db";
|
||||
import { registry, type AccessControlDevice } from "@parking/devices";
|
||||
import type { FastifyBaseLogger } from "fastify";
|
||||
import type { DeviceReadEvent, ReadOutcome } from "./device-events.js";
|
||||
import type { EventLog } from "./event-log.js";
|
||||
import { type FlowDirection, type ResolvedRelay } from "./device-resolve.js";
|
||||
import { snapshotAsync } from "./snapshot.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 barrier. `resolved` is the
|
||||
* reader's bound relay; its direction constrains, "both" defers to session state. */
|
||||
async run(resolved: ResolvedRelay, e: DeviceReadEvent, m: PermitMatch): Promise<ReadOutcome> {
|
||||
const key = `${m.permitId}:${m.carKey}`;
|
||||
if (this.#inFlight.has(key)) return { accepted: false, reason: "duplicate read in flight" };
|
||||
this.#inFlight.add(key);
|
||||
try {
|
||||
return await this.#run(resolved, e, m);
|
||||
} catch (err) {
|
||||
this.#logger.error(`permit-flow failed: ${(err as Error).message}`);
|
||||
return { accepted: false, reason: (err as Error).message };
|
||||
} finally {
|
||||
this.#inFlight.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
async #run(resolved: ResolvedRelay, e: DeviceReadEvent, m: PermitMatch): Promise<ReadOutcome> {
|
||||
const permit = this.#db.select().from(permits).where(eq(permits.id, m.permitId)).get();
|
||||
if (!permit) return { accepted: false, reason: "permit not found" };
|
||||
|
||||
// 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) {
|
||||
const reason = `permit ${permit.status}/out-of-window`;
|
||||
await this.#reject(m, reason);
|
||||
return { accepted: false, reason };
|
||||
}
|
||||
|
||||
// Direction: the car's open-session state is the natural verb (in→exit, out→entry).
|
||||
// The barrier the car is at (resolved.direction) must AGREE — a car at an exit
|
||||
// barrier that isn't inside (or at an entry barrier while already in) is a
|
||||
// wrong-barrier / anti-passback signal, refused + logged. A "both" barrier follows
|
||||
// the session state.
|
||||
const carOpen = this.#carHasOpenSession(m.carKey);
|
||||
const inferred: FlowDirection = carOpen ? "exit" : "entry";
|
||||
if (resolved.direction !== "both" && resolved.direction !== inferred) {
|
||||
const reason = `permit wrong barrier — ${resolved.direction} barrier but car would ${inferred}`;
|
||||
await this.#reject(m, reason);
|
||||
return { accepted: false, direction: resolved.direction === "exit" ? "exit" : "entry", reason };
|
||||
}
|
||||
|
||||
if (carOpen) {
|
||||
// EXIT: this car is already inside → the read is its exit.
|
||||
await this.#log.append({
|
||||
type: "vehicle_exit",
|
||||
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(resolved, "exit", m.carKey, "permit exit");
|
||||
this.#closeCache(m.carKey);
|
||||
return { accepted: true, direction: "exit" };
|
||||
}
|
||||
|
||||
// ENTRY: enforce the car-count binding (maxConcurrent), then sign + open.
|
||||
if (permit.maxConcurrent != null) {
|
||||
const open = this.#permitOpenCount(m.permitId);
|
||||
if (open >= permit.maxConcurrent) {
|
||||
const reason = `permit at capacity (${open}/${permit.maxConcurrent} cars in)`;
|
||||
await this.#reject(m, reason);
|
||||
return { accepted: false, direction: "entry", reason };
|
||||
}
|
||||
}
|
||||
|
||||
await this.#log.append({
|
||||
type: "vehicle_entry",
|
||||
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(resolved, "entry", m.carKey, "permit entry");
|
||||
try {
|
||||
this.#db
|
||||
.insert(sessions)
|
||||
.values({ id: m.carKey, 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}`);
|
||||
}
|
||||
return { accepted: true, direction: "entry" };
|
||||
}
|
||||
|
||||
/** 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(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(m: PermitMatch, reason: string): Promise<void> {
|
||||
await this.#log.append({
|
||||
type: "anomaly",
|
||||
identity: m.carKey,
|
||||
payload: { reason: `permit refused — ${reason}`, permitId: m.permitId, permitRefused: true },
|
||||
});
|
||||
this.#logger.warn(`permit refused (${m.carKey}): ${reason}`);
|
||||
}
|
||||
|
||||
async #open(resolved: ResolvedRelay, dir: FlowDirection, carKey: string, what: string): Promise<void> {
|
||||
const access = this.#buildAccess(resolved.controller);
|
||||
if (access) await access.pulseOpen(resolved.relay);
|
||||
else this.#logger.warn(`${what} signed for ${carKey} but the ${dir} relay won't build`);
|
||||
|
||||
// SNAPSHOT — fire the directional camera(s), never awaited (evidence, not a gate).
|
||||
void snapshotAsync({
|
||||
db: this.#db,
|
||||
direction: dir,
|
||||
identity: carKey,
|
||||
logger: this.#logger,
|
||||
}).catch((err) => this.#logger.error(`permit snapshot error: ${(err as Error).message}`));
|
||||
}
|
||||
|
||||
#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}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Build a live access adapter from a resolved controller row, or null. */
|
||||
#buildAccess(row: DeviceRow): AccessControlDevice | null {
|
||||
const driver = registry.get(row.driverId);
|
||||
if (!driver) return null;
|
||||
try {
|
||||
return driver.create(row.config as never) as AccessControlDevice;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
import type { FastifyBaseLogger } from "fastify";
|
||||
import { eq, devices, type Db } from "@parking/db";
|
||||
import {
|
||||
isMonitorable,
|
||||
registry,
|
||||
type PrinterStatus,
|
||||
} from "@parking/devices";
|
||||
import { deviceEvents, type PrinterStatusEvent } from "./device-events.js";
|
||||
|
||||
// Live printer-status monitor. Polls every enabled printer that supports
|
||||
// readStatus() on an interval, caches the latest status in memory, and emits a
|
||||
// "printer-status" event on the device bus whenever a printer's status CHANGES
|
||||
// (so the UI/SSE stream and any future entry-flow logic react without polling
|
||||
// the device themselves). See wiki/concepts/printer-status-monitoring.md.
|
||||
//
|
||||
// The poll is the booth's early warning: it surfaces "paper out" / "cover open"
|
||||
// BEFORE a driver presses the entry button and no ticket prints. Reachability
|
||||
// failures degrade to status "offline" — the same signal as a dead printer.
|
||||
|
||||
const POLL_MS = Number(process.env.PRINTER_POLL_MS ?? 5000);
|
||||
|
||||
/** A cached entry: the last status plus the device's identity for the UI. */
|
||||
interface CachedStatus extends PrinterStatusEvent {}
|
||||
|
||||
export class PrinterMonitor {
|
||||
readonly #db: Db;
|
||||
readonly #log: FastifyBaseLogger;
|
||||
readonly #pollMs: number;
|
||||
/** Latest status per device id. */
|
||||
readonly #latest = new Map<string, CachedStatus>();
|
||||
/** Live adapter per device id (rebuilt when the set of printers changes). */
|
||||
readonly #devices = new Map<string, { build: () => ReturnType<typeof registry.create>; meta: Omit<PrinterStatusEvent, "status"> }>();
|
||||
#timer: ReturnType<typeof setInterval> | null = null;
|
||||
#ticking = false;
|
||||
|
||||
constructor(db: Db, log: FastifyBaseLogger, pollMs = POLL_MS) {
|
||||
this.#db = db;
|
||||
this.#log = log;
|
||||
this.#pollMs = pollMs;
|
||||
}
|
||||
|
||||
/** Begin polling. Idempotent. */
|
||||
start(): void {
|
||||
if (this.#timer) return;
|
||||
// Kick an immediate pass so status is populated without waiting a full cycle.
|
||||
void this.#tick();
|
||||
this.#timer = setInterval(() => void this.#tick(), this.#pollMs);
|
||||
// Don't keep the event loop alive solely for the monitor.
|
||||
this.#timer.unref?.();
|
||||
this.#log.info(`printer-monitor: polling every ${this.#pollMs}ms`);
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
if (this.#timer) {
|
||||
clearInterval(this.#timer);
|
||||
this.#timer = null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Current snapshot for the API. */
|
||||
snapshot(): CachedStatus[] {
|
||||
return [...this.#latest.values()];
|
||||
}
|
||||
|
||||
/** Reload the set of monitored printers from lane_devices (call after assign). */
|
||||
async refreshDevices(): Promise<void> {
|
||||
const rows = await this.#db
|
||||
.select()
|
||||
.from(devices)
|
||||
.where(eq(devices.category, "printer"))
|
||||
.all();
|
||||
|
||||
const seen = new Set<string>();
|
||||
for (const row of rows) {
|
||||
if (!row.enabled) continue;
|
||||
const driver = registry.get(row.driverId);
|
||||
if (!driver) continue;
|
||||
const cfg = row.config as Record<string, unknown>;
|
||||
// Probe-build once to check the driver yields a monitorable device.
|
||||
let monitorable: boolean;
|
||||
try {
|
||||
monitorable = isMonitorable(driver.create(cfg as never));
|
||||
} catch {
|
||||
monitorable = false;
|
||||
}
|
||||
if (!monitorable) continue;
|
||||
seen.add(row.id);
|
||||
this.#devices.set(row.id, {
|
||||
build: () => driver.create(cfg as never),
|
||||
meta: {
|
||||
deviceId: row.id,
|
||||
driverId: row.driverId,
|
||||
role: typeof cfg.role === "string" ? cfg.role : undefined,
|
||||
},
|
||||
});
|
||||
}
|
||||
// Drop devices that are no longer present/enabled.
|
||||
for (const id of [...this.#devices.keys()]) {
|
||||
if (!seen.has(id)) {
|
||||
this.#devices.delete(id);
|
||||
this.#latest.delete(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async #tick(): Promise<void> {
|
||||
if (this.#ticking) return; // never overlap polls
|
||||
this.#ticking = true;
|
||||
try {
|
||||
await this.refreshDevices();
|
||||
await Promise.all(
|
||||
[...this.#devices.entries()].map(([id, entry]) => this.#poll(id, entry)),
|
||||
);
|
||||
} catch (err) {
|
||||
this.#log.warn(`printer-monitor tick failed: ${(err as Error).message}`);
|
||||
} finally {
|
||||
this.#ticking = false;
|
||||
}
|
||||
}
|
||||
|
||||
async #poll(id: string, entry: { build: () => ReturnType<typeof registry.create>; meta: Omit<PrinterStatusEvent, "status"> }): Promise<void> {
|
||||
let status: PrinterStatus;
|
||||
try {
|
||||
const device = entry.build();
|
||||
if (!isMonitorable(device)) return;
|
||||
status = await device.readStatus();
|
||||
} catch (err) {
|
||||
status = {
|
||||
status: "offline",
|
||||
detail: (err as Error).message,
|
||||
checkedAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
const event: PrinterStatusEvent = { ...entry.meta, status };
|
||||
const prev = this.#latest.get(id);
|
||||
this.#latest.set(id, event);
|
||||
|
||||
if (!prev || statusChanged(prev.status, status)) {
|
||||
this.#log.info(
|
||||
`printer-monitor: ${entry.meta.role ?? "printer"} ${id} -> ${status.status}${status.detail ? ` (${status.detail})` : ""}`,
|
||||
);
|
||||
deviceEvents.emitPrinterStatus(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Did the operator-meaningful status change between two reads? */
|
||||
function statusChanged(a: PrinterStatus, b: PrinterStatus): boolean {
|
||||
return (
|
||||
a.status !== b.status ||
|
||||
a.paperEnd !== b.paperEnd ||
|
||||
a.paperNearEnd !== b.paperNearEnd ||
|
||||
a.coverOpen !== b.coverOpen ||
|
||||
a.cutterError !== b.cutterError ||
|
||||
a.offline !== b.offline
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { devices, 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 type { PermitFlow } from "./permit-flow.js";
|
||||
import { relayForDevice } from "./device-resolve.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,
|
||||
// - 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 (permit: session
|
||||
// state; transient: exit).
|
||||
|
||||
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<ReadOutcome> {
|
||||
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)" };
|
||||
}
|
||||
|
||||
const permit = this.#permit.match(e);
|
||||
if (permit) {
|
||||
return this.#permit.run(resolved, e, permit);
|
||||
}
|
||||
// Not a permit → 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);
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,6 @@ import bcrypt from "bcrypt";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { eq, users, type Db } from "@parking/db";
|
||||
import {
|
||||
TOKEN_TTL,
|
||||
clearAuthCookies,
|
||||
newCsrfToken,
|
||||
requireRole,
|
||||
@@ -34,10 +33,13 @@ export async function authRoutes(app: FastifyInstance, db: Db): Promise<void> {
|
||||
}
|
||||
|
||||
const csrf = newCsrfToken();
|
||||
const token = await reply.jwtSign(
|
||||
{ sub: user.id, username: user.username, role: user.role, csrf },
|
||||
{ expiresIn: TOKEN_TTL },
|
||||
);
|
||||
// No expiresIn: the token is valid until explicit logout (see auth.ts).
|
||||
const token = await reply.jwtSign({
|
||||
sub: user.id,
|
||||
username: user.username,
|
||||
role: user.role,
|
||||
csrf,
|
||||
});
|
||||
setAuthCookies(reply, token, csrf);
|
||||
return { id: user.id, username: user.username, role: user.role };
|
||||
});
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
|
||||
import { eq, devices, type Db } from "@parking/db";
|
||||
import { deviceEvents } from "../device-events.js";
|
||||
import { verifyDigest } from "../digest-auth.js";
|
||||
|
||||
// Inbound device push endpoints. The Dingtian board's "Input Link URL" feature
|
||||
// HTTP-calls us when an input (button) fires — no polling. We translate the
|
||||
// push into an internal device event; the entry flow decides what to do
|
||||
// (print a ticket, then command the relay). See wiki/concepts/device-input-flow.md.
|
||||
//
|
||||
// AUTH: HTTP Digest (the device can do Digest but not HTTPS-to-self-signed —
|
||||
// both tested on hardware). The password is never sent on the wire; the secret
|
||||
// is NOT in the URL. Per-device credentials live in lane_devices (written on
|
||||
// assign). This is defence-in-depth on a flat network; the signed event log is
|
||||
// the real anti-fraud guarantee (an open with no matching signed event is an
|
||||
// anomaly). Source-IP is also checked. NOT behind the SPA cookie/CSRF auth
|
||||
// (machine call from the device).
|
||||
|
||||
interface InputParams {
|
||||
deviceId: string;
|
||||
n: string;
|
||||
edge: string;
|
||||
}
|
||||
|
||||
interface DingtianDeviceConfig {
|
||||
host?: string;
|
||||
pushUser?: string;
|
||||
pushPassword?: string;
|
||||
}
|
||||
|
||||
function clientIp(req: FastifyRequest): string {
|
||||
return req.ip.replace(/^::ffff:/, "");
|
||||
}
|
||||
|
||||
export async function deviceRoutes(app: FastifyInstance, db: Db): Promise<void> {
|
||||
const handle = async (req: FastifyRequest<{ Params: InputParams }>, reply: FastifyReply) => {
|
||||
const { deviceId, n, edge } = req.params;
|
||||
|
||||
const row = await db.select().from(devices).where(eq(devices.id, deviceId)).get();
|
||||
const cfg = row?.config as DingtianDeviceConfig | undefined;
|
||||
|
||||
// Unknown device / not a dingtian / no push creds / wrong source IP → 404.
|
||||
if (
|
||||
!row ||
|
||||
row.driverId !== "dingtian" ||
|
||||
!cfg?.pushUser ||
|
||||
!cfg.pushPassword ||
|
||||
!cfg.host ||
|
||||
clientIp(req) !== cfg.host
|
||||
) {
|
||||
app.log.warn(`rejected device push: device=${deviceId} ip=${clientIp(req)}`);
|
||||
return reply.code(404).send({ error: "not found" });
|
||||
}
|
||||
|
||||
// Digest auth — issues a 401 challenge on first hit; the device retries with
|
||||
// the hashed response (verifyDigest sends the challenge + returns false).
|
||||
if (!verifyDigest(req, reply, { user: cfg.pushUser, password: cfg.pushPassword })) {
|
||||
return; // 401 already sent
|
||||
}
|
||||
|
||||
const input = Number(n);
|
||||
const ed = edge === "off" ? "off" : "on";
|
||||
app.log.info(`[dingtian:${deviceId}] input ${input} ${ed} (push)`);
|
||||
deviceEvents.emitInput({
|
||||
driverId: "dingtian",
|
||||
deviceId,
|
||||
input,
|
||||
edge: ed,
|
||||
at: new Date().toISOString(),
|
||||
source: "push",
|
||||
});
|
||||
return { ok: true };
|
||||
};
|
||||
|
||||
for (const method of ["GET", "POST"] as const) {
|
||||
app.route({
|
||||
method,
|
||||
url: "/api/devices/dingtian/:deviceId/input/:n/:edge",
|
||||
handler: handle,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { desc, ledgerEvents, type Db } from "@parking/db";
|
||||
import { requireRole } from "../auth.js";
|
||||
import type { EventLog } from "../event-log.js";
|
||||
|
||||
// Read access to the append-only signed event log. NO write/update/delete routes
|
||||
// exist by design — events are only ever appended internally (entry flow, device
|
||||
// pushes). Corrections are new appended events, never edits. See
|
||||
// wiki/concepts/append-only-event-chain.md.
|
||||
|
||||
export async function eventRoutes(
|
||||
app: FastifyInstance,
|
||||
db: Db,
|
||||
eventLog: EventLog,
|
||||
): Promise<void> {
|
||||
// Any authenticated role may read the log (it's the audit trail).
|
||||
const guard = requireRole("admin", "operator", "cashier", "readonly");
|
||||
|
||||
// Recent events, newest first. `limit` caps the page (default 100, max 1000).
|
||||
app.get<{ Querystring: { limit?: string } }>(
|
||||
"/api/events",
|
||||
{ preHandler: guard },
|
||||
async (req) => {
|
||||
const limit = Math.min(Math.max(Number(req.query.limit) || 100, 1), 1000);
|
||||
const rows = db.select().from(ledgerEvents).orderBy(desc(ledgerEvents.index)).limit(limit).all();
|
||||
return { events: rows };
|
||||
},
|
||||
);
|
||||
|
||||
// Integrity self-check: walk the chain and verify hashes + signatures. Admin-
|
||||
// only (it's an audit action). Returns the first break, or ok. This is what a
|
||||
// reconciliation job / "is the log intact?" check calls.
|
||||
app.get(
|
||||
"/api/events/verify",
|
||||
{ preHandler: requireRole("admin") },
|
||||
async () => eventLog.verifyChain(),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { requireRole } from "../auth.js";
|
||||
import {
|
||||
NoOpenSessionError,
|
||||
NoTariffError,
|
||||
type PayStation,
|
||||
} from "../pay-station.js";
|
||||
|
||||
// Pay-station endpoints (pay-on-foot). The terminal/operator UI quotes a session
|
||||
// then takes payment; the payment becomes a signed ledger event. PCI scope stays
|
||||
// OUT of the app — actual card capture is a standalone P2PE terminal; here `tender`
|
||||
// just records cash vs. card. See wiki/concepts/tariff.md, parking-session.md, bom.md.
|
||||
|
||||
interface QuoteQuery {
|
||||
identity: string;
|
||||
}
|
||||
interface PayBody {
|
||||
identity: string;
|
||||
tender: "cash" | "card";
|
||||
/** Operator-set amount (lost ticket / dispute) — overrides the computed fee. */
|
||||
overrideMinor?: number;
|
||||
}
|
||||
|
||||
export async function payRoutes(app: FastifyInstance, payStation: PayStation): Promise<void> {
|
||||
// Cashier/operator/admin operate the pay station; readonly may not.
|
||||
const guard = requireRole("admin", "operator", "cashier");
|
||||
|
||||
// Quote: what does this session owe right now? (No side effect.)
|
||||
app.get<{ Querystring: QuoteQuery }>(
|
||||
"/api/pay/quote",
|
||||
{ preHandler: guard },
|
||||
async (req, reply) => {
|
||||
const identity = (req.query.identity ?? "").trim();
|
||||
if (!identity) return reply.code(400).send({ error: "identity required" });
|
||||
try {
|
||||
return payStation.quote(identity);
|
||||
} catch (err) {
|
||||
return mapError(reply, err);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Pay: take payment and append the signed `payment` event.
|
||||
app.post<{ Body: PayBody }>(
|
||||
"/api/pay",
|
||||
{ preHandler: guard },
|
||||
async (req, reply) => {
|
||||
const { identity, tender, overrideMinor } = req.body ?? {};
|
||||
if (!identity || (tender !== "cash" && tender !== "card")) {
|
||||
return reply.code(400).send({ error: "identity and tender (cash|card) required" });
|
||||
}
|
||||
if (overrideMinor != null && (!Number.isInteger(overrideMinor) || overrideMinor < 0)) {
|
||||
return reply.code(400).send({ error: "overrideMinor must be a non-negative integer (minor units)" });
|
||||
}
|
||||
try {
|
||||
const res = await payStation.pay(identity, tender, overrideMinor);
|
||||
return reply.code(201).send(res);
|
||||
} catch (err) {
|
||||
return mapError(reply, err);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function mapError(reply: import("fastify").FastifyReply, err: unknown) {
|
||||
if (err instanceof NoOpenSessionError) return reply.code(404).send({ error: err.message });
|
||||
if (err instanceof NoTariffError) return reply.code(409).send({ error: err.message });
|
||||
return reply.code(500).send({ error: (err as Error).message });
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { eq, permitCredentials, permitPlates, permits, type Db } from "@parking/db";
|
||||
import { requireRole } from "../auth.js";
|
||||
|
||||
// Permit (subscription) admin CRUD. A permit is mutable master data — admins
|
||||
// grant/edit/revoke — but every USE of it is a signed ledger event, so the audit
|
||||
// trail stays append-only (see wiki/entities/permit.md). A permit is an aggregate:
|
||||
// the permit row + its credentials (card/QR) + its bound plates. The API treats them
|
||||
// as one unit (create/update replace the child sets; delete removes all).
|
||||
|
||||
interface Credential {
|
||||
kind: "rf" | "qr";
|
||||
value: string;
|
||||
}
|
||||
interface PermitBody {
|
||||
holderName?: string;
|
||||
contact?: string;
|
||||
/** Car-count binding: cars inside at once. Default 1; null = unbound. */
|
||||
maxConcurrent?: number | null;
|
||||
validFrom?: string | null;
|
||||
validTo?: string | null;
|
||||
status?: "active" | "suspended" | "revoked";
|
||||
credentials?: Credential[];
|
||||
/** Plate binding (optional): bound plates that also serve as identity. */
|
||||
plates?: string[];
|
||||
}
|
||||
|
||||
export async function permitRoutes(app: FastifyInstance, db: Db): Promise<void> {
|
||||
// Admin manages permits; operator/cashier/readonly may LIST (to look one up).
|
||||
const readGuard = requireRole("admin", "operator", "cashier", "readonly");
|
||||
const writeGuard = requireRole("admin");
|
||||
|
||||
// Validate the body; returns problems (empty = ok). Shared by create + update.
|
||||
function validate(b: PermitBody): string[] {
|
||||
const errs: string[] = [];
|
||||
if (b.maxConcurrent != null) {
|
||||
if (!Number.isInteger(b.maxConcurrent) || b.maxConcurrent < 1) {
|
||||
errs.push("maxConcurrent must be a positive integer, or null for unbound");
|
||||
}
|
||||
}
|
||||
if (b.status && !["active", "suspended", "revoked"].includes(b.status)) {
|
||||
errs.push("status must be active|suspended|revoked");
|
||||
}
|
||||
for (const c of b.credentials ?? []) {
|
||||
if ((c.kind !== "rf" && c.kind !== "qr") || !c.value?.trim()) {
|
||||
errs.push("each credential needs kind (rf|qr) and a non-empty value");
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ((b.credentials?.length ?? 0) === 0 && (b.plates?.length ?? 0) === 0) {
|
||||
errs.push("a permit needs at least one credential or one bound plate (else nothing identifies it)");
|
||||
}
|
||||
return errs;
|
||||
}
|
||||
|
||||
function loadAggregate(id: string) {
|
||||
const permit = db.select().from(permits).where(eq(permits.id, id)).get();
|
||||
if (!permit) return null;
|
||||
const credentials = db.select().from(permitCredentials).where(eq(permitCredentials.permitId, id)).all();
|
||||
const plates = db.select().from(permitPlates).where(eq(permitPlates.permitId, id)).all();
|
||||
return {
|
||||
...permit,
|
||||
credentials: credentials.map((c) => ({ kind: c.kind, value: c.value })),
|
||||
plates: plates.map((p) => p.plate),
|
||||
};
|
||||
}
|
||||
|
||||
// Replace a permit's child rows (credentials + plates) from the body.
|
||||
function writeChildren(id: string, b: PermitBody) {
|
||||
db.delete(permitCredentials).where(eq(permitCredentials.permitId, id)).run();
|
||||
db.delete(permitPlates).where(eq(permitPlates.permitId, id)).run();
|
||||
for (const c of b.credentials ?? []) {
|
||||
db.insert(permitCredentials).values({ id: randomUUID(), permitId: id, kind: c.kind, value: c.value.trim() }).run();
|
||||
}
|
||||
for (const p of b.plates ?? []) {
|
||||
if (p.trim()) db.insert(permitPlates).values({ id: randomUUID(), permitId: id, plate: p.trim() }).run();
|
||||
}
|
||||
}
|
||||
|
||||
// List all permits (with their credentials + plates).
|
||||
app.get("/api/permits", { preHandler: readGuard }, async () => {
|
||||
const rows = db.select().from(permits).all();
|
||||
return { permits: rows.map((r) => loadAggregate(r.id)) };
|
||||
});
|
||||
|
||||
// Create a permit.
|
||||
app.post<{ Body: PermitBody }>("/api/permits", { preHandler: writeGuard }, async (req, reply) => {
|
||||
const b = req.body ?? {};
|
||||
const problems = validate(b);
|
||||
if (problems.length) return reply.code(400).send({ error: "invalid permit", problems });
|
||||
const id = randomUUID();
|
||||
db.insert(permits)
|
||||
.values({
|
||||
id,
|
||||
holderName: b.holderName ?? null,
|
||||
contact: b.contact ?? null,
|
||||
maxConcurrent: b.maxConcurrent === undefined ? 1 : b.maxConcurrent,
|
||||
validFrom: b.validFrom ?? null,
|
||||
validTo: b.validTo ?? null,
|
||||
status: b.status ?? "active",
|
||||
})
|
||||
.run();
|
||||
writeChildren(id, b);
|
||||
return reply.code(201).send(loadAggregate(id));
|
||||
});
|
||||
|
||||
// Update a permit (replaces fields + child sets).
|
||||
app.put<{ Params: { id: string }; Body: PermitBody }>(
|
||||
"/api/permits/:id",
|
||||
{ preHandler: writeGuard },
|
||||
async (req, reply) => {
|
||||
const existing = db.select().from(permits).where(eq(permits.id, req.params.id)).get();
|
||||
if (!existing) return reply.code(404).send({ error: "permit not found" });
|
||||
const b = req.body ?? {};
|
||||
const problems = validate(b);
|
||||
if (problems.length) return reply.code(400).send({ error: "invalid permit", problems });
|
||||
db.update(permits)
|
||||
.set({
|
||||
holderName: b.holderName ?? null,
|
||||
contact: b.contact ?? null,
|
||||
maxConcurrent: b.maxConcurrent === undefined ? existing.maxConcurrent : b.maxConcurrent,
|
||||
validFrom: b.validFrom ?? null,
|
||||
validTo: b.validTo ?? null,
|
||||
status: b.status ?? existing.status,
|
||||
})
|
||||
.where(eq(permits.id, req.params.id))
|
||||
.run();
|
||||
writeChildren(req.params.id, b);
|
||||
return loadAggregate(req.params.id);
|
||||
},
|
||||
);
|
||||
|
||||
// Revoke (soft): the common case — keeps the permit + its history, just bars it.
|
||||
// A revoked permit fails the entry check (see permit-flow.ts). Use DELETE only to
|
||||
// fully remove a permit created in error.
|
||||
app.post<{ Params: { id: string } }>(
|
||||
"/api/permits/:id/revoke",
|
||||
{ preHandler: writeGuard },
|
||||
async (req, reply) => {
|
||||
const r = db.update(permits).set({ status: "revoked" }).where(eq(permits.id, req.params.id)).run();
|
||||
if (r.changes === 0) return reply.code(404).send({ error: "permit not found" });
|
||||
return loadAggregate(req.params.id);
|
||||
},
|
||||
);
|
||||
|
||||
// Hard delete a permit + its child rows. (Past ledger events that reference it
|
||||
// are untouched — the audit trail is append-only and independent of this row.)
|
||||
app.delete<{ Params: { id: string } }>(
|
||||
"/api/permits/:id",
|
||||
{ preHandler: writeGuard },
|
||||
async (req, reply) => {
|
||||
const r = db.delete(permits).where(eq(permits.id, req.params.id)).run();
|
||||
if (r.changes === 0) return reply.code(404).send({ error: "permit not found" });
|
||||
db.delete(permitCredentials).where(eq(permitCredentials.permitId, req.params.id)).run();
|
||||
db.delete(permitPlates).where(eq(permitPlates.permitId, req.params.id)).run();
|
||||
return reply.code(204).send();
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { requireRole } from "../auth.js";
|
||||
import { deviceEvents } from "../device-events.js";
|
||||
import type { PrinterMonitor } from "../printer-monitor.js";
|
||||
|
||||
// Live printer-status API. The PrinterMonitor polls printers in the background;
|
||||
// these endpoints expose its cache (snapshot) and a live push stream (SSE) so the
|
||||
// booth UI shows paper-out / cover-open / offline in real time. Any authenticated
|
||||
// operator may read status (it's operational, not a setup action).
|
||||
|
||||
export async function printerRoutes(
|
||||
app: FastifyInstance,
|
||||
monitor: PrinterMonitor,
|
||||
): Promise<void> {
|
||||
const guard = requireRole("admin", "operator", "cashier", "readonly");
|
||||
|
||||
// Current status of every monitored printer (cached — no device round-trip).
|
||||
app.get("/api/printers/status", { preHandler: guard }, async () => ({
|
||||
printers: monitor.snapshot(),
|
||||
}));
|
||||
|
||||
// Live stream: emits the full snapshot on connect, then one event per change.
|
||||
// Server-Sent Events — one-way, survives proxies, trivially consumed by the SPA.
|
||||
app.get("/api/printers/status/stream", { preHandler: guard }, (req, reply) => {
|
||||
reply.raw.writeHead(200, {
|
||||
"content-type": "text/event-stream",
|
||||
"cache-control": "no-cache",
|
||||
connection: "keep-alive",
|
||||
});
|
||||
|
||||
const send = (event: string, data: unknown) => {
|
||||
reply.raw.write(`event: ${event}\n`);
|
||||
reply.raw.write(`data: ${JSON.stringify(data)}\n\n`);
|
||||
};
|
||||
|
||||
// Initial state so a fresh client doesn't wait for the next change.
|
||||
send("snapshot", { printers: monitor.snapshot() });
|
||||
|
||||
const unsubscribe = deviceEvents.onPrinterStatus((e) => send("status", e));
|
||||
|
||||
// Heartbeat keeps intermediaries from closing an idle connection.
|
||||
const heartbeat = setInterval(() => reply.raw.write(": ping\n\n"), 25000);
|
||||
heartbeat.unref?.();
|
||||
|
||||
req.raw.on("close", () => {
|
||||
clearInterval(heartbeat);
|
||||
unsubscribe();
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { eq, devices, type Db } from "@parking/db";
|
||||
import type { DeviceReadEvent } from "../device-events.js";
|
||||
import type { ReadDispatcher } from "../read-dispatch.js";
|
||||
|
||||
// GEE/Dingtian QR reader endpoint. The reader is configured (vendor tool) with our
|
||||
// host as its "server"; on each scan it sends an HTTP GET and BEEPS/acts based on
|
||||
// our JSON reply — host-in-the-loop and synchronous. Protocol from the QRCode SDK
|
||||
// v1.6.5; see wiki/sources/qrcode-sdk.md and wiki/entities/gee-qr-er80.md.
|
||||
//
|
||||
// reader → GET /qa/mcardsea.php?cardid=<QR>&mjihao=<devId>&cjihao=<devSN>&status=<2ch>&time=<utc>
|
||||
// server → {"data":[{cardid,cjihao,mjihao,status,time,output}],"code":0,"message":""}
|
||||
// reply status: 1 = valid (beep 2×) / 0 = invalid (beep 1×)
|
||||
// reply output: 0 = Access, 1 = WG26, 2 = WG34 (line driven on a valid read)
|
||||
// reply time: UTC — syncs the device clock
|
||||
//
|
||||
// The "server language" set on the device only selects this URL path; we accept the
|
||||
// SDK default path. No auth on the device side (it can't); the reader sits on the
|
||||
// device subnet (network-isolation) and the signed ledger is the real guarantee.
|
||||
|
||||
interface ReaderQuery {
|
||||
cardid?: string;
|
||||
mjihao?: string; // device id
|
||||
cjihao?: string; // device serial
|
||||
status?: string; // 2 chars: high valid/invalid, low 1=in/0=out
|
||||
time?: string;
|
||||
}
|
||||
|
||||
export async function qrReaderRoutes(
|
||||
app: FastifyInstance,
|
||||
db: Db,
|
||||
dispatcher: ReadDispatcher,
|
||||
): Promise<void> {
|
||||
// Resolve the lane_devices row whose config.serial matches the reader's reported
|
||||
// serial (cjihao). The row id is a normal UUID; the serial is config the admin
|
||||
// enters when assigning the gee-qr-reader. Returns the row id, or null if no
|
||||
// reader is assigned for that serial. (Small device set → scan in JS.)
|
||||
const readerRowIdForSerial = (serial: string): string | null => {
|
||||
if (!serial) return null;
|
||||
const rows = db.select().from(devices).where(eq(devices.category, "reader")).all();
|
||||
const match = rows.find((r) => r.enabled && (r.config as { serial?: string }).serial === serial);
|
||||
return match?.id ?? null;
|
||||
};
|
||||
|
||||
// No auth: the reader is a machine on the isolated device subnet and offers no
|
||||
// auth on its side. Public route, like the Dingtian input push.
|
||||
const handler = async (req: { query: ReaderQuery }, reply: import("fastify").FastifyReply) => {
|
||||
const q = req.query;
|
||||
// The reader sends `Connection: keep-alive` but only ACTS on our verdict (beep,
|
||||
// drive output) once the socket CLOSES — every vendor demo replies
|
||||
// `Connection: close` and shuts the socket. Without it the reader waits out a
|
||||
// ~10 s keep-alive timeout before beeping. So force-close the connection.
|
||||
// See wiki/sources/qrcode-sdk.md, entities/gee-qr-er80.md.
|
||||
reply.header("connection", "close");
|
||||
const cardid = (q.cardid ?? "").trim();
|
||||
const mjihao = q.mjihao != null ? Number(q.mjihao) : 0;
|
||||
const serial = (q.cjihao ?? "").trim();
|
||||
|
||||
// Map the reader's serial → its assigned lane_devices row id (the dispatcher
|
||||
// resolves the lane from that row). If unassigned, deviceId stays the serial so
|
||||
// the dispatcher simply finds no lane and rejects (status:0) — never crashes.
|
||||
const deviceId = readerRowIdForSerial(serial) ?? serial;
|
||||
|
||||
let accepted = false;
|
||||
if (cardid) {
|
||||
const read: DeviceReadEvent = {
|
||||
driverId: "gee-qr-reader",
|
||||
deviceId,
|
||||
value: cardid,
|
||||
kind: "qr",
|
||||
at: new Date().toISOString(),
|
||||
};
|
||||
try {
|
||||
const outcome = await dispatcher.dispatch(read);
|
||||
accepted = outcome.accepted;
|
||||
if (!accepted) app.log.info(`QR ${cardid} rejected: ${outcome.reason ?? "?"}`);
|
||||
} catch (err) {
|
||||
app.log.error(`QR dispatch failed for ${cardid}: ${(err as Error).message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Reply the SDK verdict. status 1 → beep 2× (valid) / 0 → beep 1× (invalid).
|
||||
// output 0 = Access (drive the reader's access line on a valid read).
|
||||
return {
|
||||
data: [
|
||||
{
|
||||
cardid,
|
||||
cjihao: q.cjihao ?? 0,
|
||||
mjihao,
|
||||
status: accepted ? 1 : 0,
|
||||
time: String(Math.floor(Date.now() / 1000)),
|
||||
output: 0,
|
||||
},
|
||||
],
|
||||
code: 0,
|
||||
message: "",
|
||||
};
|
||||
};
|
||||
|
||||
// The reader's "server language" setting (JSP/PHP/C#/ASP/CGI) selects the URL
|
||||
// EXTENSION it GETs — verified on hardware: a JSP-configured unit posts
|
||||
// /qa/mcardsea.jsp. Register every extension so the endpoint works whatever the
|
||||
// device is set to; accept POST too in case a variant differs.
|
||||
for (const ext of ["php", "jsp", "asp", "aspx", "cgi"]) {
|
||||
const path = `/qa/mcardsea.${ext}`;
|
||||
app.get<{ Querystring: ReaderQuery }>(path, handler);
|
||||
app.post<{ Querystring: ReaderQuery }>(path, handler);
|
||||
}
|
||||
}
|
||||
+200
-17
@@ -1,25 +1,56 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { randomBytes, randomUUID } from "node:crypto";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { eq, laneDevices, setupState, type Db } from "@parking/db";
|
||||
import { eq, devices, setupState, type Db } from "@parking/db";
|
||||
import {
|
||||
hasPreconditions,
|
||||
hasPushConfig,
|
||||
isDiscoverable,
|
||||
isHardenable,
|
||||
registerBuiltinDrivers,
|
||||
registry,
|
||||
setDeviceLogSink,
|
||||
type DeviceCategory,
|
||||
type DeviceConfig,
|
||||
} from "@parking/devices";
|
||||
import { requireRole } from "../auth.js";
|
||||
import { backendIpCandidates, backendIpForDevice, backendPort } from "../net.js";
|
||||
|
||||
// First-run setup API. The admin reads the driver catalog and assigns devices
|
||||
// per lane. See wiki/concepts/first-run-setup.md.
|
||||
|
||||
interface AssignBody {
|
||||
lane: number;
|
||||
category: DeviceCategory;
|
||||
driverId: string;
|
||||
// Driver config (opaque JSON, validated by the driver). Carries the model's
|
||||
// direction/binding: access → config.relays=[{relay,direction,button?}];
|
||||
// reader/camera → config.controllerId + config.relay. See entry-exit-points.md.
|
||||
config: DeviceConfig;
|
||||
/** Optional: the backend IP the device should push to (overrides auto-pick;
|
||||
* matters on multi-NIC hosts). */
|
||||
backendIp?: string;
|
||||
}
|
||||
|
||||
interface TestBody {
|
||||
driverId: string;
|
||||
config: Record<string, string | number | boolean>;
|
||||
}
|
||||
|
||||
// Config keys that hold MACHINE-ONLY secrets — never sent back to the client.
|
||||
// No human ever uses these to log in: `pushPassword` is the device→backend Digest
|
||||
// secret, `relayPassword` is the binary-protocol relay_pw. They stay redacted.
|
||||
//
|
||||
// NOTE: the device web-UI login (`webUser`/`webPassword`) is deliberately NOT
|
||||
// redacted. It's an operational credential an admin needs to reach the device's
|
||||
// own web page, and the whole device-management area is admin-only — so it's
|
||||
// surfaced in the admin device view rather than hidden. See first-run-setup.md.
|
||||
const SECRET_CONFIG_KEYS = ["pushPassword", "relayPassword"] as const;
|
||||
|
||||
function redactSecrets(config: Record<string, unknown>): Record<string, unknown> {
|
||||
const out = { ...config };
|
||||
for (const k of SECRET_CONFIG_KEYS) delete out[k];
|
||||
return out;
|
||||
}
|
||||
|
||||
export async function setupRoutes(app: FastifyInstance, db: Db): Promise<void> {
|
||||
registerBuiltinDrivers();
|
||||
setDeviceLogSink((line) => app.log.info(line));
|
||||
@@ -28,14 +59,16 @@ export async function setupRoutes(app: FastifyInstance, db: Db): Promise<void> {
|
||||
const adminGuard = requireRole("admin");
|
||||
|
||||
// Catalog of selectable drivers per category (no secrets — schema only).
|
||||
// `discoverable` flags drivers that can scan the LAN (e.g. UHPPOTE).
|
||||
// `discoverable` flags drivers that can scan the LAN; `pushCapable` flags
|
||||
// drivers that push to the backend (and thus need a backend IP at assign time).
|
||||
app.get("/api/setup/catalog", async () => {
|
||||
const catalog = registry.catalog();
|
||||
const discoverable = registry.list().filter(isDiscoverable).map((d) => d.id);
|
||||
return { ...catalog, discoverable };
|
||||
const pushCapable = registry.pushCapable();
|
||||
return { ...catalog, discoverable, pushCapable };
|
||||
});
|
||||
|
||||
// Scan the LAN for devices a driver can discover (UHPPOTE UDP broadcast, etc).
|
||||
// Scan the LAN for devices a driver can discover (UDP broadcast, etc).
|
||||
// Each found device is health-checked so the admin sees reachability before
|
||||
// assigning. Admin-only. See wiki/concepts/device-discovery.md.
|
||||
app.get<{ Params: { driverId: string } }>(
|
||||
@@ -67,43 +100,193 @@ export async function setupRoutes(app: FastifyInstance, db: Db): Promise<void> {
|
||||
},
|
||||
);
|
||||
|
||||
// Current setup status + assignments.
|
||||
// Current setup status + assignments. Secrets are stripped from each config
|
||||
// (the UI lists devices; it never needs the stored push/relay/web passwords).
|
||||
app.get(
|
||||
"/api/setup/state",
|
||||
{ preHandler: adminGuard },
|
||||
async () => {
|
||||
const state = await db.select().from(setupState).where(eq(setupState.id, 1)).get();
|
||||
const assignments = await db.select().from(laneDevices).all();
|
||||
const rows = await db.select().from(devices).all();
|
||||
const assignments = rows.map((r) => ({ ...r, config: redactSecrets(r.config) }));
|
||||
return { completedAt: state?.completedAt ?? null, assignments };
|
||||
},
|
||||
);
|
||||
|
||||
// Assign a device to a lane. Validates the chosen driver + config against the
|
||||
// registry before persisting; rejects unknown drivers / missing config.
|
||||
// Test a device config WITHOUT saving or changing the device: validate the
|
||||
// config, probe reachability (healthCheck), and report preconditions
|
||||
// (e.g. input_link_relay state). Lets the admin verify before committing.
|
||||
app.post<{ Body: TestBody }>(
|
||||
"/api/setup/test",
|
||||
{ preHandler: adminGuard },
|
||||
async (req, reply) => {
|
||||
const { driverId, config } = req.body;
|
||||
const driver = registry.get(driverId);
|
||||
if (!driver) return reply.code(400).send({ error: `unknown driver: ${driverId}` });
|
||||
|
||||
let device;
|
||||
try {
|
||||
device = registry.create(driverId, config);
|
||||
} catch (err) {
|
||||
return reply.code(400).send({ error: (err as Error).message });
|
||||
}
|
||||
|
||||
const health = await device.healthCheck();
|
||||
const preconditions = hasPreconditions(device)
|
||||
? await device.checkPreconditions()
|
||||
: { ok: true, issues: [] };
|
||||
return { health, preconditions };
|
||||
},
|
||||
);
|
||||
|
||||
// Candidate backend IPs the device can push to, for a given device host. The
|
||||
// wizard pre-fills with the on-subnet one and lets the admin override (matters
|
||||
// on multi-NIC hosts). See net.ts / wiki/concepts/device-input-flow.md.
|
||||
app.get<{ Querystring: { host?: string } }>(
|
||||
"/api/setup/backend-ips",
|
||||
{ preHandler: adminGuard },
|
||||
async (req) => {
|
||||
const candidates = backendIpCandidates(req.query.host ?? "");
|
||||
return { candidates, port: backendPort() };
|
||||
},
|
||||
);
|
||||
|
||||
// Assign a device. Validates the chosen driver + config, configures the device
|
||||
// (fix preconditions + set up Digest-authenticated input push — no manual device-
|
||||
// web-UI step by the admin), then persists. Fails the save if the device can't be
|
||||
// configured. See wiki/concepts/device-input-flow.md, entry-exit-points.md.
|
||||
app.post<{ Body: AssignBody }>(
|
||||
"/api/setup/assign",
|
||||
{ preHandler: adminGuard },
|
||||
async (req, reply) => {
|
||||
const { lane, category, driverId, config } = req.body;
|
||||
const { category, driverId, config, backendIp } = req.body;
|
||||
const driver = registry.get(driverId);
|
||||
if (!driver || driver.category !== category) {
|
||||
return reply.code(400).send({ error: `invalid driver for ${category}: ${driverId}` });
|
||||
}
|
||||
|
||||
const id = randomUUID();
|
||||
const fullConfig: Record<string, unknown> = { ...config };
|
||||
// The web password the admin typed is a DESIRED value, not a stored fact:
|
||||
// it's passed to the driver (via create(config) below) as the rotation
|
||||
// target, but we do NOT persist it from the form. Only harden()'s VERIFIED
|
||||
// secrets.webPassword gets saved — otherwise a failed rotation would leave
|
||||
// the DB claiming a password the device never accepted (login stays old).
|
||||
delete fullConfig.webPassword;
|
||||
// webPasswordCurrent is an input-only credential (the OLD password used to
|
||||
// authorize the change) — never persist it as typed.
|
||||
delete fullConfig.webPasswordCurrent;
|
||||
// Residual-risk warnings from device hardening (shown to the admin; the
|
||||
// save still succeeds — these are "configured, but note X" advisories).
|
||||
const hardenWarnings: string[] = [];
|
||||
|
||||
let device;
|
||||
try {
|
||||
registry.create(driverId, config); // validates required fields
|
||||
device = registry.create(driverId, config); // validates required fields
|
||||
} catch (err) {
|
||||
return reply.code(400).send({ error: (err as Error).message });
|
||||
}
|
||||
|
||||
// Configure the device on save (before persisting, so we don't store a row
|
||||
// for a device we couldn't configure):
|
||||
// 1. fix preconditions (e.g. disable input_link_relay so a button press
|
||||
// doesn't auto-fire its relay — host must decide first),
|
||||
// 2. harden (relay password + disable unused protocol channels), and
|
||||
// 3. set up input push (Digest creds + push URLs).
|
||||
// Each step is a device config write (the device reboots on apply).
|
||||
try {
|
||||
if (hasPreconditions(device)) {
|
||||
const fixed = await device.fixPreconditions();
|
||||
if (!fixed.ok) {
|
||||
const unfixable = fixed.issues.find((i) => !i.fixable);
|
||||
return reply.code(502).send({
|
||||
error: `device precondition not satisfied: ${unfixable?.message ?? fixed.issues[0]?.message}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (isHardenable(device)) {
|
||||
const { secrets, warnings } = await device.harden();
|
||||
Object.assign(fullConfig, secrets); // e.g. relayPassword
|
||||
// Surface residual-risk warnings (e.g. firmware that won't disable the
|
||||
// password-less string protocol) so the admin can act (web-UI step).
|
||||
for (const w of warnings ?? []) {
|
||||
app.log.warn(`harden(${driverId} ${id}): ${w}`);
|
||||
hardenWarnings.push(w);
|
||||
}
|
||||
}
|
||||
|
||||
if (hasPushConfig(device)) {
|
||||
const host = String(config.host ?? "");
|
||||
// Admin-provided backend IP wins; else auto-derive (on-subnet NIC).
|
||||
const pushHost = backendIp ?? backendIpForDevice(host);
|
||||
if (!pushHost) {
|
||||
return reply.code(400).send({
|
||||
error: `cannot determine the backend IP on the device's subnet (${host}). Pick one in setup or set BACKEND_HOST_IP.`,
|
||||
});
|
||||
}
|
||||
const pushUser = "dingtian";
|
||||
// 24 hex chars = 96 bits. The Dingtian `pass` field caps at 31 chars
|
||||
// (longer is silently truncated → auth mismatch), so keep it short.
|
||||
const pushPassword = randomBytes(12).toString("hex");
|
||||
await device.configureInputPush({
|
||||
host: pushHost,
|
||||
port: backendPort(),
|
||||
pathBase: `/api/devices/${driverId}/${id}/input`,
|
||||
auth: { user: pushUser, password: pushPassword },
|
||||
});
|
||||
fullConfig.pushUser = pushUser;
|
||||
fullConfig.pushPassword = pushPassword;
|
||||
// Record the backend IP the device was told to push to — lets us detect
|
||||
// a later mismatch if the host's IP changes.
|
||||
fullConfig.backendIp = pushHost;
|
||||
}
|
||||
} catch (err) {
|
||||
return reply
|
||||
.code(502)
|
||||
.send({ error: `device configuration failed: ${(err as Error).message}` });
|
||||
}
|
||||
|
||||
const row = {
|
||||
id: randomUUID(),
|
||||
lane,
|
||||
id,
|
||||
category,
|
||||
driverId,
|
||||
config,
|
||||
config: fullConfig,
|
||||
enabled: true,
|
||||
};
|
||||
await db.insert(laneDevices).values(row);
|
||||
return reply.code(201).send(row);
|
||||
await db.insert(devices).values(row);
|
||||
// Don't echo device secrets back (push Digest password, web-UI login, …).
|
||||
return reply.code(201).send({
|
||||
...row,
|
||||
config: redactSecrets(fullConfig),
|
||||
...(hardenWarnings.length ? { warnings: hardenWarnings } : {}),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
// Unassign (remove) a device instance. The schema is multi-instance — one row
|
||||
// per (lane, category, instance) — so removing one is just deleting its row by
|
||||
// id. Lets the admin manage a LIST of devices per category (add/remove), not a
|
||||
// fixed one-per-category slot. Admin-only. See wiki/concepts/first-run-setup.md.
|
||||
//
|
||||
// NOTE: we only drop our row; we do NOT un-harden / un-configure the device
|
||||
// itself (e.g. clear the Dingtian push URL). The device keeps its last config
|
||||
// harmlessly — pushes from an unknown device id are already rejected (see
|
||||
// routes/devices.ts), and re-assigning reconfigures it. A future "factory
|
||||
// reset on unassign" can hook here if needed.
|
||||
app.delete<{ Params: { id: string } }>(
|
||||
"/api/setup/assign/:id",
|
||||
{ preHandler: adminGuard },
|
||||
async (req, reply) => {
|
||||
const existing = await db
|
||||
.select()
|
||||
.from(devices)
|
||||
.where(eq(devices.id, req.params.id))
|
||||
.get();
|
||||
if (!existing) return reply.code(404).send({ error: "no such device assignment" });
|
||||
await db.delete(devices).where(eq(devices.id, req.params.id));
|
||||
app.log.info(`unassigned device ${req.params.id} (${existing.category}/${existing.driverId})`);
|
||||
return reply.code(204).send();
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { requireRole } from "../auth.js";
|
||||
import {
|
||||
NoOpenShiftError,
|
||||
ShiftAlreadyOpenError,
|
||||
type ShiftService,
|
||||
} from "../shift-service.js";
|
||||
|
||||
// Shift endpoints (manned mode). The operator is the logged-in user; a shift is
|
||||
// opened/closed explicitly (not time-based — see wiki/concepts/shift.md and
|
||||
// local-jwt-auth.md "until logout"). End Shift signs a shift_z_report + prints it.
|
||||
|
||||
export async function shiftRoutes(app: FastifyInstance, shift: ShiftService): Promise<void> {
|
||||
// Cashier/operator/admin run shifts; readonly can't.
|
||||
const guard = requireRole("admin", "operator", "cashier");
|
||||
|
||||
// Is the current operator's shift open? (For the UI to show Start vs. End.)
|
||||
app.get("/api/shift/current", { preHandler: guard }, async (req) => {
|
||||
const operator = req.user.username;
|
||||
const open = shift.openShiftFor(operator);
|
||||
return { operator, open: open ? { startedAt: open.occurredAt } : null };
|
||||
});
|
||||
|
||||
app.post("/api/shift/open", { preHandler: guard }, async (req, reply) => {
|
||||
try {
|
||||
return await shift.open(req.user.username);
|
||||
} catch (err) {
|
||||
if (err instanceof ShiftAlreadyOpenError) return reply.code(409).send({ error: err.message });
|
||||
return reply.code(500).send({ error: (err as Error).message });
|
||||
}
|
||||
});
|
||||
|
||||
app.post("/api/shift/close", { preHandler: guard }, async (req, reply) => {
|
||||
try {
|
||||
return await shift.close(req.user.username);
|
||||
} catch (err) {
|
||||
if (err instanceof NoOpenShiftError) return reply.code(409).send({ error: err.message });
|
||||
return reply.code(500).send({ error: (err as Error).message });
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { eq, siteConfig, type Db } from "@parking/db";
|
||||
import { requireRole } from "../auth.js";
|
||||
import { getOccupancy } from "../occupancy.js";
|
||||
|
||||
// Site config (capacity) + live occupancy. Occupancy is a fold over the signed
|
||||
// ledger; capacity is an admin-set knob. The FULL gate (refuse transient entry at
|
||||
// capacity) lives in the entry flow. See wiki/concepts/capacity-occupancy.md.
|
||||
|
||||
interface SiteConfigBody {
|
||||
/** Nominal capacity; null = no limit. */
|
||||
capacity: number | null;
|
||||
}
|
||||
|
||||
export async function siteRoutes(app: FastifyInstance, db: Db): Promise<void> {
|
||||
const readGuard = requireRole("admin", "operator", "cashier", "readonly");
|
||||
const writeGuard = requireRole("admin");
|
||||
|
||||
// Live occupancy: cars inside, capacity, free, full. Any signed-in role.
|
||||
app.get("/api/occupancy", { preHandler: readGuard }, async () => getOccupancy(db));
|
||||
|
||||
// Read site config (capacity).
|
||||
app.get("/api/site-config", { preHandler: readGuard }, async () => {
|
||||
const row = db.select().from(siteConfig).where(eq(siteConfig.id, 1)).get();
|
||||
return { capacity: row?.capacity ?? null };
|
||||
});
|
||||
|
||||
// Set capacity (admin). null or 0+ integer.
|
||||
app.put<{ Body: SiteConfigBody }>("/api/site-config", { preHandler: writeGuard }, async (req, reply) => {
|
||||
const { capacity } = req.body ?? ({} as SiteConfigBody);
|
||||
if (capacity != null && (!Number.isInteger(capacity) || capacity < 0)) {
|
||||
return reply.code(400).send({ error: "capacity must be a non-negative integer or null" });
|
||||
}
|
||||
const existing = db.select().from(siteConfig).where(eq(siteConfig.id, 1)).get();
|
||||
const updatedAt = new Date().toISOString();
|
||||
if (existing) {
|
||||
db.update(siteConfig).set({ capacity: capacity ?? null, updatedAt }).where(eq(siteConfig.id, 1)).run();
|
||||
} else {
|
||||
db.insert(siteConfig).values({ id: 1, capacity: capacity ?? null, updatedAt }).run();
|
||||
}
|
||||
return { capacity: capacity ?? null };
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { desc, eq, snapshots, type Db } from "@parking/db";
|
||||
import { requireRole } from "../auth.js";
|
||||
|
||||
// Read access to captured entry/exit snapshots (the BLOB-in-DB image store, see
|
||||
// packages/db schema + wiki/concepts/lane-direction.md). Snapshots are evidence
|
||||
// tied to a signed vehicle_entry/exit by `identity`; the operator reviews them
|
||||
// next to the event. Read-only — images are written only by the flows (snapshot.ts),
|
||||
// never via the API.
|
||||
|
||||
export async function snapshotRoutes(app: FastifyInstance, db: Db): Promise<void> {
|
||||
const guard = requireRole("admin", "operator", "cashier", "readonly");
|
||||
|
||||
// Snapshot metadata for one session/credential identity (NOT the bytes), newest
|
||||
// first — lets the UI show "entry/exit image" links beside an event.
|
||||
app.get<{ Params: { identity: string } }>(
|
||||
"/api/snapshots/by-identity/:identity",
|
||||
{ preHandler: guard },
|
||||
async (req) => {
|
||||
const rows = db
|
||||
.select({
|
||||
id: snapshots.id,
|
||||
direction: snapshots.direction,
|
||||
deviceId: snapshots.deviceId,
|
||||
identity: snapshots.identity,
|
||||
contentType: snapshots.contentType,
|
||||
capturedAt: snapshots.capturedAt,
|
||||
})
|
||||
.from(snapshots)
|
||||
.where(eq(snapshots.identity, req.params.identity))
|
||||
.orderBy(desc(snapshots.capturedAt))
|
||||
.all();
|
||||
return { snapshots: rows };
|
||||
},
|
||||
);
|
||||
|
||||
// Stream one snapshot's image bytes by id. Returns the stored content type.
|
||||
app.get<{ Params: { id: string } }>(
|
||||
"/api/snapshots/:id",
|
||||
{ preHandler: guard },
|
||||
async (req, reply) => {
|
||||
const row = db.select().from(snapshots).where(eq(snapshots.id, req.params.id)).get();
|
||||
if (!row) return reply.code(404).send({ error: "no such snapshot" });
|
||||
reply.header("content-type", row.contentType);
|
||||
reply.header("cache-control", "private, max-age=31536000, immutable");
|
||||
return reply.send(row.bytes);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { desc, eq, tariffVersions, tariffs, type Db } from "@parking/db";
|
||||
import { validateTariffStructure, type TariffStructure } from "@parking/shared";
|
||||
import { requireRole } from "../auth.js";
|
||||
|
||||
// Tariff composer API — the admin builds + edits the rate card at runtime. Tariffs
|
||||
// are EFFECTIVE-DATED IMMUTABLE VERSIONS: editing publishes a new version, never
|
||||
// mutates one; a session reprices against the version in force at its entry, and
|
||||
// the `payment` event records the tariffVersionId. "One active tariff per site" for
|
||||
// now (a single `tariffs` row, lazily created). See wiki/concepts/tariff.md.
|
||||
|
||||
interface PublishBody {
|
||||
currency: string;
|
||||
structure: TariffStructure;
|
||||
/** When this version takes effect (ISO-8601). Defaults to now. */
|
||||
effectiveFrom?: string;
|
||||
}
|
||||
|
||||
const SITE_TARIFF_NAME = "Site tariff";
|
||||
|
||||
export async function tariffRoutes(app: FastifyInstance, db: Db): Promise<void> {
|
||||
// Any signed-in role may READ the tariff (the pay station / operator UI needs it).
|
||||
const readGuard = requireRole("admin", "operator", "cashier", "readonly");
|
||||
// Only an admin may PUBLISH a new version (it changes what customers are charged).
|
||||
const writeGuard = requireRole("admin");
|
||||
|
||||
// The single site tariff row, created on first read/publish.
|
||||
function ensureSiteTariff(): string {
|
||||
const existing = db.select().from(tariffs).where(eq(tariffs.scope, "site")).get();
|
||||
if (existing) return existing.id;
|
||||
const id = randomUUID();
|
||||
db.insert(tariffs).values({ id, scope: "site", name: SITE_TARIFF_NAME }).run();
|
||||
return id;
|
||||
}
|
||||
|
||||
// Current state: the active (latest-effective, ≤ now) version + the full history.
|
||||
app.get("/api/tariff", { preHandler: readGuard }, async () => {
|
||||
const tariffId = ensureSiteTariff();
|
||||
const versions = db
|
||||
.select()
|
||||
.from(tariffVersions)
|
||||
.where(eq(tariffVersions.tariffId, tariffId))
|
||||
.orderBy(desc(tariffVersions.effectiveFrom))
|
||||
.all();
|
||||
const now = new Date().toISOString();
|
||||
const active = versions.find((v) => v.effectiveFrom <= now) ?? null;
|
||||
return { tariffId, active, versions };
|
||||
});
|
||||
|
||||
// Publish a new immutable version. Validates the structure first — a malformed
|
||||
// rate card can never be published (the fee calc + the chain depend on it).
|
||||
app.post<{ Body: PublishBody }>(
|
||||
"/api/tariff/versions",
|
||||
{ preHandler: writeGuard },
|
||||
async (req, reply) => {
|
||||
const { currency, structure, effectiveFrom } = req.body ?? ({} as PublishBody);
|
||||
if (!currency || typeof currency !== "string" || currency.length < 3) {
|
||||
return reply.code(400).send({ error: "currency (ISO 4217) required" });
|
||||
}
|
||||
const problems = validateTariffStructure(structure);
|
||||
if (problems.length) {
|
||||
return reply.code(400).send({ error: "invalid tariff structure", problems });
|
||||
}
|
||||
const tariffId = ensureSiteTariff();
|
||||
const id = randomUUID();
|
||||
const row = {
|
||||
id,
|
||||
tariffId,
|
||||
effectiveFrom: effectiveFrom ?? new Date().toISOString(),
|
||||
currency,
|
||||
structure: structure as unknown as Record<string, unknown>,
|
||||
createdBy: req.user?.username ?? null,
|
||||
};
|
||||
db.insert(tariffVersions).values(row).run();
|
||||
return reply.code(201).send(row);
|
||||
},
|
||||
);
|
||||
}
|
||||
+120
-5
@@ -1,9 +1,30 @@
|
||||
import cookie from "@fastify/cookie";
|
||||
import jwt from "@fastify/jwt";
|
||||
import Fastify, { type FastifyInstance } from "fastify";
|
||||
import { createDb, type Db } from "@parking/db";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { createDb, deviceEvents as deviceEventsTable, type Db } from "@parking/db";
|
||||
import { TOKEN_COOKIE, requireJwtSecret } from "./auth.js";
|
||||
import { deviceEvents } from "./device-events.js";
|
||||
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 { ShiftService } from "./shift-service.js";
|
||||
import { ReadDispatcher } from "./read-dispatch.js";
|
||||
import { PrinterMonitor } from "./printer-monitor.js";
|
||||
import { buildSigner } from "./signer.js";
|
||||
import { authRoutes } from "./routes/auth.js";
|
||||
import { deviceRoutes } from "./routes/devices.js";
|
||||
import { eventRoutes } from "./routes/events.js";
|
||||
import { payRoutes } from "./routes/pay.js";
|
||||
import { permitRoutes } from "./routes/permits.js";
|
||||
import { qrReaderRoutes } from "./routes/qr-reader.js";
|
||||
import { shiftRoutes } from "./routes/shift.js";
|
||||
import { siteRoutes } from "./routes/site.js";
|
||||
import { snapshotRoutes } from "./routes/snapshots.js";
|
||||
import { tariffRoutes } from "./routes/tariffs.js";
|
||||
import { printerRoutes } from "./routes/printers.js";
|
||||
import { setupRoutes } from "./routes/setup.js";
|
||||
|
||||
// The backend is Fastify (Node). Hardware drivers live as isolated Fastify
|
||||
@@ -30,7 +51,8 @@ export async function buildServer(opts: BuildOptions = {}): Promise<FastifyInsta
|
||||
// The token is carried in an HttpOnly cookie (not the Authorization header).
|
||||
await app.register(jwt, {
|
||||
secret: requireJwtSecret(),
|
||||
sign: { expiresIn: "8h" }, // bound to a shift; minted tokens must expire
|
||||
// No expiry: a login is valid until explicit logout — a shift is a separate
|
||||
// boundary, not the token lifetime (see auth.ts + wiki/concepts/shift.md).
|
||||
cookie: { cookieName: TOKEN_COOKIE, signed: false },
|
||||
});
|
||||
|
||||
@@ -39,11 +61,104 @@ export async function buildServer(opts: BuildOptions = {}): Promise<FastifyInsta
|
||||
// Local username/password login → JWT in an HttpOnly cookie + CSRF cookie.
|
||||
await authRoutes(app, db);
|
||||
|
||||
// Device-agnostic setup: the admin selects devices per lane from the driver
|
||||
// catalog at first-run. See wiki/concepts/first-run-setup.md.
|
||||
// Device-agnostic setup: the admin adds controllers (with their relays + entry
|
||||
// button) and binds readers/cameras to a controller relay at first-run. There is
|
||||
// no lane — a parking lot is one pool with a flexible set of entry/exit points.
|
||||
// See wiki/concepts/first-run-setup.md, entry-exit-points.md.
|
||||
await setupRoutes(app, db);
|
||||
|
||||
// TODO: device-driver runtime plugins, append-only event-log routes.
|
||||
// Inbound device pushes (e.g. Dingtian Input Link URL → button events),
|
||||
// guarded by source-IP allowlist + a shared-secret path token, both read from
|
||||
// the device's lane_devices config (written on assign).
|
||||
await deviceRoutes(app, db);
|
||||
|
||||
// Live printer-status monitor: polls printers (paper/cover/cutter/offline) and
|
||||
// pushes changes to the booth UI. setupRoutes() has already registered the
|
||||
// built-in drivers the monitor needs. See wiki/concepts/printer-status-monitoring.md.
|
||||
const printerMonitor = new PrinterMonitor(db, app.log);
|
||||
await printerRoutes(app, printerMonitor);
|
||||
app.addHook("onReady", async () => printerMonitor.start());
|
||||
app.addHook("onClose", async () => printerMonitor.stop());
|
||||
|
||||
// Append-only signed business LEDGER (ledger_events). Holds only business facts
|
||||
// (vehicle_entry/exit, payment, void, …) — the anti-fraud audit trail. A raw
|
||||
// button press is NOT a business fact: it's device telemetry, recorded UNSIGNED
|
||||
// in device_events. The entry flow (TODO) turns an input into a signed
|
||||
// vehicle_entry once a ticket prints + the barrier is commanded.
|
||||
// See wiki/decisions/event-streams-split.md.
|
||||
const eventLog = new EventLog(db, buildSigner(app.log));
|
||||
await eventRoutes(app, db, eventLog);
|
||||
|
||||
// Entry/exit camera snapshots (BLOB-in-DB), read-only. See snapshot.ts.
|
||||
await snapshotRoutes(app, db);
|
||||
|
||||
// Entry flow: a button press → print ticket → signed vehicle_entry → pulseOpen.
|
||||
// Subscribes to the SAME input bus as the telemetry writer below; the two are
|
||||
// independent (telemetry always records; the entry flow acts only on an access
|
||||
// device's rising edge). See wiki/concepts/device-input-flow.md + parking-session.md.
|
||||
const entryFlow = new EntryFlow(db, eventLog, app.log);
|
||||
const unsubscribeEntry = deviceEvents.onInput((e) => {
|
||||
void entryFlow.onInput(e);
|
||||
});
|
||||
app.addHook("onClose", async () => unsubscribeEntry());
|
||||
|
||||
// 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 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 () => unsubscribeRead());
|
||||
|
||||
// GEE/Dingtian QR reader: it HTTP-GETs on each scan and beeps/acts on our JSON
|
||||
// verdict (host-in-the-loop, synchronous). Routes the read through the dispatcher
|
||||
// and replies the SDK verdict. See wiki/entities/gee-qr-er80.md, qrcode-sdk.md.
|
||||
await qrReaderRoutes(app, db, readDispatcher);
|
||||
|
||||
// Pay station (pay-on-foot): quote an open session against the active tariff +
|
||||
// take payment → signed `payment` event. See wiki/concepts/tariff.md.
|
||||
const payStation = new PayStation(db, eventLog, app.log);
|
||||
await payRoutes(app, payStation);
|
||||
|
||||
// Tariff composer: admin publishes effective-dated, immutable rate-card versions
|
||||
// the pay station prices against. See wiki/concepts/tariff.md.
|
||||
await tariffRoutes(app, db);
|
||||
|
||||
// Permit (subscription) admin CRUD. See wiki/entities/permit.md.
|
||||
await permitRoutes(app, db);
|
||||
|
||||
// Shifts (manned mode): explicit open/close → signed shift_open / shift_z_report
|
||||
// (sum payments by tender, print the Z-report). See wiki/concepts/shift.md.
|
||||
const shiftService = new ShiftService(db, eventLog, app.log);
|
||||
await shiftRoutes(app, shiftService);
|
||||
|
||||
// Site config (capacity) + live occupancy. The FULL gate (refuse transient entry
|
||||
// at capacity) is in the entry flow. See wiki/concepts/capacity-occupancy.md.
|
||||
await siteRoutes(app, db);
|
||||
|
||||
const unsubscribeInput = deviceEvents.onInput((e) => {
|
||||
// Record every input edge as unsigned telemetry, keyed to the device that fired
|
||||
// (provenance). No lane — the pool-of-spaces model has none. The entry flow
|
||||
// (above) independently decides whether this edge is an entry button.
|
||||
try {
|
||||
db.insert(deviceEventsTable)
|
||||
.values({
|
||||
id: randomUUID(),
|
||||
deviceId: e.deviceId,
|
||||
category: "access",
|
||||
kind: "input",
|
||||
detail: { driverId: e.driverId, input: e.input, edge: e.edge },
|
||||
occurredAt: e.at,
|
||||
})
|
||||
.run();
|
||||
} catch (err) {
|
||||
app.log.error(`device-event insert failed: ${(err as Error).message}`);
|
||||
}
|
||||
});
|
||||
app.addHook("onClose", async () => unsubscribeInput());
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
import { eq, devices, ledgerEvents, type Db } from "@parking/db";
|
||||
import { registry, type PrinterDevice } from "@parking/devices";
|
||||
import type { LedgerPayload } from "@parking/shared";
|
||||
import type { FastifyBaseLogger } from "fastify";
|
||||
import type { EventLog } from "./event-log.js";
|
||||
|
||||
// Shift service (manned mode only). A shift is an operator's accountability period,
|
||||
// delimited by EXPLICIT marks — not a clock. Represented entirely as signed ledger
|
||||
// events (no mutable table): `shift_open` … `shift_z_report`. At close, sum the
|
||||
// `payment` events taken during the shift by tender and print a Z-report.
|
||||
// See wiki/concepts/shift.md.
|
||||
|
||||
export class ShiftAlreadyOpenError extends Error {
|
||||
constructor(operator: string) {
|
||||
super(`operator ${operator} already has an open shift`);
|
||||
this.name = "ShiftAlreadyOpenError";
|
||||
}
|
||||
}
|
||||
export class NoOpenShiftError extends Error {
|
||||
constructor(operator: string) {
|
||||
super(`operator ${operator} has no open shift`);
|
||||
this.name = "NoOpenShiftError";
|
||||
}
|
||||
}
|
||||
|
||||
export interface ShiftReport {
|
||||
readonly operator: string;
|
||||
readonly startedAt: string;
|
||||
readonly endedAt: string;
|
||||
readonly cashTotalMinor: number;
|
||||
readonly cardTotalMinor: number;
|
||||
readonly currency: string | null;
|
||||
readonly paymentCount: number;
|
||||
readonly printed: boolean;
|
||||
}
|
||||
|
||||
export class ShiftService {
|
||||
readonly #db: Db;
|
||||
readonly #log: EventLog;
|
||||
readonly #logger: FastifyBaseLogger;
|
||||
|
||||
constructor(db: Db, log: EventLog, logger: FastifyBaseLogger) {
|
||||
this.#db = db;
|
||||
this.#log = log;
|
||||
this.#logger = logger;
|
||||
}
|
||||
|
||||
/** Is there an open shift for this operator? Returns the open `shift_open` row or null. */
|
||||
openShiftFor(operator: string) {
|
||||
// Scan shift events for this operator; the shift is open if the most recent
|
||||
// shift event for them is a `shift_open` (not yet closed by a z_report).
|
||||
const rows = this.#db
|
||||
.select()
|
||||
.from(ledgerEvents)
|
||||
.where(eq(ledgerEvents.identity, operator))
|
||||
.orderBy(ledgerEvents.index)
|
||||
.all()
|
||||
.filter((r) => r.type === "shift_open" || r.type === "shift_z_report");
|
||||
const last = rows[rows.length - 1];
|
||||
return last && last.type === "shift_open" ? last : null;
|
||||
}
|
||||
|
||||
/** Open a shift for the operator (explicit start). */
|
||||
async open(operator: string): Promise<{ startedAt: string }> {
|
||||
if (this.openShiftFor(operator)) throw new ShiftAlreadyOpenError(operator);
|
||||
const startedAt = new Date().toISOString();
|
||||
await this.#log.append({
|
||||
type: "shift_open",
|
||||
source: "manual",
|
||||
identity: operator, // the shift's operator; `identity` keys the shift to them
|
||||
payload: { operator },
|
||||
occurredAt: startedAt,
|
||||
});
|
||||
this.#logger.info(`shift opened for ${operator}`);
|
||||
return { startedAt };
|
||||
}
|
||||
|
||||
/** Close the operator's open shift: sum payments in the window, sign + print the Z-report. */
|
||||
async close(operator: string): Promise<ShiftReport> {
|
||||
const open = this.openShiftFor(operator);
|
||||
if (!open) throw new NoOpenShiftError(operator);
|
||||
const startedAt = open.occurredAt;
|
||||
const endedAt = new Date().toISOString();
|
||||
|
||||
// All payments taken in [startedAt, endedAt], summed by tender. Payment time =
|
||||
// the operator who handled the money (decision: sum by payment time).
|
||||
const payments = this.#db
|
||||
.select()
|
||||
.from(ledgerEvents)
|
||||
.where(eq(ledgerEvents.type, "payment"))
|
||||
.all()
|
||||
.filter((r) => r.occurredAt >= startedAt && r.occurredAt <= endedAt);
|
||||
|
||||
let cashTotalMinor = 0;
|
||||
let cardTotalMinor = 0;
|
||||
let currency: string | null = null;
|
||||
for (const p of payments) {
|
||||
const pl = (p.payload ?? {}) as LedgerPayload;
|
||||
const amt = typeof pl.amountMinor === "number" ? pl.amountMinor : 0;
|
||||
if (pl.tender === "card") cardTotalMinor += amt;
|
||||
else cashTotalMinor += amt;
|
||||
if (pl.currency) currency = pl.currency;
|
||||
}
|
||||
|
||||
await this.#log.append({
|
||||
type: "shift_z_report",
|
||||
source: "manual",
|
||||
identity: operator,
|
||||
payload: {
|
||||
operator,
|
||||
startedAt,
|
||||
endedAt,
|
||||
cashTotalMinor,
|
||||
cardTotalMinor,
|
||||
currency: currency ?? undefined,
|
||||
paymentCount: payments.length,
|
||||
},
|
||||
});
|
||||
|
||||
const printed = await this.#printZReport({
|
||||
operator,
|
||||
startedAt,
|
||||
endedAt,
|
||||
cashTotalMinor,
|
||||
cardTotalMinor,
|
||||
currency,
|
||||
paymentCount: payments.length,
|
||||
});
|
||||
|
||||
this.#logger.info(
|
||||
`shift closed for ${operator}: cash ${cashTotalMinor} card ${cardTotalMinor} (${payments.length} payments)`,
|
||||
);
|
||||
return { operator, startedAt, endedAt, cashTotalMinor, cardTotalMinor, currency, paymentCount: payments.length, printed };
|
||||
}
|
||||
|
||||
/** Print the Z-report on a booth-receipt printer (best-effort; the signed event
|
||||
* is the record — a failed print doesn't undo the close). */
|
||||
async #printZReport(r: Omit<ShiftReport, "printed">): Promise<boolean> {
|
||||
const printer = await this.#boothPrinter();
|
||||
if (!printer) {
|
||||
this.#logger.warn(`no booth-receipt printer — Z-report for ${r.operator} not printed (event is recorded)`);
|
||||
return false;
|
||||
}
|
||||
const cur = r.currency ?? "";
|
||||
const money = (m: number) => (m / 100).toFixed(2);
|
||||
const lines = [
|
||||
`Operator: ${r.operator}`,
|
||||
`From: ${r.startedAt}`,
|
||||
`To: ${r.endedAt}`,
|
||||
"",
|
||||
`Payments: ${r.paymentCount}`,
|
||||
`Cash: ${money(r.cashTotalMinor)} ${cur}`,
|
||||
`Card: ${money(r.cardTotalMinor)} ${cur}`,
|
||||
];
|
||||
try {
|
||||
await printer.printReport({ title: "SHIFT Z-REPORT", lines });
|
||||
return true;
|
||||
} catch (err) {
|
||||
this.#logger.warn(`Z-report print failed for ${r.operator}: ${(err as Error).message} (event recorded)`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** First enabled booth-receipt printer, or any enabled printer. */
|
||||
async #boothPrinter(): Promise<PrinterDevice | null> {
|
||||
const rows = await this.#db.select().from(devices).where(eq(devices.category, "printer")).all();
|
||||
const enabled = rows.filter((r) => r.enabled);
|
||||
const booth = enabled.find((r) => (r.config as { role?: string }).role === "booth-receipt") ?? enabled[0];
|
||||
if (!booth) return null;
|
||||
const driver = registry.get(booth.driverId);
|
||||
if (!driver) return null;
|
||||
try {
|
||||
return driver.create(booth.config as never) as PrinterDevice;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { createHmac, timingSafeEqual } from "node:crypto";
|
||||
import type { Signer } from "@parking/shared";
|
||||
|
||||
// Concrete signers for the append-only event chain. The Signer interface is the
|
||||
// abstraction over the ATECC608 secure element (open-question #6 — chip not yet
|
||||
// confirmed wired). Until the chip is present we use a software HMAC signer:
|
||||
// it makes the chain self-consistent + tamper-evident, but is NOT unforgeable by
|
||||
// someone who owns the host (only the ATECC608's non-extractable key is). The
|
||||
// swap to hardware is a new Signer impl — no event-log changes.
|
||||
// See wiki/concepts/append-only-event-chain.md and wiki/entities/atecc608.md.
|
||||
|
||||
/** HMAC-SHA256 software signer. Key from env; fail fast if missing in prod. */
|
||||
export class SoftwareSigner implements Signer {
|
||||
readonly keyId: string;
|
||||
readonly #key: Buffer;
|
||||
|
||||
// v2 canonical form: `lane` dropped from the signed array (pool-of-spaces model,
|
||||
// 2026-06-16). v1 events used a different field order and won't verify under v2 —
|
||||
// that's intentional and gated by the per-event keyId. See event-log canonicalize().
|
||||
constructor(secret: string, keyId = "sw-hmac-v2") {
|
||||
this.#key = Buffer.from(secret, "utf8");
|
||||
this.keyId = keyId;
|
||||
}
|
||||
|
||||
sign(payload: string): string {
|
||||
return createHmac("sha256", this.#key).update(payload, "utf8").digest("hex");
|
||||
}
|
||||
|
||||
verify(payload: string, signature: string): boolean {
|
||||
const expected = this.sign(payload);
|
||||
// Constant-time compare; bail on length mismatch (timingSafeEqual throws).
|
||||
if (expected.length !== signature.length) return false;
|
||||
return timingSafeEqual(Buffer.from(expected, "hex"), Buffer.from(signature, "hex"));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the process signer. Uses EVENT_SIGNING_KEY (HMAC secret). Falls back to
|
||||
* the JWT secret only as a last resort so dev works out of the box — logged as a
|
||||
* warning, because reusing the auth secret for event signing is not ideal.
|
||||
*
|
||||
* TODO(atecc608): when the secure element is wired, return an Atecc608Signer here
|
||||
* (keyId "atecc608-slotN"); existing events stay verifiable via their stored keyId.
|
||||
*/
|
||||
export function buildSigner(log?: { warn: (msg: string) => void }): Signer {
|
||||
const dedicated = process.env.EVENT_SIGNING_KEY;
|
||||
if (dedicated && dedicated.length >= 16) {
|
||||
return new SoftwareSigner(dedicated);
|
||||
}
|
||||
const jwtSecret = process.env.JWT_SECRET;
|
||||
if (jwtSecret && jwtSecret.length >= 16) {
|
||||
log?.warn(
|
||||
"event signing: EVENT_SIGNING_KEY unset — falling back to JWT_SECRET. Set a dedicated key (and wire the ATECC608) before production.",
|
||||
);
|
||||
return new SoftwareSigner(jwtSecret, "sw-hmac-jwtfallback");
|
||||
}
|
||||
throw new Error(
|
||||
"event signing: no signing key. Set EVENT_SIGNING_KEY (>=16 chars) for the append-only event chain.",
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { deviceEvents as deviceEventsTable, snapshots, type Db } from "@parking/db";
|
||||
import { registry, type CameraDevice } from "@parking/devices";
|
||||
import type { FastifyBaseLogger } from "fastify";
|
||||
import { devicesByDirection, type FlowDirection } from "./device-resolve.js";
|
||||
|
||||
// Camera snapshot capture, fired AFTER the barrier opens and never awaited on the
|
||||
// open path (decision 2026-06-16): a snapshot is EVIDENCE, not a gate. A camera
|
||||
// failure must never delay or prevent an open — the signed ledger is the decision,
|
||||
// the image is an independent, prunable record stored as a BLOB in `snapshots`.
|
||||
// See wiki/concepts/entry-exit-points.md and append-only-event-chain.md.
|
||||
//
|
||||
// Every camera serving the firing direction (entry/exit, or both) snapshots. Each
|
||||
// capture is independent — one camera down doesn't stop the others. A captured image
|
||||
// → a `snapshots` row + a `kind:"snapshot"` telemetry device_event; a failure → a
|
||||
// telemetry device_event only. The caller passes the session `identity` so the image
|
||||
// links to the signed vehicle_entry/exit.
|
||||
|
||||
interface SnapshotJob {
|
||||
readonly db: Db;
|
||||
readonly direction: FlowDirection;
|
||||
/** Session/credential ref (ticket id, plate, permit car key) — links to the ledger. */
|
||||
readonly identity: string;
|
||||
readonly logger: FastifyBaseLogger;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fire snapshots for the directional camera set. Returns immediately with a promise
|
||||
* the caller MAY ignore (fire-and-forget) — it resolves to the captured snapshot ids.
|
||||
* The caller must NOT block its open path on this.
|
||||
*/
|
||||
export function snapshotAsync(job: SnapshotJob): Promise<string[]> {
|
||||
const { db, direction, identity, logger } = job;
|
||||
const rows = devicesByDirection(db, "camera", direction);
|
||||
if (rows.length === 0) return Promise.resolve([]);
|
||||
|
||||
return Promise.all(
|
||||
rows.map(async (row): Promise<string | null> => {
|
||||
const camera = buildCamera(row);
|
||||
if (!camera) {
|
||||
recordFailure(db, direction, row.id, identity, "camera config won't build", logger);
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const shot = await camera.captureSnapshot({ direction });
|
||||
const id: string = randomUUID();
|
||||
db.insert(snapshots)
|
||||
.values({
|
||||
id,
|
||||
direction,
|
||||
deviceId: row.id,
|
||||
identity,
|
||||
contentType: shot.contentType,
|
||||
bytes: shot.bytes,
|
||||
capturedAt: shot.capturedAt,
|
||||
})
|
||||
.run();
|
||||
// Telemetry breadcrumb pointing at the stored image (NOT the bytes).
|
||||
recordEvent(db, direction, row.id, identity, { snapshotId: id, ok: true }, logger);
|
||||
return id;
|
||||
} catch (err) {
|
||||
recordFailure(db, direction, row.id, identity, (err as Error).message, logger);
|
||||
return null;
|
||||
}
|
||||
}),
|
||||
).then((ids) => ids.filter((id): id is string => id != null));
|
||||
}
|
||||
|
||||
/** Build a live camera adapter from a resolved devices row, or null. */
|
||||
function buildCamera(row: { driverId: string; config: unknown }): CameraDevice | null {
|
||||
const driver = registry.get(row.driverId);
|
||||
if (!driver) return null;
|
||||
try {
|
||||
return driver.create(row.config as never) as CameraDevice;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function recordFailure(
|
||||
db: Db,
|
||||
direction: FlowDirection,
|
||||
deviceId: string,
|
||||
identity: string,
|
||||
error: string,
|
||||
logger: FastifyBaseLogger,
|
||||
): void {
|
||||
logger.warn(`snapshot failed (${direction}, ${identity}): ${error}`);
|
||||
recordEvent(db, direction, deviceId, identity, { ok: false, error }, logger);
|
||||
}
|
||||
|
||||
function recordEvent(
|
||||
db: Db,
|
||||
direction: FlowDirection,
|
||||
deviceId: string,
|
||||
identity: string,
|
||||
detail: Record<string, unknown>,
|
||||
logger: FastifyBaseLogger,
|
||||
): void {
|
||||
try {
|
||||
db.insert(deviceEventsTable)
|
||||
.values({
|
||||
id: randomUUID(),
|
||||
deviceId,
|
||||
category: "camera",
|
||||
kind: "snapshot",
|
||||
detail: { ...detail, direction, identity },
|
||||
occurredAt: new Date().toISOString(),
|
||||
})
|
||||
.run();
|
||||
} catch (err) {
|
||||
// Telemetry is best-effort; never let it surface on the (already-open) path.
|
||||
logger.error(`snapshot device-event insert failed: ${(err as Error).message}`);
|
||||
}
|
||||
}
|
||||
+11
-1
@@ -1,7 +1,11 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { fetchMe, logout, type SessionUser } from "./api.js";
|
||||
import { Login } from "./Login.js";
|
||||
import { PermitManager } from "./PermitManager.js";
|
||||
import { SetupWizard } from "./SetupWizard.js";
|
||||
import { ShiftControl } from "./ShiftControl.js";
|
||||
import { SiteSettings } from "./SiteSettings.js";
|
||||
import { TariffComposer } from "./TariffComposer.js";
|
||||
|
||||
// Operator UI shell. Plain React (no admin framework) — the operator UI is
|
||||
// simple enough that a framework's abstractions cost more than they save.
|
||||
@@ -38,8 +42,14 @@ export function App() {
|
||||
</button>
|
||||
</span>
|
||||
</header>
|
||||
<SiteSettings canEdit={user.role === "admin"} />
|
||||
{user.role !== "readonly" && <ShiftControl />}
|
||||
{user.role === "admin" ? (
|
||||
<SetupWizard />
|
||||
<>
|
||||
<SetupWizard />
|
||||
<TariffComposer />
|
||||
<PermitManager />
|
||||
</>
|
||||
) : (
|
||||
<p style={{ marginTop: "1rem" }}>Signed in. (Operator console coming soon.)</p>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import {
|
||||
ApiError,
|
||||
createPermit,
|
||||
deletePermit,
|
||||
fetchPermits,
|
||||
revokePermit,
|
||||
updatePermit,
|
||||
type Permit,
|
||||
type PermitCredential,
|
||||
type PermitInput,
|
||||
} from "./api.js";
|
||||
|
||||
// Permit (subscription) admin. Create/edit/revoke/delete permits + their
|
||||
// credentials (card/QR) and bound plates. A permit is mutable master data; every
|
||||
// USE of it is a signed ledger event elsewhere. See wiki/entities/permit.md.
|
||||
|
||||
interface FormState {
|
||||
holderName: string;
|
||||
contact: string;
|
||||
carBound: boolean; // false = unbound (maxConcurrent null)
|
||||
maxConcurrent: string;
|
||||
validFrom: string;
|
||||
validTo: string;
|
||||
credentials: PermitCredential[];
|
||||
platesText: string; // comma/space separated
|
||||
}
|
||||
|
||||
function emptyForm(): FormState {
|
||||
return { holderName: "", contact: "", carBound: true, maxConcurrent: "1", validFrom: "", validTo: "", credentials: [{ kind: "rf", value: "" }], platesText: "" };
|
||||
}
|
||||
function formFrom(p: Permit): FormState {
|
||||
return {
|
||||
holderName: p.holderName ?? "",
|
||||
contact: p.contact ?? "",
|
||||
carBound: p.maxConcurrent != null,
|
||||
maxConcurrent: p.maxConcurrent != null ? String(p.maxConcurrent) : "1",
|
||||
validFrom: p.validFrom ?? "",
|
||||
validTo: p.validTo ?? "",
|
||||
credentials: p.credentials.length ? p.credentials : [{ kind: "rf", value: "" }],
|
||||
platesText: p.plates.join(", "),
|
||||
};
|
||||
}
|
||||
function toInput(f: FormState): PermitInput {
|
||||
return {
|
||||
holderName: f.holderName.trim() || null,
|
||||
contact: f.contact.trim() || null,
|
||||
maxConcurrent: f.carBound ? Math.max(1, Math.round(Number(f.maxConcurrent) || 1)) : null,
|
||||
validFrom: f.validFrom.trim() || null,
|
||||
validTo: f.validTo.trim() || null,
|
||||
credentials: f.credentials.filter((c) => c.value.trim()).map((c) => ({ kind: c.kind, value: c.value.trim() })),
|
||||
plates: f.platesText.split(/[,\s]+/).map((s) => s.trim()).filter(Boolean),
|
||||
};
|
||||
}
|
||||
|
||||
export function PermitManager() {
|
||||
const [permits, setPermits] = useState<Permit[] | null>(null);
|
||||
const [editing, setEditing] = useState<string | "new" | null>(null);
|
||||
const [form, setForm] = useState<FormState>(emptyForm);
|
||||
const [msg, setMsg] = useState<{ kind: "ok" | "err"; text: string } | null>(null);
|
||||
|
||||
function reload() {
|
||||
fetchPermits()
|
||||
.then((r) => setPermits(r.permits))
|
||||
.catch((e) => setMsg({ kind: "err", text: (e as Error).message }));
|
||||
}
|
||||
useEffect(reload, []);
|
||||
|
||||
function startNew() {
|
||||
setForm(emptyForm());
|
||||
setEditing("new");
|
||||
setMsg(null);
|
||||
}
|
||||
function startEdit(p: Permit) {
|
||||
setForm(formFrom(p));
|
||||
setEditing(p.id);
|
||||
setMsg(null);
|
||||
}
|
||||
|
||||
async function save() {
|
||||
setMsg(null);
|
||||
try {
|
||||
if (editing === "new") await createPermit(toInput(form));
|
||||
else if (editing) await updatePermit(editing, toInput(form));
|
||||
setEditing(null);
|
||||
reload();
|
||||
setMsg({ kind: "ok", text: "Permit saved." });
|
||||
} catch (e) {
|
||||
const problems = e instanceof ApiError ? (e as ApiError & { problems?: string[] }).problems : undefined;
|
||||
setMsg({ kind: "err", text: problems?.length ? `${(e as Error).message}: ${problems.join("; ")}` : (e as Error).message });
|
||||
}
|
||||
}
|
||||
async function doRevoke(p: Permit) {
|
||||
if (!confirm(`Revoke permit for ${p.holderName ?? p.id}? It will be refused at the barrier.`)) return;
|
||||
await revokePermit(p.id).catch((e) => setMsg({ kind: "err", text: (e as Error).message }));
|
||||
reload();
|
||||
}
|
||||
async function doDelete(p: Permit) {
|
||||
if (!confirm(`Delete permit for ${p.holderName ?? p.id}? (Past events are kept.)`)) return;
|
||||
await deletePermit(p.id).catch((e) => setMsg({ kind: "err", text: (e as Error).message }));
|
||||
reload();
|
||||
}
|
||||
|
||||
function setCred(i: number, patch: Partial<PermitCredential>) {
|
||||
setForm((f) => ({ ...f, credentials: f.credentials.map((c, j) => (j === i ? { ...c, ...patch } : c)) }));
|
||||
}
|
||||
|
||||
if (!permits) return null;
|
||||
|
||||
return (
|
||||
<section style={{ marginTop: "2rem" }}>
|
||||
<h2>Permits</h2>
|
||||
<ul style={{ listStyle: "none", padding: 0 }}>
|
||||
{permits.map((p) => (
|
||||
<li key={p.id} style={{ display: "flex", gap: "0.5rem", alignItems: "center", padding: "0.4rem 0", borderBottom: "1px solid #eee" }}>
|
||||
<strong>{p.holderName ?? "(unnamed)"}</strong>
|
||||
<span style={{ color: p.status === "active" ? "#16a34a" : "#b45309" }}>{p.status}</span>
|
||||
<span style={{ color: "#666" }}>
|
||||
{p.maxConcurrent == null ? "unbound" : `${p.maxConcurrent} car${p.maxConcurrent > 1 ? "s" : ""}`} ·{" "}
|
||||
{p.credentials.length} cred · {p.plates.length} plate(s)
|
||||
</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<button type="button" onClick={() => startEdit(p)}>Edit</button>
|
||||
{p.status !== "revoked" && <button type="button" onClick={() => doRevoke(p)}>Revoke</button>}
|
||||
<button type="button" onClick={() => doDelete(p)}>Delete</button>
|
||||
</li>
|
||||
))}
|
||||
{permits.length === 0 && <li style={{ color: "#777" }}>No permits yet.</li>}
|
||||
</ul>
|
||||
|
||||
{editing == null ? (
|
||||
<button type="button" onClick={startNew}>+ Add permit</button>
|
||||
) : (
|
||||
<div style={{ border: "1px solid #ddd", padding: "1rem", marginTop: "0.5rem", maxWidth: 460 }}>
|
||||
<h3 style={{ marginTop: 0 }}>{editing === "new" ? "New permit" : "Edit permit"}</h3>
|
||||
<div style={{ display: "grid", gridTemplateColumns: "max-content 1fr", gap: "0.4rem 0.75rem", alignItems: "center" }}>
|
||||
<label>Holder name</label>
|
||||
<input value={form.holderName} onChange={(e) => setForm((f) => ({ ...f, holderName: e.target.value }))} />
|
||||
<label>Contact</label>
|
||||
<input value={form.contact} onChange={(e) => setForm((f) => ({ ...f, contact: e.target.value }))} />
|
||||
<label>Car limit</label>
|
||||
<span>
|
||||
<label style={{ marginRight: "0.5rem" }}>
|
||||
<input type="checkbox" checked={form.carBound} onChange={(e) => setForm((f) => ({ ...f, carBound: e.target.checked }))} /> limit cars in at once
|
||||
</label>
|
||||
{form.carBound && (
|
||||
<input value={form.maxConcurrent} onChange={(e) => setForm((f) => ({ ...f, maxConcurrent: e.target.value }))} style={{ width: 50 }} />
|
||||
)}
|
||||
</span>
|
||||
<label>Valid from</label>
|
||||
<input value={form.validFrom} onChange={(e) => setForm((f) => ({ ...f, validFrom: e.target.value }))} placeholder="ISO date (optional)" />
|
||||
<label>Valid to</label>
|
||||
<input value={form.validTo} onChange={(e) => setForm((f) => ({ ...f, validTo: e.target.value }))} placeholder="ISO date (optional)" />
|
||||
<label>Bound plates</label>
|
||||
<input value={form.platesText} onChange={(e) => setForm((f) => ({ ...f, platesText: e.target.value }))} placeholder="comma-separated (optional)" />
|
||||
</div>
|
||||
|
||||
<h4 style={{ marginBottom: "0.25rem" }}>Credentials (card / QR)</h4>
|
||||
{form.credentials.map((c, i) => (
|
||||
<div key={i} style={{ display: "flex", gap: "0.4rem", marginBottom: "0.3rem" }}>
|
||||
<select value={c.kind} onChange={(e) => setCred(i, { kind: e.target.value as "rf" | "qr" })}>
|
||||
<option value="rf">RF card/tag</option>
|
||||
<option value="qr">QR</option>
|
||||
</select>
|
||||
<input value={c.value} onChange={(e) => setCred(i, { value: e.target.value })} placeholder="credential value" style={{ flex: 1 }} />
|
||||
<button type="button" onClick={() => setForm((f) => ({ ...f, credentials: f.credentials.filter((_, j) => j !== i) }))}>×</button>
|
||||
</div>
|
||||
))}
|
||||
<button type="button" onClick={() => setForm((f) => ({ ...f, credentials: [...f.credentials, { kind: "rf", value: "" }] }))}>+ credential</button>
|
||||
<p style={{ color: "#777", fontSize: "0.85em", margin: "0.5rem 0 0" }}>
|
||||
A permit needs at least one credential OR one bound plate.
|
||||
</p>
|
||||
|
||||
<div style={{ marginTop: "1rem", display: "flex", gap: "0.5rem" }}>
|
||||
<button type="button" onClick={save}>Save</button>
|
||||
<button type="button" onClick={() => setEditing(null)}>Cancel</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{msg && <p style={{ color: msg.kind === "ok" ? "#16a34a" : "crimson" }}>{msg.text}</p>}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
+635
-49
@@ -1,92 +1,350 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import {
|
||||
assignDevice,
|
||||
discoverDevices,
|
||||
fetchBackendIps,
|
||||
fetchCatalog,
|
||||
fetchState,
|
||||
testDevice,
|
||||
unassignDevice,
|
||||
type Assignment,
|
||||
type BackendIpCandidate,
|
||||
type Catalog,
|
||||
type CatalogEntry,
|
||||
type DeviceCategory,
|
||||
type DeviceConfig,
|
||||
type Direction,
|
||||
type DiscoveredDevice,
|
||||
type RelaySpec,
|
||||
type TestResult,
|
||||
} from "./api.js";
|
||||
|
||||
// First-run setup wizard (scaffold). The admin picks a device per category for a
|
||||
// lane from the driver catalog and fills in its connection config. Drivers that
|
||||
// support LAN discovery (e.g. UHPPOTE) get a "Scan" button that lists found
|
||||
// devices; selecting one auto-fills the config. Auth is via the admin's session
|
||||
// cookie (the SPA only renders this for admins). See wiki/concepts/first-run-setup.md
|
||||
// and device-discovery.md.
|
||||
// First-run setup wizard. The pool-of-spaces model: a parking lot is one pool with
|
||||
// a flexible set of entry/exit points — NO lane. The admin adds CONTROLLERS (each
|
||||
// declares its relays = entry/exit/both + which input terminal the entry button is
|
||||
// on), then binds READERS / CAMERAS to a controller relay (the barrier they sit at).
|
||||
// Direction is a property of the relay, inherited by bound devices. The data model
|
||||
// is multi-instance — one `devices` row per instance. See entry-exit-points.md.
|
||||
|
||||
const CATEGORIES: { key: DeviceCategory; title: string }[] = [
|
||||
{ key: "access", title: "Access controller" },
|
||||
{ key: "reader", title: "Reader" },
|
||||
{ key: "camera", title: "Camera (entry/exit snapshot)" },
|
||||
{ key: "printer", title: "Printer" },
|
||||
const CONTROLLER: { key: DeviceCategory; title: string; noun: string } = {
|
||||
key: "access",
|
||||
title: "Controllers (barriers + entry button)",
|
||||
noun: "controller",
|
||||
};
|
||||
// Categories that BIND to a controller relay (direction inherited from the relay).
|
||||
const BOUND: { key: DeviceCategory; title: string; noun: string }[] = [
|
||||
{ key: "reader", title: "Readers (QR / RFID)", noun: "reader" },
|
||||
{ key: "camera", title: "Cameras (snapshot + plate)", noun: "camera" },
|
||||
{ key: "printer", title: "Printers (tickets / vouchers)", noun: "printer" },
|
||||
];
|
||||
|
||||
const DIRECTION_LABELS: Record<Direction, string> = {
|
||||
entry: "Entry",
|
||||
exit: "Exit",
|
||||
both: "Both (entry + exit)",
|
||||
};
|
||||
|
||||
export function SetupWizard() {
|
||||
const [catalog, setCatalog] = useState<Catalog | null>(null);
|
||||
const [lane, setLane] = useState(1);
|
||||
const [picked, setPicked] = useState<Partial<Record<DeviceCategory, string>>>({});
|
||||
const [assignments, setAssignments] = useState<Assignment[] | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const reloadState = useCallback(() => {
|
||||
return fetchState()
|
||||
.then((s) => setAssignments(s.assignments))
|
||||
.catch((e: Error) => setError(e.message));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
fetchCatalog().then(setCatalog).catch((e: Error) => setError(e.message));
|
||||
}, []);
|
||||
reloadState();
|
||||
}, [reloadState]);
|
||||
|
||||
if (error) return <p style={{ color: "crimson" }}>Failed to load catalog: {error}</p>;
|
||||
if (!catalog) return <p>Loading device catalog…</p>;
|
||||
if (error) return <p style={{ color: "crimson" }}>Failed to load setup: {error}</p>;
|
||||
if (!catalog || !assignments) return <p>Loading device catalog…</p>;
|
||||
|
||||
// Controllers are needed before binding readers/cameras (they pick a controller relay).
|
||||
const controllers = assignments.filter((a) => a.category === "access");
|
||||
|
||||
return (
|
||||
<section>
|
||||
<h2>First-run setup</h2>
|
||||
<div style={{ display: "flex", gap: "1rem", alignItems: "center" }}>
|
||||
<label>
|
||||
Lane{" "}
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
value={lane}
|
||||
onChange={(e) => setLane(Number(e.target.value))}
|
||||
style={{ width: "4rem" }}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<p style={{ color: "#666", fontSize: "0.9em" }}>
|
||||
Add your barrier controllers first — set which relay is entry/exit and which
|
||||
terminal the entry button is wired to. Then add readers, cameras and printers
|
||||
and point each at the barrier it serves.
|
||||
</p>
|
||||
|
||||
{CATEGORIES.map(({ key, title }) => (
|
||||
<CategoryPicker
|
||||
<CategorySection
|
||||
category={CONTROLLER.key}
|
||||
title={CONTROLLER.title}
|
||||
noun={CONTROLLER.noun}
|
||||
entries={catalog[CONTROLLER.key]}
|
||||
discoverableIds={catalog.discoverable}
|
||||
pushCapableIds={catalog.pushCapable}
|
||||
controllers={controllers}
|
||||
assignments={controllers}
|
||||
onChanged={reloadState}
|
||||
/>
|
||||
|
||||
{BOUND.map(({ key, title, noun }) => (
|
||||
<CategorySection
|
||||
key={key}
|
||||
category={key}
|
||||
title={title}
|
||||
noun={noun}
|
||||
entries={catalog[key]}
|
||||
discoverableIds={catalog.discoverable}
|
||||
selectedId={picked[key]}
|
||||
onSelect={(id) => setPicked((p) => ({ ...p, [key]: id }))}
|
||||
pushCapableIds={catalog.pushCapable}
|
||||
controllers={controllers}
|
||||
assignments={assignments.filter((a) => a.category === key)}
|
||||
onChanged={reloadState}
|
||||
/>
|
||||
))}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function CategoryPicker({
|
||||
function CategorySection({
|
||||
category,
|
||||
title,
|
||||
noun,
|
||||
entries,
|
||||
discoverableIds,
|
||||
selectedId,
|
||||
onSelect,
|
||||
pushCapableIds,
|
||||
controllers,
|
||||
assignments,
|
||||
onChanged,
|
||||
}: {
|
||||
category: DeviceCategory;
|
||||
title: string;
|
||||
noun: string;
|
||||
entries: CatalogEntry[];
|
||||
discoverableIds: string[];
|
||||
selectedId: string | undefined;
|
||||
onSelect: (id: string) => void;
|
||||
pushCapableIds: string[];
|
||||
controllers: Assignment[];
|
||||
assignments: Assignment[];
|
||||
onChanged: () => Promise<void> | void;
|
||||
}) {
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [warnings, setWarnings] = useState<string[]>([]);
|
||||
const showForm = adding || assignments.length === 0;
|
||||
|
||||
// Binding categories need a controller to point at first.
|
||||
const isBound = category !== "access";
|
||||
const blockedNoController = isBound && controllers.length === 0;
|
||||
|
||||
return (
|
||||
<fieldset style={{ marginTop: "1rem" }}>
|
||||
<legend>{title}</legend>
|
||||
|
||||
{warnings.length > 0 && (
|
||||
<div
|
||||
style={{
|
||||
margin: "0 0 0.75rem",
|
||||
padding: "0.5rem 0.75rem",
|
||||
background: "#fef3c7",
|
||||
border: "1px solid #f59e0b",
|
||||
borderRadius: 6,
|
||||
}}
|
||||
>
|
||||
<strong style={{ color: "#92400e" }}>⚠ Saved, but action needed:</strong>
|
||||
<ul style={{ margin: "0.25rem 0 0", paddingLeft: "1.25rem", color: "#92400e" }}>
|
||||
{warnings.map((w, i) => (
|
||||
<li key={i}>{w}</li>
|
||||
))}
|
||||
</ul>
|
||||
<button type="button" onClick={() => setWarnings([])} style={{ marginTop: "0.5rem" }}>
|
||||
Dismiss
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{assignments.length > 0 && (
|
||||
<ul style={{ listStyle: "none", padding: 0, margin: "0 0 0.75rem" }}>
|
||||
{assignments.map((a) => (
|
||||
<AssignmentRow key={a.id} assignment={a} controllers={controllers} onChanged={onChanged} />
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{blockedNoController ? (
|
||||
<p style={{ color: "#b45309", margin: 0 }}>Add a controller first — a {noun} points at one of its relays.</p>
|
||||
) : showForm ? (
|
||||
<DeviceForm
|
||||
category={category}
|
||||
entries={entries}
|
||||
discoverableIds={discoverableIds}
|
||||
pushCapableIds={pushCapableIds}
|
||||
controllers={controllers}
|
||||
onSaved={async (w) => {
|
||||
setWarnings(w);
|
||||
await onChanged();
|
||||
setAdding(false);
|
||||
}}
|
||||
onCancel={assignments.length > 0 ? () => setAdding(false) : undefined}
|
||||
/>
|
||||
) : (
|
||||
<button type="button" onClick={() => setAdding(true)}>
|
||||
+ Add another {noun}
|
||||
</button>
|
||||
)}
|
||||
</fieldset>
|
||||
);
|
||||
}
|
||||
|
||||
function AssignmentRow({
|
||||
assignment,
|
||||
controllers,
|
||||
onChanged,
|
||||
}: {
|
||||
assignment: Assignment;
|
||||
controllers: Assignment[];
|
||||
onChanged: () => Promise<void> | void;
|
||||
}) {
|
||||
const [removing, setRemoving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const cfg = assignment.config as Record<string, unknown>;
|
||||
const host = typeof cfg.host === "string" ? cfg.host : null;
|
||||
|
||||
async function remove() {
|
||||
if (!confirm(`Remove this ${assignment.driverId} device?`)) return;
|
||||
setRemoving(true);
|
||||
setError(null);
|
||||
try {
|
||||
await unassignDevice(assignment.id);
|
||||
await onChanged();
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
setRemoving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<li
|
||||
style={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: "0.5rem",
|
||||
padding: "0.4rem 0.5rem",
|
||||
borderBottom: "1px solid #eee",
|
||||
}}
|
||||
>
|
||||
<strong>{assignment.driverId}</strong>
|
||||
{host && <span style={{ color: "#666" }}>{host}</span>}
|
||||
<DeviceSummary assignment={assignment} controllers={controllers} />
|
||||
{!assignment.enabled && <span style={{ color: "#b45309" }}>(disabled)</span>}
|
||||
<span style={{ flex: 1 }} />
|
||||
{error && <span style={{ color: "crimson" }}>{error}</span>}
|
||||
<button type="button" onClick={remove} disabled={removing}>
|
||||
{removing ? "Removing…" : "Remove"}
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
/** Inline summary of an assignment's direction/binding for the list. */
|
||||
function DeviceSummary({ assignment, controllers }: { assignment: Assignment; controllers: Assignment[] }) {
|
||||
const cfg = assignment.config as Record<string, unknown>;
|
||||
if (assignment.category === "access") {
|
||||
const relays = Array.isArray(cfg.relays) ? (cfg.relays as RelaySpec[]) : [];
|
||||
if (relays.length === 0) return <em style={{ color: "#b45309" }}>no relays set</em>;
|
||||
return (
|
||||
<span style={{ display: "flex", gap: "0.35rem" }}>
|
||||
{relays.map((r) => (
|
||||
<DirectionBadge key={r.relay} direction={r.direction} label={`R${r.relay}${r.button ? `·btn${r.button}` : ""}`} />
|
||||
))}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
// Bound device: show controller + relay it points at, with inherited direction.
|
||||
const controllerId = typeof cfg.controllerId === "string" ? cfg.controllerId : null;
|
||||
const relay = typeof cfg.relay === "number" ? cfg.relay : null;
|
||||
if (!controllerId || relay == null) return <em style={{ color: "#b45309" }}>unbound</em>;
|
||||
const controller = controllers.find((c) => c.id === controllerId);
|
||||
const spec = controller
|
||||
? (((controller.config as Record<string, unknown>).relays as RelaySpec[]) ?? []).find((r) => r.relay === relay)
|
||||
: undefined;
|
||||
return (
|
||||
<DirectionBadge
|
||||
direction={spec?.direction ?? "both"}
|
||||
label={`${controller ? controller.driverId : "?"} · R${relay}`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DeviceForm({
|
||||
category,
|
||||
entries,
|
||||
discoverableIds,
|
||||
pushCapableIds,
|
||||
controllers,
|
||||
onSaved,
|
||||
onCancel,
|
||||
}: {
|
||||
category: DeviceCategory;
|
||||
entries: CatalogEntry[];
|
||||
discoverableIds: string[];
|
||||
pushCapableIds: string[];
|
||||
controllers: Assignment[];
|
||||
onSaved: (warnings: string[]) => Promise<void> | void;
|
||||
onCancel?: () => void;
|
||||
}) {
|
||||
const [selectedId, setSelectedId] = useState<string>("");
|
||||
const selected = entries.find((e) => e.id === selectedId);
|
||||
const canDiscover = selected != null && discoverableIds.includes(selected.id);
|
||||
const pushesToBackend = selected != null && pushCapableIds.includes(selected.id);
|
||||
const isController = category === "access";
|
||||
|
||||
// Config values (auto-filled by discovery, editable by hand).
|
||||
const [config, setConfig] = useState<Record<string, string | number>>({});
|
||||
// Controllers: the relay map (which relay = entry/exit/both, + entry button terminal).
|
||||
const [relays, setRelays] = useState<RelaySpec[]>([{ relay: 1, direction: "both" }]);
|
||||
// Bound devices: which controller + relay this device sits at.
|
||||
const [controllerId, setControllerId] = useState<string>("");
|
||||
const [boundRelay, setBoundRelay] = useState<number | "">("");
|
||||
|
||||
const [tested, setTested] = useState<TestResult | null>(null);
|
||||
const [testing, setTesting] = useState(false);
|
||||
const [testError, setTestError] = useState<string | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [saveError, setSaveError] = useState<string | null>(null);
|
||||
const [found, setFound] = useState<DiscoveredDevice[] | null>(null);
|
||||
const [scanning, setScanning] = useState(false);
|
||||
const [scanError, setScanError] = useState<string | null>(null);
|
||||
|
||||
const [backendIps, setBackendIps] = useState<BackendIpCandidate[] | null>(null);
|
||||
const [backendIp, setBackendIp] = useState<string>("");
|
||||
|
||||
const testedHost = tested ? String(mergedScalarConfig().host ?? "") : "";
|
||||
useEffect(() => {
|
||||
if (!testedHost || !pushesToBackend) {
|
||||
setBackendIps(null);
|
||||
return;
|
||||
}
|
||||
let live = true;
|
||||
fetchBackendIps(testedHost)
|
||||
.then(({ candidates }) => {
|
||||
if (!live) return;
|
||||
setBackendIps(candidates);
|
||||
setBackendIp((cur) => cur || candidates.find((c) => c.onDeviceSubnet)?.ip || "");
|
||||
})
|
||||
.catch(() => {
|
||||
if (live) setBackendIps(null);
|
||||
});
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [testedHost, pushesToBackend]);
|
||||
|
||||
function selectDriver(id: string) {
|
||||
setSelectedId(id);
|
||||
setConfig({});
|
||||
setFound(null);
|
||||
resetStatus();
|
||||
}
|
||||
|
||||
async function scan() {
|
||||
if (!selected) return;
|
||||
setScanning(true);
|
||||
@@ -102,15 +360,86 @@ function CategoryPicker({
|
||||
|
||||
function applyDiscovered(d: DiscoveredDevice) {
|
||||
setConfig((c) => ({ ...c, ...(d.config as Record<string, string | number>) }));
|
||||
resetStatus();
|
||||
}
|
||||
|
||||
/** Scalar config the user entered, merged over driver defaults (for test/push-IP). */
|
||||
function mergedScalarConfig(): Record<string, string | number> {
|
||||
const out: Record<string, string | number> = {};
|
||||
for (const f of selected?.configFields ?? []) {
|
||||
const v = config[f.key] ?? (f.default as string | number | undefined);
|
||||
if (v !== undefined && v !== "") out[f.key] = v;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Full config to persist: scalars + the model's direction/binding fields. */
|
||||
function mergedConfig(): DeviceConfig {
|
||||
const out: DeviceConfig = { ...mergedScalarConfig() };
|
||||
if (isController) {
|
||||
out.relays = relays.map((r) => ({
|
||||
relay: r.relay,
|
||||
direction: r.direction,
|
||||
...(r.button ? { button: r.button } : {}),
|
||||
}));
|
||||
} else if (controllerId && boundRelay !== "") {
|
||||
out.controllerId = controllerId;
|
||||
out.relay = boundRelay;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function resetStatus() {
|
||||
setTested(null);
|
||||
setTestError(null);
|
||||
setSaveError(null);
|
||||
}
|
||||
|
||||
async function test() {
|
||||
if (!selected) return;
|
||||
setTesting(true);
|
||||
setTestError(null);
|
||||
setTested(null);
|
||||
try {
|
||||
setTested(await testDevice(selected.id, mergedScalarConfig()));
|
||||
} catch (e) {
|
||||
setTestError((e as Error).message);
|
||||
} finally {
|
||||
setTesting(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (!selected) return;
|
||||
// Bound devices must point at a controller relay (binding is optional in the
|
||||
// model with a fallback, but the wizard guides the admin to bind explicitly).
|
||||
if (!isController && (!controllerId || boundRelay === "")) {
|
||||
setSaveError("Pick the controller and relay this device sits at.");
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
setSaveError(null);
|
||||
try {
|
||||
const result = await assignDevice({
|
||||
category,
|
||||
driverId: selected.id,
|
||||
config: mergedConfig(),
|
||||
...(backendIp ? { backendIp } : {}),
|
||||
});
|
||||
await onSaved(result.warnings ?? []);
|
||||
} catch (e) {
|
||||
setSaveError((e as Error).message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<fieldset style={{ marginTop: "1rem" }}>
|
||||
<legend>{title}</legend>
|
||||
<div style={{ padding: "0.5rem", background: "#fafafa", borderRadius: 6 }}>
|
||||
{entries.length === 0 ? (
|
||||
<em>No drivers registered.</em>
|
||||
) : (
|
||||
<select value={selectedId ?? ""} onChange={(e) => onSelect(e.target.value)}>
|
||||
<select value={selectedId} onChange={(e) => selectDriver(e.target.value)}>
|
||||
<option value="" disabled>
|
||||
Choose a device…
|
||||
</option>
|
||||
@@ -155,18 +484,275 @@ function CategoryPicker({
|
||||
<label>
|
||||
{f.label}
|
||||
{f.required ? " *" : ""}{" "}
|
||||
<input
|
||||
type={f.type === "secret" ? "password" : f.type === "number" || f.type === "port" ? "number" : "text"}
|
||||
value={config[f.key] ?? (f.default as string | number | undefined) ?? ""}
|
||||
placeholder={f.help}
|
||||
onChange={(e) => setConfig((c) => ({ ...c, [f.key]: e.target.value }))}
|
||||
/>
|
||||
{f.type === "select" ? (
|
||||
<select
|
||||
value={String(config[f.key] ?? (f.default as string | number | undefined) ?? "")}
|
||||
onChange={(e) => {
|
||||
const v = e.target.value;
|
||||
setConfig((c) => ({ ...c, [f.key]: v }));
|
||||
resetStatus();
|
||||
}}
|
||||
>
|
||||
{f.options?.map((o) => (
|
||||
<option key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
) : (
|
||||
<input
|
||||
type={f.type === "secret" ? "password" : f.type === "number" || f.type === "port" ? "number" : "text"}
|
||||
value={config[f.key] ?? (f.default as string | number | undefined) ?? ""}
|
||||
placeholder={f.help}
|
||||
onChange={(e) => {
|
||||
const v = e.target.value;
|
||||
setConfig((c) => ({ ...c, [f.key]: v }));
|
||||
resetStatus();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</label>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* CONTROLLER: the relay map — which relay opens which direction + entry button. */}
|
||||
{isController && <RelayEditor relays={relays} onChange={setRelays} />}
|
||||
|
||||
{/* BOUND device: which controller + relay it sits at. */}
|
||||
{!isController && (
|
||||
<BindingPicker
|
||||
controllers={controllers}
|
||||
controllerId={controllerId}
|
||||
relay={boundRelay}
|
||||
onControllerChange={(id) => {
|
||||
setControllerId(id);
|
||||
setBoundRelay("");
|
||||
}}
|
||||
onRelayChange={setBoundRelay}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Test (no save/no device change) then Save (configures + persists). */}
|
||||
<div style={{ marginTop: "0.75rem", display: "flex", gap: "0.5rem", alignItems: "center" }}>
|
||||
<button type="button" onClick={test} disabled={testing}>
|
||||
{testing ? "Testing…" : "Test connection"}
|
||||
</button>
|
||||
<button type="button" onClick={save} disabled={saving}>
|
||||
{saving ? "Saving…" : "Save & configure"}
|
||||
</button>
|
||||
{onCancel && (
|
||||
<button type="button" onClick={onCancel} disabled={saving}>
|
||||
Cancel
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{testError && <p style={{ color: "crimson", margin: "0.5rem 0 0" }}>Test failed: {testError}</p>}
|
||||
{tested && (
|
||||
<div style={{ margin: "0.5rem 0 0" }}>
|
||||
<div>
|
||||
Device: <HealthBadge status={tested.health.status} />
|
||||
{tested.health.detail && <span style={{ color: "#666" }}> — {tested.health.detail}</span>}
|
||||
</div>
|
||||
{tested.preconditions.ok ? (
|
||||
<div style={{ color: "#16a34a" }}>● preconditions OK</div>
|
||||
) : (
|
||||
tested.preconditions.issues.map((i) => (
|
||||
<div key={i.key} style={{ color: "#d97706" }}>
|
||||
⚠ {i.message}
|
||||
{i.fixable && <span style={{ color: "#666" }}> (auto-fixed on save)</span>}
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{backendIps && backendIps.length > 0 && (
|
||||
<div style={{ margin: "0.5rem 0 0" }}>
|
||||
<label>
|
||||
Backend push IP{" "}
|
||||
<select value={backendIp} onChange={(e) => setBackendIp(e.target.value)}>
|
||||
{!backendIps.some((c) => c.onDeviceSubnet) && (
|
||||
<option value="" disabled>
|
||||
Choose an address…
|
||||
</option>
|
||||
)}
|
||||
{backendIps.map((c) => (
|
||||
<option key={c.ip} value={c.ip}>
|
||||
{c.ip} ({c.iface}){c.onDeviceSubnet ? " — on device subnet" : ""}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{!backendIps.some((c) => c.onDeviceSubnet) && (
|
||||
<span style={{ marginLeft: 8, color: "#d97706" }}>
|
||||
⚠ no NIC on the device's subnet — the device may not reach the backend
|
||||
</span>
|
||||
)}
|
||||
<p style={{ margin: "0.25rem 0 0", color: "#666", fontSize: "0.85em" }}>
|
||||
The address this device will POST input events to.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{saveError && <p style={{ color: "crimson", margin: "0.5rem 0 0" }}>Save failed: {saveError}</p>}
|
||||
</div>
|
||||
)}
|
||||
</fieldset>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Controller relay map editor: each row = a relay + its direction + (optional)
|
||||
* the input terminal its entry button is wired to. */
|
||||
function RelayEditor({ relays, onChange }: { relays: RelaySpec[]; onChange: (r: RelaySpec[]) => void }) {
|
||||
function update(i: number, patch: Partial<RelaySpec>) {
|
||||
onChange(relays.map((r, idx) => (idx === i ? { ...r, ...patch } : r)));
|
||||
}
|
||||
function add() {
|
||||
const nextRelay = (relays.reduce((m, r) => Math.max(m, r.relay), 0) || 0) + 1;
|
||||
onChange([...relays, { relay: nextRelay, direction: "both" }]);
|
||||
}
|
||||
function remove(i: number) {
|
||||
onChange(relays.filter((_, idx) => idx !== i));
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ margin: "0.5rem 0", padding: "0.5rem", background: "#f3f4f6", borderRadius: 6 }}>
|
||||
<strong style={{ fontSize: "0.9em" }}>Relays on this controller</strong>
|
||||
<p style={{ margin: "0.15rem 0 0.5rem", color: "#666", fontSize: "0.8em" }}>
|
||||
Each relay opens one barrier. Set its direction; for transient entry, set which input
|
||||
terminal the entry button is wired to.
|
||||
</p>
|
||||
{relays.map((r, i) => (
|
||||
<div key={i} style={{ display: "flex", gap: "0.5rem", alignItems: "center", margin: "0.25rem 0" }}>
|
||||
<label>
|
||||
Relay{" "}
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
value={r.relay}
|
||||
style={{ width: "3.5rem" }}
|
||||
onChange={(e) => update(i, { relay: Number(e.target.value) })}
|
||||
/>
|
||||
</label>
|
||||
<select value={r.direction} onChange={(e) => update(i, { direction: e.target.value as Direction })}>
|
||||
{(["entry", "exit", "both"] as Direction[]).map((d) => (
|
||||
<option key={d} value={d}>
|
||||
{DIRECTION_LABELS[d]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{(r.direction === "entry" || r.direction === "both") && (
|
||||
<label>
|
||||
Entry button on terminal{" "}
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
value={r.button ?? ""}
|
||||
placeholder="—"
|
||||
style={{ width: "3.5rem" }}
|
||||
onChange={(e) => update(i, { button: e.target.value === "" ? undefined : Number(e.target.value) })}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
{relays.length > 1 && (
|
||||
<button type="button" onClick={() => remove(i)}>
|
||||
✕
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
<button type="button" onClick={add} style={{ marginTop: "0.25rem" }}>
|
||||
+ Add relay
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Binding picker for readers/cameras/printers: choose the controller + relay this
|
||||
* device sits at. Direction is inherited from the chosen relay (shown). */
|
||||
function BindingPicker({
|
||||
controllers,
|
||||
controllerId,
|
||||
relay,
|
||||
onControllerChange,
|
||||
onRelayChange,
|
||||
}: {
|
||||
controllers: Assignment[];
|
||||
controllerId: string;
|
||||
relay: number | "";
|
||||
onControllerChange: (id: string) => void;
|
||||
onRelayChange: (relay: number) => void;
|
||||
}) {
|
||||
const controller = controllers.find((c) => c.id === controllerId);
|
||||
const relays: RelaySpec[] = controller
|
||||
? (((controller.config as Record<string, unknown>).relays as RelaySpec[]) ?? [])
|
||||
: [];
|
||||
const chosen = relays.find((r) => r.relay === relay);
|
||||
|
||||
return (
|
||||
<div style={{ margin: "0.5rem 0", padding: "0.5rem", background: "#f3f4f6", borderRadius: 6 }}>
|
||||
<strong style={{ fontSize: "0.9em" }}>Which barrier does this device serve?</strong>
|
||||
<div style={{ display: "flex", gap: "0.5rem", alignItems: "center", marginTop: "0.35rem", flexWrap: "wrap" }}>
|
||||
<label>
|
||||
Controller{" "}
|
||||
<select value={controllerId} onChange={(e) => onControllerChange(e.target.value)}>
|
||||
<option value="" disabled>
|
||||
Choose…
|
||||
</option>
|
||||
{controllers.map((c) => {
|
||||
const host = (c.config as Record<string, unknown>).host;
|
||||
return (
|
||||
<option key={c.id} value={c.id}>
|
||||
{c.driverId}
|
||||
{typeof host === "string" ? ` (${host})` : ""}
|
||||
</option>
|
||||
);
|
||||
})}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Relay{" "}
|
||||
<select
|
||||
value={relay === "" ? "" : String(relay)}
|
||||
disabled={!controller}
|
||||
onChange={(e) => onRelayChange(Number(e.target.value))}
|
||||
>
|
||||
<option value="" disabled>
|
||||
Choose…
|
||||
</option>
|
||||
{relays.map((r) => (
|
||||
<option key={r.relay} value={r.relay}>
|
||||
Relay {r.relay} ({DIRECTION_LABELS[r.direction]})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{chosen && <DirectionBadge direction={chosen.direction} label={`inherits ${chosen.direction}`} />}
|
||||
</div>
|
||||
{controller && relays.length === 0 && (
|
||||
<p style={{ margin: "0.35rem 0 0", color: "#b45309", fontSize: "0.85em" }}>
|
||||
This controller has no relays configured.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DirectionBadge({ direction, label }: { direction: Direction; label?: string }) {
|
||||
const color = direction === "entry" ? "#15803d" : direction === "exit" ? "#b45309" : "#6b7280";
|
||||
return (
|
||||
<span
|
||||
style={{
|
||||
color,
|
||||
border: `1px solid ${color}`,
|
||||
borderRadius: 4,
|
||||
padding: "0 0.35rem",
|
||||
fontSize: "0.75em",
|
||||
fontWeight: 600,
|
||||
}}
|
||||
>
|
||||
{label ?? direction}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { closeShift, fetchShift, openShift, type ShiftReport } from "./api.js";
|
||||
|
||||
// Manned-mode shift control. Start/End are explicit (not time-based — see
|
||||
// wiki/concepts/shift.md). End Shift signs + prints a Z-report and shows the
|
||||
// totals. Available to cashier/operator/admin (readonly has no shift).
|
||||
|
||||
const money = (m: number, cur: string | null) => `${(m / 100).toFixed(2)} ${cur ?? ""}`.trim();
|
||||
|
||||
export function ShiftControl() {
|
||||
const [startedAt, setStartedAt] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [report, setReport] = useState<ShiftReport | null>(null);
|
||||
const [err, setErr] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
fetchShift()
|
||||
.then((s) => setStartedAt(s.open?.startedAt ?? null))
|
||||
.catch(() => {
|
||||
/* readonly / not permitted — hide control */
|
||||
});
|
||||
}, []);
|
||||
|
||||
async function start() {
|
||||
setBusy(true);
|
||||
setErr(null);
|
||||
setReport(null);
|
||||
try {
|
||||
const { startedAt } = await openShift();
|
||||
setStartedAt(startedAt);
|
||||
} catch (e) {
|
||||
setErr((e as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
async function end() {
|
||||
setBusy(true);
|
||||
setErr(null);
|
||||
try {
|
||||
const z = await closeShift();
|
||||
setReport(z);
|
||||
setStartedAt(null);
|
||||
} catch (e) {
|
||||
setErr((e as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section style={{ marginTop: "1.5rem", padding: "0.75rem 1rem", border: "1px solid #ddd", borderRadius: 6, maxWidth: 460 }}>
|
||||
<strong>Shift:</strong>{" "}
|
||||
{startedAt ? (
|
||||
<>
|
||||
<span style={{ color: "#16a34a" }}>open</span> since {new Date(startedAt).toLocaleString()}{" "}
|
||||
<button type="button" onClick={end} disabled={busy}>
|
||||
{busy ? "Ending…" : "End shift"}
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span style={{ color: "#777" }}>not started</span>{" "}
|
||||
<button type="button" onClick={start} disabled={busy}>
|
||||
{busy ? "Starting…" : "Start shift"}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{err && <p style={{ color: "crimson", margin: "0.5rem 0 0" }}>{err}</p>}
|
||||
{report && (
|
||||
<div style={{ marginTop: "0.75rem", fontFamily: "ui-monospace, monospace", fontSize: "0.9em" }}>
|
||||
<div style={{ fontWeight: 600 }}>Z-REPORT — {report.operator}</div>
|
||||
<div>Payments: {report.paymentCount}</div>
|
||||
<div>Cash: {money(report.cashTotalMinor, report.currency)}</div>
|
||||
<div>Card: {money(report.cardTotalMinor, report.currency)}</div>
|
||||
<div style={{ color: report.printed ? "#16a34a" : "#b45309" }}>
|
||||
{report.printed ? "Printed to booth receipt." : "Recorded (no printer to print to)."}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { fetchOccupancy, fetchSiteConfig, setCapacity, type Occupancy } from "./api.js";
|
||||
|
||||
// Live occupancy + capacity. Occupancy is shown to everyone (it's a fold over the
|
||||
// signed ledger); the capacity field is admin-editable. The FULL gate (refuse
|
||||
// transient entry at capacity) is enforced server-side in the entry flow.
|
||||
// See wiki/concepts/capacity-occupancy.md.
|
||||
|
||||
export function SiteSettings({ canEdit }: { canEdit: boolean }) {
|
||||
const [occ, setOcc] = useState<Occupancy | null>(null);
|
||||
const [capInput, setCapInput] = useState("");
|
||||
const [msg, setMsg] = useState<string | null>(null);
|
||||
|
||||
function reload() {
|
||||
fetchOccupancy().then(setOcc).catch(() => {});
|
||||
}
|
||||
useEffect(() => {
|
||||
reload();
|
||||
fetchSiteConfig()
|
||||
.then((c) => setCapInput(c.capacity == null ? "" : String(c.capacity)))
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
async function save() {
|
||||
setMsg(null);
|
||||
const raw = capInput.trim();
|
||||
const capacity = raw === "" ? null : Math.round(Number(raw));
|
||||
try {
|
||||
await setCapacity(capacity);
|
||||
reload();
|
||||
setMsg("Capacity saved.");
|
||||
} catch (e) {
|
||||
setMsg((e as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section style={{ marginTop: "1.5rem", padding: "0.75rem 1rem", border: "1px solid #ddd", borderRadius: 6, maxWidth: 460 }}>
|
||||
<strong>Occupancy:</strong>{" "}
|
||||
{occ == null ? (
|
||||
"…"
|
||||
) : (
|
||||
<>
|
||||
<span style={{ fontWeight: 600 }}>{occ.count}</span>
|
||||
{occ.capacity != null ? ` / ${occ.capacity}` : " (no capacity set)"}
|
||||
{occ.capacity != null && (
|
||||
<span style={{ color: "#666" }}> · {occ.free} free</span>
|
||||
)}
|
||||
{occ.full && <span style={{ color: "crimson", marginLeft: "0.5rem", fontWeight: 600 }}>FULL</span>}{" "}
|
||||
<button type="button" onClick={reload} style={{ marginLeft: "0.5rem" }}>↻</button>
|
||||
</>
|
||||
)}
|
||||
{canEdit && (
|
||||
<div style={{ marginTop: "0.6rem" }}>
|
||||
<label>
|
||||
Capacity (blank = no limit):{" "}
|
||||
<input value={capInput} onChange={(e) => setCapInput(e.target.value)} style={{ width: 80 }} placeholder="e.g. 120" />
|
||||
</label>{" "}
|
||||
<button type="button" onClick={save}>Save</button>
|
||||
{msg && <span style={{ marginLeft: "0.5rem", color: "#555" }}>{msg}</span>}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import {
|
||||
ApiError,
|
||||
fetchTariff,
|
||||
publishTariffVersion,
|
||||
type TariffBlock,
|
||||
type TariffStructure,
|
||||
type TariffState,
|
||||
} from "./api.js";
|
||||
|
||||
// Tariff composer — the admin builds + edits the rate card at runtime. Publishing
|
||||
// creates a new IMMUTABLE version (the active card); old versions are kept so past
|
||||
// sessions reprice correctly. Amounts are entered in major units (e.g. euros) for
|
||||
// usability and converted to integer minor units on submit. See wiki/concepts/tariff.md.
|
||||
|
||||
// Editable form mirror of TariffStructure, but money in major-unit strings.
|
||||
interface BlockForm {
|
||||
uptoMin: string; // "" = open-ended (last block)
|
||||
price: string; // major units, e.g. "2.00"
|
||||
}
|
||||
interface FormState {
|
||||
currency: string;
|
||||
gracePeriodEntryMin: string;
|
||||
incrementMin: string;
|
||||
dailyCap: string; // "" = no cap
|
||||
lostTicket: string;
|
||||
gracePeriodExitMin: string;
|
||||
blocks: BlockForm[];
|
||||
}
|
||||
|
||||
const toMinor = (major: string): number => Math.round(parseFloat(major || "0") * 100);
|
||||
const toMajor = (minor: number): string => (minor / 100).toFixed(2);
|
||||
|
||||
function emptyForm(): FormState {
|
||||
return {
|
||||
currency: "EUR",
|
||||
gracePeriodEntryMin: "15",
|
||||
incrementMin: "60",
|
||||
dailyCap: "",
|
||||
lostTicket: "20.00",
|
||||
gracePeriodExitMin: "15",
|
||||
blocks: [{ uptoMin: "60", price: "2.00" }, { uptoMin: "", price: "1.00" }],
|
||||
};
|
||||
}
|
||||
|
||||
function formFromActive(s: TariffState): FormState {
|
||||
const v = s.active;
|
||||
if (!v) return emptyForm();
|
||||
const st = v.structure;
|
||||
return {
|
||||
currency: v.currency,
|
||||
gracePeriodEntryMin: String(st.gracePeriodEntryMin),
|
||||
incrementMin: String(st.incrementMin),
|
||||
dailyCap: st.dailyCapMinor == null ? "" : toMajor(st.dailyCapMinor),
|
||||
lostTicket: toMajor(st.lostTicketMinor),
|
||||
gracePeriodExitMin: String(st.gracePeriodExitMin),
|
||||
blocks: st.blocks.map((b) => ({
|
||||
uptoMin: b.uptoMin == null ? "" : String(b.uptoMin),
|
||||
price: toMajor(b.priceMinorPerIncrement),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
function toStructure(f: FormState): TariffStructure {
|
||||
const blocks: TariffBlock[] = f.blocks.map((b) => ({
|
||||
uptoMin: b.uptoMin.trim() === "" ? null : Math.round(Number(b.uptoMin)),
|
||||
priceMinorPerIncrement: toMinor(b.price),
|
||||
}));
|
||||
return {
|
||||
gracePeriodEntryMin: Math.round(Number(f.gracePeriodEntryMin)),
|
||||
incrementMin: Math.round(Number(f.incrementMin)),
|
||||
blocks,
|
||||
dailyCapMinor: f.dailyCap.trim() === "" ? null : toMinor(f.dailyCap),
|
||||
lostTicketMinor: toMinor(f.lostTicket),
|
||||
gracePeriodExitMin: Math.round(Number(f.gracePeriodExitMin)),
|
||||
overstay: "reprice",
|
||||
};
|
||||
}
|
||||
|
||||
export function TariffComposer() {
|
||||
const [state, setState] = useState<TariffState | null>(null);
|
||||
const [form, setForm] = useState<FormState>(emptyForm);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [msg, setMsg] = useState<{ kind: "ok" | "err"; text: string } | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
fetchTariff()
|
||||
.then((s) => {
|
||||
setState(s);
|
||||
setForm(formFromActive(s));
|
||||
})
|
||||
.catch((e) => setMsg({ kind: "err", text: (e as Error).message }));
|
||||
}, []);
|
||||
|
||||
function set<K extends keyof FormState>(key: K, value: FormState[K]) {
|
||||
setForm((f) => ({ ...f, [key]: value }));
|
||||
}
|
||||
function setBlock(i: number, patch: Partial<BlockForm>) {
|
||||
setForm((f) => ({ ...f, blocks: f.blocks.map((b, j) => (j === i ? { ...b, ...patch } : b)) }));
|
||||
}
|
||||
function addBlock() {
|
||||
setForm((f) => ({ ...f, blocks: [...f.blocks, { uptoMin: "", price: "0.00" }] }));
|
||||
}
|
||||
function removeBlock(i: number) {
|
||||
setForm((f) => ({ ...f, blocks: f.blocks.filter((_, j) => j !== i) }));
|
||||
}
|
||||
|
||||
async function publish() {
|
||||
setSaving(true);
|
||||
setMsg(null);
|
||||
try {
|
||||
await publishTariffVersion({ currency: form.currency.trim().toUpperCase(), structure: toStructure(form) });
|
||||
const fresh = await fetchTariff();
|
||||
setState(fresh);
|
||||
setMsg({ kind: "ok", text: "New tariff version published — it's now the active rate card." });
|
||||
} catch (e) {
|
||||
const text =
|
||||
e instanceof ApiError && (e as ApiError & { problems?: string[] }).problems
|
||||
? `${e.message}: ${((e as ApiError & { problems?: string[] }).problems ?? []).join("; ")}`
|
||||
: (e as Error).message;
|
||||
setMsg({ kind: "err", text });
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section style={{ marginTop: "2rem" }}>
|
||||
<h2>Tariff</h2>
|
||||
{!state?.active ? (
|
||||
<p style={{ color: "#b45309" }}>
|
||||
No rate card published yet — the pay station can't charge until you publish one.
|
||||
</p>
|
||||
) : (
|
||||
<p style={{ color: "#555" }}>
|
||||
Active since {new Date(state.active.effectiveFrom).toLocaleString()} ·{" "}
|
||||
{state.versions.length} version(s) in history. Publishing creates a new version; past
|
||||
sessions keep their original pricing.
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div style={{ display: "grid", gridTemplateColumns: "max-content 1fr", gap: "0.4rem 0.75rem", alignItems: "center", maxWidth: 460 }}>
|
||||
<label>Currency</label>
|
||||
<input value={form.currency} onChange={(e) => set("currency", e.target.value)} maxLength={3} style={{ width: 80 }} />
|
||||
<label>Free entry grace (min)</label>
|
||||
<input value={form.gracePeriodEntryMin} onChange={(e) => set("gracePeriodEntryMin", e.target.value)} />
|
||||
<label>Billing increment (min)</label>
|
||||
<input value={form.incrementMin} onChange={(e) => set("incrementMin", e.target.value)} />
|
||||
<label>Daily cap (blank = none)</label>
|
||||
<input value={form.dailyCap} onChange={(e) => set("dailyCap", e.target.value)} placeholder="e.g. 12.00" />
|
||||
<label>Lost-ticket fee</label>
|
||||
<input value={form.lostTicket} onChange={(e) => set("lostTicket", e.target.value)} />
|
||||
<label>Exit walk-back grace (min)</label>
|
||||
<input value={form.gracePeriodExitMin} onChange={(e) => set("gracePeriodExitMin", e.target.value)} />
|
||||
</div>
|
||||
|
||||
<h3 style={{ marginBottom: "0.25rem" }}>Rate blocks</h3>
|
||||
<p style={{ color: "#777", margin: "0 0 0.5rem", fontSize: "0.9em" }}>
|
||||
Consumed in order as time accrues. "Up to (min)" is the block's upper bound; leave the last
|
||||
block's bound blank for "thereafter". Price is per billing increment.
|
||||
</p>
|
||||
<table style={{ borderCollapse: "collapse" }}>
|
||||
<thead>
|
||||
<tr style={{ textAlign: "left", color: "#555" }}>
|
||||
<th style={{ padding: "0 0.5rem" }}>Up to (min)</th>
|
||||
<th style={{ padding: "0 0.5rem" }}>Price / increment</th>
|
||||
<th />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{form.blocks.map((b, i) => (
|
||||
<tr key={i}>
|
||||
<td style={{ padding: "0.15rem 0.5rem" }}>
|
||||
<input
|
||||
value={b.uptoMin}
|
||||
onChange={(e) => setBlock(i, { uptoMin: e.target.value })}
|
||||
placeholder={i === form.blocks.length - 1 ? "thereafter" : "e.g. 60"}
|
||||
style={{ width: 110 }}
|
||||
/>
|
||||
</td>
|
||||
<td style={{ padding: "0.15rem 0.5rem" }}>
|
||||
<input value={b.price} onChange={(e) => setBlock(i, { price: e.target.value })} style={{ width: 90 }} />
|
||||
</td>
|
||||
<td>
|
||||
<button type="button" onClick={() => removeBlock(i)} disabled={form.blocks.length <= 1}>
|
||||
Remove
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
<button type="button" onClick={addBlock} style={{ marginTop: "0.4rem" }}>
|
||||
+ Add block
|
||||
</button>
|
||||
|
||||
<div style={{ marginTop: "1rem" }}>
|
||||
<button type="button" onClick={publish} disabled={saving}>
|
||||
{saving ? "Publishing…" : "Publish new version"}
|
||||
</button>
|
||||
</div>
|
||||
{msg && (
|
||||
<p style={{ color: msg.kind === "ok" ? "#16a34a" : "crimson", marginTop: "0.5rem" }}>{msg.text}</p>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
+221
-7
@@ -96,6 +96,8 @@ export type DeviceCategory = "access" | "reader" | "camera" | "printer";
|
||||
export type Catalog = Record<DeviceCategory, CatalogEntry[]> & {
|
||||
/** Driver ids that support LAN discovery. */
|
||||
discoverable: string[];
|
||||
/** Driver ids that push to the backend (need a backend IP at assign time). */
|
||||
pushCapable: string[];
|
||||
};
|
||||
|
||||
export function fetchCatalog(): Promise<Catalog> {
|
||||
@@ -110,7 +112,7 @@ export interface DiscoveredDevice {
|
||||
health: { status: string; detail?: string };
|
||||
}
|
||||
|
||||
/** Scan the LAN for devices a driver can discover (e.g. UHPPOTE). Admin-only. */
|
||||
/** Scan the LAN for devices a driver can discover. Admin-only. */
|
||||
export async function discoverDevices(driverId: string): Promise<DiscoveredDevice[]> {
|
||||
const body = await apiFetch<{ devices: DiscoveredDevice[] }>(
|
||||
`/api/setup/discover/${driverId}`,
|
||||
@@ -118,13 +120,225 @@ export async function discoverDevices(driverId: string): Promise<DiscoveredDevic
|
||||
return body.devices;
|
||||
}
|
||||
|
||||
export interface AssignBody {
|
||||
lane: number;
|
||||
category: DeviceCategory;
|
||||
driverId: string;
|
||||
config: Record<string, string | number | boolean>;
|
||||
export type ConfigValue =
|
||||
| string
|
||||
| number
|
||||
| boolean
|
||||
| null
|
||||
| ConfigValue[]
|
||||
| { [k: string]: ConfigValue };
|
||||
export type DeviceConfig = Record<string, ConfigValue>;
|
||||
|
||||
/** Direction a barrier/relay (or a device bound to it) serves. */
|
||||
export type Direction = "entry" | "exit" | "both";
|
||||
|
||||
/** One relay on an access controller: which barrier it opens, in which direction,
|
||||
* and (optionally) the input terminal its entry button is wired to. */
|
||||
export interface RelaySpec {
|
||||
relay: number;
|
||||
direction: Direction;
|
||||
/** Input terminal of the entry button that fires this relay (transient entry). */
|
||||
button?: number;
|
||||
}
|
||||
|
||||
export function assignDevice(body: AssignBody): Promise<unknown> {
|
||||
export interface TestResult {
|
||||
health: { status: string; detail?: string };
|
||||
preconditions: {
|
||||
ok: boolean;
|
||||
issues: { key: string; message: string; fixable: boolean }[];
|
||||
};
|
||||
}
|
||||
|
||||
/** Test a device config (reachability + preconditions) without saving. */
|
||||
export function testDevice(driverId: string, config: DeviceConfig): Promise<TestResult> {
|
||||
return apiFetch<TestResult>("/api/setup/test", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ driverId, config }),
|
||||
});
|
||||
}
|
||||
|
||||
export interface BackendIpCandidate {
|
||||
ip: string;
|
||||
iface: string;
|
||||
onDeviceSubnet: boolean;
|
||||
}
|
||||
|
||||
/** Local IPs the device could push to (on-subnet first), for the wizard to
|
||||
* pre-fill/override. Matters on multi-NIC hosts. */
|
||||
export function fetchBackendIps(
|
||||
host: string,
|
||||
): Promise<{ candidates: BackendIpCandidate[]; port: number }> {
|
||||
return apiFetch(`/api/setup/backend-ips?host=${encodeURIComponent(host)}`);
|
||||
}
|
||||
|
||||
export interface AssignBody {
|
||||
category: DeviceCategory;
|
||||
driverId: string;
|
||||
// Direction/binding lives in config: access → config.relays=[{relay,direction,button?}];
|
||||
// reader/camera → config.controllerId + config.relay.
|
||||
config: DeviceConfig;
|
||||
/** Backend IP the device should push to (overrides auto-pick). */
|
||||
backendIp?: string;
|
||||
}
|
||||
|
||||
/** Save + configure the device (preconditions, push setup), then persist. */
|
||||
export function assignDevice(body: AssignBody): Promise<AssignResult> {
|
||||
return apiFetch("/api/setup/assign", { method: "POST", body: JSON.stringify(body) });
|
||||
}
|
||||
|
||||
/** A persisted device assignment (one per instance; machine-only secrets stripped). */
|
||||
export interface Assignment {
|
||||
id: string;
|
||||
category: DeviceCategory;
|
||||
driverId: string;
|
||||
config: DeviceConfig;
|
||||
enabled: boolean;
|
||||
createdAt?: string;
|
||||
}
|
||||
|
||||
/** Assign response = the saved assignment plus any residual-risk warnings
|
||||
* (e.g. "string protocol could not be disabled — finish in the device web UI"). */
|
||||
export interface AssignResult extends Assignment {
|
||||
warnings?: string[];
|
||||
}
|
||||
|
||||
export interface SetupState {
|
||||
completedAt: string | null;
|
||||
assignments: Assignment[];
|
||||
}
|
||||
|
||||
/** Current setup status + all assigned device instances. */
|
||||
export function fetchState(): Promise<SetupState> {
|
||||
return apiFetch<SetupState>("/api/setup/state");
|
||||
}
|
||||
|
||||
/** Remove one assigned device instance by id. */
|
||||
export function unassignDevice(id: string): Promise<void> {
|
||||
return apiFetch(`/api/setup/assign/${id}`, { method: "DELETE" });
|
||||
}
|
||||
|
||||
// --- Tariff composer ------------------------------------------------------
|
||||
|
||||
export interface TariffBlock {
|
||||
uptoMin: number | null;
|
||||
priceMinorPerIncrement: number;
|
||||
}
|
||||
export interface TariffStructure {
|
||||
gracePeriodEntryMin: number;
|
||||
incrementMin: number;
|
||||
blocks: TariffBlock[];
|
||||
dailyCapMinor: number | null;
|
||||
lostTicketMinor: number;
|
||||
gracePeriodExitMin: number;
|
||||
overstay: "reprice";
|
||||
}
|
||||
export interface TariffVersion {
|
||||
id: string;
|
||||
tariffId: string;
|
||||
effectiveFrom: string;
|
||||
currency: string;
|
||||
structure: TariffStructure;
|
||||
createdBy?: string | null;
|
||||
createdAt?: string;
|
||||
}
|
||||
export interface TariffState {
|
||||
tariffId: string;
|
||||
active: TariffVersion | null;
|
||||
versions: TariffVersion[];
|
||||
}
|
||||
|
||||
export function fetchTariff(): Promise<TariffState> {
|
||||
return apiFetch<TariffState>("/api/tariff");
|
||||
}
|
||||
|
||||
/** Publish a new immutable tariff version (becomes the active rate card). */
|
||||
export function publishTariffVersion(body: {
|
||||
currency: string;
|
||||
structure: TariffStructure;
|
||||
effectiveFrom?: string;
|
||||
}): Promise<TariffVersion> {
|
||||
return apiFetch("/api/tariff/versions", { method: "POST", body: JSON.stringify(body) });
|
||||
}
|
||||
|
||||
// --- Permits --------------------------------------------------------------
|
||||
|
||||
export interface PermitCredential {
|
||||
kind: "rf" | "qr";
|
||||
value: string;
|
||||
}
|
||||
export interface Permit {
|
||||
id: string;
|
||||
holderName: string | null;
|
||||
contact: string | null;
|
||||
maxConcurrent: number | null;
|
||||
validFrom: string | null;
|
||||
validTo: string | null;
|
||||
status: "active" | "suspended" | "revoked";
|
||||
credentials: PermitCredential[];
|
||||
plates: string[];
|
||||
}
|
||||
export type PermitInput = Omit<Permit, "id" | "status"> & {
|
||||
status?: Permit["status"];
|
||||
};
|
||||
|
||||
export function fetchPermits(): Promise<{ permits: Permit[] }> {
|
||||
return apiFetch("/api/permits");
|
||||
}
|
||||
export function createPermit(body: PermitInput): Promise<Permit> {
|
||||
return apiFetch("/api/permits", { method: "POST", body: JSON.stringify(body) });
|
||||
}
|
||||
export function updatePermit(id: string, body: PermitInput): Promise<Permit> {
|
||||
return apiFetch(`/api/permits/${id}`, { method: "PUT", body: JSON.stringify(body) });
|
||||
}
|
||||
export function revokePermit(id: string): Promise<Permit> {
|
||||
return apiFetch(`/api/permits/${id}/revoke`, { method: "POST" });
|
||||
}
|
||||
export function deletePermit(id: string): Promise<void> {
|
||||
return apiFetch(`/api/permits/${id}`, { method: "DELETE" });
|
||||
}
|
||||
|
||||
// --- Shifts ---------------------------------------------------------------
|
||||
|
||||
export interface ShiftStatus {
|
||||
operator: string;
|
||||
open: { startedAt: string } | null;
|
||||
}
|
||||
export interface ShiftReport {
|
||||
operator: string;
|
||||
startedAt: string;
|
||||
endedAt: string;
|
||||
cashTotalMinor: number;
|
||||
cardTotalMinor: number;
|
||||
currency: string | null;
|
||||
paymentCount: number;
|
||||
printed: boolean;
|
||||
}
|
||||
|
||||
export function fetchShift(): Promise<ShiftStatus> {
|
||||
return apiFetch("/api/shift/current");
|
||||
}
|
||||
export function openShift(): Promise<{ startedAt: string }> {
|
||||
return apiFetch("/api/shift/open", { method: "POST" });
|
||||
}
|
||||
export function closeShift(): Promise<ShiftReport> {
|
||||
return apiFetch("/api/shift/close", { method: "POST" });
|
||||
}
|
||||
|
||||
// --- Site config / occupancy ----------------------------------------------
|
||||
|
||||
export interface Occupancy {
|
||||
count: number;
|
||||
capacity: number | null;
|
||||
free: number | null;
|
||||
full: boolean;
|
||||
}
|
||||
|
||||
export function fetchOccupancy(): Promise<Occupancy> {
|
||||
return apiFetch("/api/occupancy");
|
||||
}
|
||||
export function fetchSiteConfig(): Promise<{ capacity: number | null }> {
|
||||
return apiFetch("/api/site-config");
|
||||
}
|
||||
export function setCapacity(capacity: number | null): Promise<{ capacity: number | null }> {
|
||||
return apiFetch("/api/site-config", { method: "PUT", body: JSON.stringify({ capacity }) });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
[Unit]
|
||||
Description=Parking dev: pin route source addresses (WSL2 mirrored-mode fix)
|
||||
# Run after WSL has populated the mirrored interfaces/addresses.
|
||||
After=network.target wsl-pro.service
|
||||
Wants=network.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
RemainAfterExit=yes
|
||||
# Idempotent; safe to re-run. Path is the repo checkout on this dev box.
|
||||
ExecStart=/home/julian/projects/JS/parking-system/deploy/wsl-fix-route-source.sh eth1
|
||||
# Mirrored-mode addresses can land slightly after boot; one retry covers the race.
|
||||
ExecStartPost=/bin/sh -c 'sleep 3; /home/julian/projects/JS/parking-system/deploy/wsl-fix-route-source.sh eth1 || true'
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
Executable
+101
@@ -0,0 +1,101 @@
|
||||
#!/usr/bin/env bash
|
||||
# WSL2 mirrored-mode source-address fix (dev box only).
|
||||
#
|
||||
# Problem: in WSL2 mirrored networking the Windows host's interfaces — and ALL
|
||||
# their IPs — are cloned into Linux on every boot. When two device subnets land
|
||||
# on one NIC (e.g. 192.168.1.x AND 10.0.10.x on eth1), the kernel's connected
|
||||
# routes come up `scope link` with NO preferred source, and source selection can
|
||||
# pick the WRONG address (sourcing 10.0.10.x traffic from 192.168.1.123). ARP
|
||||
# still resolves (L2), so the device looks REACHABLE while every ping/TCP times
|
||||
# out. See wiki/concepts/wsl-dev-networking.md.
|
||||
#
|
||||
# Fix: for each connected `scope link` route, pin its preferred `src` to THIS
|
||||
# host's own address in that same subnet. No hardcoded IPs — derived at runtime,
|
||||
# so it also covers future device subnets. Idempotent; a no-op when nothing needs
|
||||
# fixing. Runs at boot via parking-net.service.
|
||||
#
|
||||
# Production note: the real appliance is bare-metal Linux, not WSL — there this
|
||||
# is just static networkd/netplan config. This script exists only for the dev box.
|
||||
# NB: intentionally NOT `set -e`. This is a best-effort boot fixer; an individual
|
||||
# `ip` call failing (e.g. a route not up yet) must not abort the rest.
|
||||
set -uo pipefail
|
||||
|
||||
fix_iface() {
|
||||
local iface="$1"
|
||||
# Each connected /N route on this iface that the kernel manages (proto kernel,
|
||||
# scope link) — i.e. the directly-attached subnets. Capture the full line so we
|
||||
# can preserve attributes (notably `metric`) when we replace the route.
|
||||
ip -4 route show dev "$iface" proto kernel scope link | while read -r line; do
|
||||
local subnet="${line%% *}" # e.g. "10.0.10.0/24"
|
||||
local prefix="${subnet%/*}"
|
||||
# Preserve a metric if the route has one (mirrored-mode routes carry e.g. 281);
|
||||
# replacing without it would change the route's priority.
|
||||
local metric=""
|
||||
case "$line" in *" metric "*) metric="metric ${line##* metric }";; esac
|
||||
|
||||
# Find THIS host's own address inside the same subnet — the correct src.
|
||||
local hostip=""
|
||||
local cidr
|
||||
for cidr in $(ip -4 -o addr show dev "$iface" | awk '{print $4}'); do
|
||||
if ipcalc_net "$cidr" "$subnet"; then hostip="${cidr%/*}"; break; fi
|
||||
done
|
||||
[ -n "$hostip" ] || continue
|
||||
|
||||
local current
|
||||
current=$(ip -4 route get "$prefix" 2>/dev/null | sed -n 's/.*src \([0-9.]*\).*/\1/p' | head -1)
|
||||
[ "$current" = "$hostip" ] && continue # already correct — no-op
|
||||
|
||||
# `replace` creates-or-updates, so it works whether or not the route is
|
||||
# present yet (avoids the boot-race RTNETLINK "No such file" that `change` hits).
|
||||
# Non-fatal: a single failure must not abort the whole boot fixer.
|
||||
if ip route replace "$subnet" dev "$iface" proto kernel scope link src "$hostip" $metric; then
|
||||
echo "pinned $subnet -> src $hostip (was ${current:-none})"
|
||||
else
|
||||
echo "warn: could not pin $subnet -> src $hostip" >&2
|
||||
fi
|
||||
done
|
||||
return 0
|
||||
}
|
||||
|
||||
# True if address $1 (a.b.c.d/p) is inside subnet $2 (n.n.n.0/p), same prefix len.
|
||||
ipcalc_net() {
|
||||
local addr="${1%/*}" alen="${1#*/}"
|
||||
local net="${2%/*}" nlen="${2#*/}"
|
||||
[ "$alen" = "$nlen" ] || return 1
|
||||
# Compare the network part by masking both to /nlen.
|
||||
local a n
|
||||
a=$(mask_to_net "$addr" "$nlen")
|
||||
n=$(mask_to_net "$net" "$nlen")
|
||||
[ "$a" = "$n" ]
|
||||
}
|
||||
|
||||
# Mask an IPv4 dotted-quad to its /len network address.
|
||||
mask_to_net() {
|
||||
local ip="$1" len="$2"
|
||||
local IFS=. ; read -r o1 o2 o3 o4 <<<"$ip"
|
||||
local int=$(( (o1<<24) + (o2<<16) + (o3<<8) + o4 ))
|
||||
local mask=$(( len == 0 ? 0 : (0xFFFFFFFF << (32 - len)) & 0xFFFFFFFF ))
|
||||
local net=$(( int & mask ))
|
||||
echo "$(( (net>>24)&255 )).$(( (net>>16)&255 )).$(( (net>>8)&255 )).$(( net&255 ))"
|
||||
}
|
||||
|
||||
main() {
|
||||
# Default to eth1 (the mirrored LAN NIC here); accept overrides as args.
|
||||
local ifaces=("${@:-eth1}")
|
||||
# Boot race: WSL mirrored mode can populate the interface's addresses/routes a
|
||||
# beat after the unit starts. Wait (bounded) for at least one connected route
|
||||
# to appear on the first interface before pinning.
|
||||
local i tries=0
|
||||
for i in "${ifaces[@]}"; do
|
||||
while [ "$tries" -lt 15 ] \
|
||||
&& [ -z "$(ip -4 route show dev "$i" proto kernel scope link 2>/dev/null)" ]; do
|
||||
sleep 1; tries=$((tries + 1))
|
||||
done
|
||||
break
|
||||
done
|
||||
for i in "${ifaces[@]}"; do
|
||||
ip link show "$i" >/dev/null 2>&1 && fix_iface "$i"
|
||||
done
|
||||
}
|
||||
|
||||
main "$@"
|
||||
@@ -1,23 +0,0 @@
|
||||
CREATE TABLE `events` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`index` integer NOT NULL,
|
||||
`type` text NOT NULL,
|
||||
`direction` text,
|
||||
`lane` integer NOT NULL,
|
||||
`source` text,
|
||||
`identity` text,
|
||||
`occurred_at` text NOT NULL,
|
||||
`prev_hash` text,
|
||||
`signature` text NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `events_index_unique` ON `events` (`index`);--> statement-breakpoint
|
||||
CREATE TABLE `users` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`username` text NOT NULL,
|
||||
`password_hash` text NOT NULL,
|
||||
`role` text NOT NULL,
|
||||
`created_at` text DEFAULT (current_timestamp) NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `users_username_unique` ON `users` (`username`);
|
||||
@@ -0,0 +1,125 @@
|
||||
CREATE TABLE `blocklist` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`kind` text NOT NULL,
|
||||
`value` text NOT NULL,
|
||||
`reason` text,
|
||||
`active` integer DEFAULT true NOT NULL,
|
||||
`added_by` text,
|
||||
`added_at` text DEFAULT (current_timestamp) NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `device_events` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`device_id` text,
|
||||
`category` text,
|
||||
`kind` text NOT NULL,
|
||||
`detail` text,
|
||||
`occurred_at` text DEFAULT (current_timestamp) NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `devices` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`category` text NOT NULL,
|
||||
`driver_id` text NOT NULL,
|
||||
`config` text NOT NULL,
|
||||
`enabled` integer DEFAULT true NOT NULL,
|
||||
`created_at` text DEFAULT (current_timestamp) NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `ledger_events` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`index` integer NOT NULL,
|
||||
`type` text NOT NULL,
|
||||
`direction` text,
|
||||
`source` text,
|
||||
`identity` text,
|
||||
`payload` text,
|
||||
`occurred_at` text NOT NULL,
|
||||
`prev_hash` text,
|
||||
`signature` text NOT NULL,
|
||||
`key_id` text NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `ledger_events_index_unique` ON `ledger_events` (`index`);--> statement-breakpoint
|
||||
CREATE TABLE `permit_credentials` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`permit_id` text NOT NULL,
|
||||
`kind` text NOT NULL,
|
||||
`value` text NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `permit_plates` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`permit_id` text NOT NULL,
|
||||
`plate` text NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `permits` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`holder_name` text,
|
||||
`contact` text,
|
||||
`max_concurrent` integer DEFAULT 1,
|
||||
`valid_from` text,
|
||||
`valid_to` text,
|
||||
`status` text DEFAULT 'active' NOT NULL,
|
||||
`created_at` text DEFAULT (current_timestamp) NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `sessions` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`identity` text,
|
||||
`source` text,
|
||||
`permit_id` text,
|
||||
`entered_at` text NOT NULL,
|
||||
`exited_at` text,
|
||||
`state` text DEFAULT 'open' NOT NULL,
|
||||
`last_event_index` integer
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `setup_state` (
|
||||
`id` integer PRIMARY KEY NOT NULL,
|
||||
`completed_at` text
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `site_config` (
|
||||
`id` integer PRIMARY KEY NOT NULL,
|
||||
`capacity` integer,
|
||||
`updated_at` text DEFAULT (current_timestamp) NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `snapshots` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`direction` text NOT NULL,
|
||||
`device_id` text,
|
||||
`identity` text,
|
||||
`content_type` text NOT NULL,
|
||||
`bytes` blob NOT NULL,
|
||||
`captured_at` text NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `tariff_versions` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`tariff_id` text NOT NULL,
|
||||
`effective_from` text NOT NULL,
|
||||
`currency` text NOT NULL,
|
||||
`structure` text NOT NULL,
|
||||
`created_by` text,
|
||||
`created_at` text DEFAULT (current_timestamp) NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `tariffs` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`scope` text DEFAULT 'site' NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`created_at` text DEFAULT (current_timestamp) NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `users` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`username` text NOT NULL,
|
||||
`password_hash` text NOT NULL,
|
||||
`role` text NOT NULL,
|
||||
`created_at` text DEFAULT (current_timestamp) NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `users_username_unique` ON `users` (`username`);
|
||||
@@ -1,14 +0,0 @@
|
||||
CREATE TABLE `lane_devices` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`lane` integer NOT NULL,
|
||||
`category` text NOT NULL,
|
||||
`driver_id` text NOT NULL,
|
||||
`config` text NOT NULL,
|
||||
`enabled` integer DEFAULT true NOT NULL,
|
||||
`created_at` text DEFAULT (current_timestamp) NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE `setup_state` (
|
||||
`id` integer PRIMARY KEY NOT NULL,
|
||||
`completed_at` text
|
||||
);
|
||||
@@ -1,11 +1,179 @@
|
||||
{
|
||||
"version": "6",
|
||||
"dialect": "sqlite",
|
||||
"id": "721bbb8f-b929-4018-9420-0ae75b03ff93",
|
||||
"id": "a6d81d46-c4a4-4ee7-8565-ec012bbe0252",
|
||||
"prevId": "00000000-0000-0000-0000-000000000000",
|
||||
"tables": {
|
||||
"events": {
|
||||
"name": "events",
|
||||
"blocklist": {
|
||||
"name": "blocklist",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"kind": {
|
||||
"name": "kind",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"value": {
|
||||
"name": "value",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"reason": {
|
||||
"name": "reason",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"active": {
|
||||
"name": "active",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": true
|
||||
},
|
||||
"added_by": {
|
||||
"name": "added_by",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"added_at": {
|
||||
"name": "added_at",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "(current_timestamp)"
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"device_events": {
|
||||
"name": "device_events",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"device_id": {
|
||||
"name": "device_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"category": {
|
||||
"name": "category",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"kind": {
|
||||
"name": "kind",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"detail": {
|
||||
"name": "detail",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"occurred_at": {
|
||||
"name": "occurred_at",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "(current_timestamp)"
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"devices": {
|
||||
"name": "devices",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"category": {
|
||||
"name": "category",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"driver_id": {
|
||||
"name": "driver_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"config": {
|
||||
"name": "config",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"enabled": {
|
||||
"name": "enabled",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": true
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "(current_timestamp)"
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"ledger_events": {
|
||||
"name": "ledger_events",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
@@ -35,13 +203,6 @@
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"lane": {
|
||||
"name": "lane",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"source": {
|
||||
"name": "source",
|
||||
"type": "text",
|
||||
@@ -56,6 +217,13 @@
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"payload": {
|
||||
"name": "payload",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"occurred_at": {
|
||||
"name": "occurred_at",
|
||||
"type": "text",
|
||||
@@ -76,11 +244,18 @@
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"key_id": {
|
||||
"name": "key_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"events_index_unique": {
|
||||
"name": "events_index_unique",
|
||||
"ledger_events_index_unique": {
|
||||
"name": "ledger_events_index_unique",
|
||||
"columns": [
|
||||
"index"
|
||||
],
|
||||
@@ -92,6 +267,426 @@
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"permit_credentials": {
|
||||
"name": "permit_credentials",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"permit_id": {
|
||||
"name": "permit_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"kind": {
|
||||
"name": "kind",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"value": {
|
||||
"name": "value",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"permit_plates": {
|
||||
"name": "permit_plates",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"permit_id": {
|
||||
"name": "permit_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"plate": {
|
||||
"name": "plate",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"permits": {
|
||||
"name": "permits",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"holder_name": {
|
||||
"name": "holder_name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"contact": {
|
||||
"name": "contact",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"max_concurrent": {
|
||||
"name": "max_concurrent",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false,
|
||||
"default": 1
|
||||
},
|
||||
"valid_from": {
|
||||
"name": "valid_from",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"valid_to": {
|
||||
"name": "valid_to",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"status": {
|
||||
"name": "status",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'active'"
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "(current_timestamp)"
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"sessions": {
|
||||
"name": "sessions",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"identity": {
|
||||
"name": "identity",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"source": {
|
||||
"name": "source",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"permit_id": {
|
||||
"name": "permit_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"entered_at": {
|
||||
"name": "entered_at",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"exited_at": {
|
||||
"name": "exited_at",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"state": {
|
||||
"name": "state",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'open'"
|
||||
},
|
||||
"last_event_index": {
|
||||
"name": "last_event_index",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"setup_state": {
|
||||
"name": "setup_state",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "integer",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"completed_at": {
|
||||
"name": "completed_at",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"site_config": {
|
||||
"name": "site_config",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "integer",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"capacity": {
|
||||
"name": "capacity",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "(current_timestamp)"
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"snapshots": {
|
||||
"name": "snapshots",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"direction": {
|
||||
"name": "direction",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"device_id": {
|
||||
"name": "device_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"identity": {
|
||||
"name": "identity",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"content_type": {
|
||||
"name": "content_type",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"bytes": {
|
||||
"name": "bytes",
|
||||
"type": "blob",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"captured_at": {
|
||||
"name": "captured_at",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"tariff_versions": {
|
||||
"name": "tariff_versions",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"tariff_id": {
|
||||
"name": "tariff_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"effective_from": {
|
||||
"name": "effective_from",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"currency": {
|
||||
"name": "currency",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"structure": {
|
||||
"name": "structure",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"created_by": {
|
||||
"name": "created_by",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "(current_timestamp)"
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"tariffs": {
|
||||
"name": "tariffs",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"scope": {
|
||||
"name": "scope",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "'site'"
|
||||
},
|
||||
"name": {
|
||||
"name": "name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "(current_timestamp)"
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"users": {
|
||||
"name": "users",
|
||||
"columns": {
|
||||
|
||||
@@ -1,245 +0,0 @@
|
||||
{
|
||||
"version": "6",
|
||||
"dialect": "sqlite",
|
||||
"id": "1073123c-0df9-4109-84bf-7f23b95ec5bd",
|
||||
"prevId": "721bbb8f-b929-4018-9420-0ae75b03ff93",
|
||||
"tables": {
|
||||
"events": {
|
||||
"name": "events",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"index": {
|
||||
"name": "index",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"type": {
|
||||
"name": "type",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"direction": {
|
||||
"name": "direction",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"lane": {
|
||||
"name": "lane",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"source": {
|
||||
"name": "source",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"identity": {
|
||||
"name": "identity",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"occurred_at": {
|
||||
"name": "occurred_at",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"prev_hash": {
|
||||
"name": "prev_hash",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"signature": {
|
||||
"name": "signature",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"events_index_unique": {
|
||||
"name": "events_index_unique",
|
||||
"columns": [
|
||||
"index"
|
||||
],
|
||||
"isUnique": true
|
||||
}
|
||||
},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"lane_devices": {
|
||||
"name": "lane_devices",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"lane": {
|
||||
"name": "lane",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"category": {
|
||||
"name": "category",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"driver_id": {
|
||||
"name": "driver_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"config": {
|
||||
"name": "config",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"enabled": {
|
||||
"name": "enabled",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": true
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "(current_timestamp)"
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"setup_state": {
|
||||
"name": "setup_state",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "integer",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"completed_at": {
|
||||
"name": "completed_at",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
},
|
||||
"users": {
|
||||
"name": "users",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"username": {
|
||||
"name": "username",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"password_hash": {
|
||||
"name": "password_hash",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"role": {
|
||||
"name": "role",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false,
|
||||
"default": "(current_timestamp)"
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"users_username_unique": {
|
||||
"name": "users_username_unique",
|
||||
"columns": [
|
||||
"username"
|
||||
],
|
||||
"isUnique": true
|
||||
}
|
||||
},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
}
|
||||
},
|
||||
"views": {},
|
||||
"enums": {},
|
||||
"_meta": {
|
||||
"schemas": {},
|
||||
"tables": {},
|
||||
"columns": {}
|
||||
},
|
||||
"internal": {
|
||||
"indexes": {}
|
||||
}
|
||||
}
|
||||
@@ -5,15 +5,8 @@
|
||||
{
|
||||
"idx": 0,
|
||||
"version": "6",
|
||||
"when": 1781389618205,
|
||||
"tag": "0000_absent_rocket_raccoon",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 1,
|
||||
"version": "6",
|
||||
"when": 1781416636098,
|
||||
"tag": "0001_cuddly_maria_hill",
|
||||
"when": 1781632874398,
|
||||
"tag": "0000_baseline",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
|
||||
+209
-16
@@ -1,11 +1,17 @@
|
||||
import { sql } from "drizzle-orm";
|
||||
import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
|
||||
import { blob, integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
|
||||
|
||||
// Schema notes:
|
||||
// - `events` is APPEND-ONLY. Never expose UPDATE/DELETE on it. A correction or
|
||||
// void is a new row of type 'void'. Each row chains to the previous via
|
||||
// `prevHash` and is signed by the ATECC608 (`signature`). This is the core
|
||||
// anti-fraud integrity mechanism. See wiki/concepts/append-only-event-chain.md.
|
||||
// - TWO event streams, deliberately separate (see wiki/decisions/event-streams-split.md):
|
||||
// • `ledger_events` — the APPEND-ONLY, hash-chained, ATECC608-SIGNED business ledger.
|
||||
// Never UPDATE/DELETE. A correction or void is a new row of type 'void'. Each row
|
||||
// chains via `prevHash` and is signed (`signature`). The anti-fraud record; sessions,
|
||||
// tariffs and occupancy are PROJECTIONS over it. See append-only-event-chain.md.
|
||||
// • `device_events` — UNSIGNED operational telemetry (relay/printer/camera/reader/input).
|
||||
// High-volume, prunable, never reconciled. See wiki/concepts/device-events.md.
|
||||
// - Business master data (tariffs/permits/blocklist) IS mutable, but its USE is fixed in a
|
||||
// signed ledger event, so the audit trail stays append-only. Tariffs are versioned:
|
||||
// editing publishes a new immutable tariff_version. See wiki/concepts/tariff.md.
|
||||
// - `users` holds bcrypt hashes + a role; auth is fully local (offline-first).
|
||||
// See wiki/entities/local-jwt-auth.md.
|
||||
|
||||
@@ -21,30 +27,88 @@ export const users = sqliteTable("users", {
|
||||
.default(sql`(current_timestamp)`),
|
||||
});
|
||||
|
||||
export const events = sqliteTable("events", {
|
||||
// --- The signed business ledger (formerly `events`) ----------------------
|
||||
// Holds ONLY business/accountability facts: vehicle_entry, vehicle_exit, payment,
|
||||
// void, shift_z_report, plus witness-grade barrier_open_command/observed, anomaly.
|
||||
// `payload` carries type-specific data (amount, tariffVersionId, sessionRef, tender,
|
||||
// plate confidence…) and is part of the SIGNED canonical form, so it is tamper-evident
|
||||
// like the rest of the row. See packages/shared ParkingEventType + LedgerPayload.
|
||||
export const ledgerEvents = sqliteTable("ledger_events", {
|
||||
id: text("id").primaryKey(),
|
||||
// Monotonic chain index. Gaps are alarms (see event-log-ingestion).
|
||||
index: integer("index").notNull().unique(),
|
||||
type: text("type").notNull(),
|
||||
direction: text("direction", { enum: ["entry", "exit"] }),
|
||||
lane: integer("lane").notNull(),
|
||||
source: text("source"),
|
||||
identity: text("identity"),
|
||||
// Type-specific business payload (JSON). Signed as part of the canonical form.
|
||||
payload: text("payload", { mode: "json" }).$type<Record<string, unknown>>(),
|
||||
occurredAt: text("occurred_at").notNull(),
|
||||
// Hash of the previous event (hex). Null only for the genesis event.
|
||||
prevHash: text("prev_hash"),
|
||||
// ATECC608 signature over the canonical event payload (hex).
|
||||
signature: text("signature").notNull(),
|
||||
// Which signer/key produced `signature` (e.g. "sw-hmac-v1", "atecc608-slot0"),
|
||||
// so old events stay verifiable across a signer swap. See packages/shared Signer.
|
||||
keyId: text("key_id").notNull(),
|
||||
});
|
||||
|
||||
// Per-lane device assignments chosen by the admin during first-run setup.
|
||||
// One row per (lane, category, instance). `driverId` references a driver in the
|
||||
// @parking/devices registry; `config` is that driver's JSON config (host, port,
|
||||
// credentials…). Lets the system stay device-agnostic and admin-configurable.
|
||||
// See wiki/concepts/device-registry.md and first-run-setup.md.
|
||||
export const laneDevices = sqliteTable("lane_devices", {
|
||||
// --- Device telemetry (unsigned, prunable) -------------------------------
|
||||
// Operational monitoring, NOT anti-fraud: relay fired, printer paper-out, camera
|
||||
// offline, reader read, raw input edges. Keyed to a `devices` instance. No
|
||||
// prevHash/signature — this stream may rotate/prune.
|
||||
export const deviceEvents = sqliteTable("device_events", {
|
||||
id: text("id").primaryKey(),
|
||||
// The `devices` instance that produced it (raw provenance).
|
||||
deviceId: text("device_id"),
|
||||
category: text("category", {
|
||||
enum: ["access", "reader", "camera", "printer"],
|
||||
}),
|
||||
// e.g. "input", "relay", "status", "read", "snapshot".
|
||||
kind: text("kind").notNull(),
|
||||
// Free-form telemetry detail (input number + edge, status flags, error…).
|
||||
detail: text("detail", { mode: "json" }).$type<Record<string, unknown>>(),
|
||||
occurredAt: text("occurred_at")
|
||||
.notNull()
|
||||
.default(sql`(current_timestamp)`),
|
||||
});
|
||||
|
||||
// --- Camera snapshots (unsigned, prunable, blob-in-DB) -------------------
|
||||
// An entry/exit snapshot captured asynchronously AFTER the barrier opens — evidence,
|
||||
// not a gate (camera failure never blocks an open; see entry/exit flows). Stored as a
|
||||
// BLOB so the appliance keeps a single backed-up file with nothing scattered on disk.
|
||||
// Kept in its own table (not inline in device_events) so the hot telemetry scans don't
|
||||
// drag image bytes, and so images can be pruned independently. The signed
|
||||
// vehicle_entry/exit references a snapshot by `id` in its payload — the image is an
|
||||
// independent record (anti-fraud), unsigned and prunable. Retention policy is an open
|
||||
// question — see wiki/concepts/entry-exit-points.md. Served via GET /api/snapshots/:id.
|
||||
export const snapshots = sqliteTable("snapshots", {
|
||||
id: text("id").primaryKey(),
|
||||
direction: text("direction", { enum: ["entry", "exit"] }).notNull(),
|
||||
// The camera `devices` instance that captured it (raw provenance).
|
||||
deviceId: text("device_id"),
|
||||
// The session/credential ref (ticket id, plate, permit) — links to the ledger event.
|
||||
identity: text("identity"),
|
||||
contentType: text("content_type").notNull(),
|
||||
bytes: blob("bytes").notNull().$type<Buffer>(),
|
||||
capturedAt: text("captured_at").notNull(),
|
||||
});
|
||||
|
||||
// --- Device assignments (first-run setup) --------------------------------
|
||||
// One row per device instance. `driverId` references a driver in the @parking/devices
|
||||
// registry; `config` is that driver's JSON config. There is NO lane: a parking lot is
|
||||
// one pool of spaces with a flexible set of entry/exit points. Direction lives INSIDE
|
||||
// the config, per the hardware:
|
||||
// - access controller: config.relays = [{ relay, direction: entry|exit|both, button? }]
|
||||
// — one physical board has several relays; each relay opens one barrier in one
|
||||
// direction (or both). `button` = the input terminal the entry button is wired to
|
||||
// (transient entry trigger; absent = no button at that barrier).
|
||||
// - reader / camera: config.controllerId + config.relay BIND it to the barrier it sits
|
||||
// at; its direction is INHERITED from that relay. Unbound → falls back to a
|
||||
// direction picked in config.
|
||||
// See device-registry.md, first-run-setup.md, wiki/concepts/entry-exit-points.md.
|
||||
export const devices = sqliteTable("devices", {
|
||||
id: text("id").primaryKey(),
|
||||
lane: integer("lane").notNull(),
|
||||
category: text("category", {
|
||||
enum: ["access", "reader", "camera", "printer"],
|
||||
}).notNull(),
|
||||
@@ -64,7 +128,136 @@ export const setupState = sqliteTable("setup_state", {
|
||||
completedAt: text("completed_at"),
|
||||
});
|
||||
|
||||
// Single-row site settings (admin-configurable). The home for site-wide knobs;
|
||||
// `capacity` is the nominal space count the FULL gate refuses transient entry at
|
||||
// (null = no cap). See wiki/concepts/capacity-occupancy.md.
|
||||
export const siteConfig = sqliteTable("site_config", {
|
||||
id: integer("id").primaryKey(), // always 1
|
||||
capacity: integer("capacity"), // null = no capacity limit
|
||||
updatedAt: text("updated_at")
|
||||
.notNull()
|
||||
.default(sql`(current_timestamp)`),
|
||||
});
|
||||
|
||||
// --- Tariffs (composable, versioned) -------------------------------------
|
||||
// A `tariffs` row is a logical rate card; its pricing lives in immutable, effective-
|
||||
// dated `tariff_versions`. Editing prices PUBLISHES a new version, never mutates one.
|
||||
// A session reprices against the version in force at its entry time; the `payment`
|
||||
// ledger event records the tariffVersionId used. "One active tariff per site" today;
|
||||
// `scope` lets multiple be added later without migration. See wiki/concepts/tariff.md.
|
||||
export const tariffs = sqliteTable("tariffs", {
|
||||
id: text("id").primaryKey(),
|
||||
// Only "site" used now; "zone" reserved for multi-tariff later.
|
||||
scope: text("scope", { enum: ["site", "zone"] }).notNull().default("site"),
|
||||
name: text("name").notNull(),
|
||||
createdAt: text("created_at")
|
||||
.notNull()
|
||||
.default(sql`(current_timestamp)`),
|
||||
});
|
||||
|
||||
export const tariffVersions = sqliteTable("tariff_versions", {
|
||||
id: text("id").primaryKey(),
|
||||
tariffId: text("tariff_id").notNull(),
|
||||
// The version is in force from this instant (latest with effectiveFrom ≤ entry wins).
|
||||
effectiveFrom: text("effective_from").notNull(),
|
||||
// ISO 4217; selectable. Money everywhere is { minorUnits, currency }, never a float.
|
||||
currency: text("currency").notNull(),
|
||||
// The composable rate card (stepped blocks + caps/grace). Shape: TariffStructure
|
||||
// in packages/shared. Immutable once published.
|
||||
structure: text("structure", { mode: "json" }).notNull().$type<Record<string, unknown>>(),
|
||||
createdBy: text("created_by"),
|
||||
createdAt: text("created_at")
|
||||
.notNull()
|
||||
.default(sql`(current_timestamp)`),
|
||||
});
|
||||
|
||||
// --- Permits (subscriptions) ---------------------------------------------
|
||||
// Mutable master data; every USE produces a signed vehicle_entry/exit ledger event.
|
||||
// Two optional, independent bindings: car-count (maxConcurrent, default 1, null =
|
||||
// unbound) and plate (plates rows, default none = any car). Identity = card/QR OR a
|
||||
// matching plate. Credentials and cars are child rows. See wiki/entities/permit.md.
|
||||
export const permits = sqliteTable("permits", {
|
||||
id: text("id").primaryKey(),
|
||||
holderName: text("holder_name"),
|
||||
contact: text("contact"),
|
||||
// Car-count binding: how many of the permit's cars may be inside at once.
|
||||
// null = unbound. Default 1.
|
||||
maxConcurrent: integer("max_concurrent").default(1),
|
||||
validFrom: text("valid_from"),
|
||||
validTo: text("valid_to"),
|
||||
status: text("status", { enum: ["active", "suspended", "revoked"] })
|
||||
.notNull()
|
||||
.default("active"),
|
||||
createdAt: text("created_at")
|
||||
.notNull()
|
||||
.default(sql`(current_timestamp)`),
|
||||
});
|
||||
|
||||
// A permit's credentials (RF tag/chip/card, or QR). Either opens the lane.
|
||||
export const permitCredentials = sqliteTable("permit_credentials", {
|
||||
id: text("id").primaryKey(),
|
||||
permitId: text("permit_id").notNull(),
|
||||
kind: text("kind", { enum: ["rf", "qr"] }).notNull(),
|
||||
value: text("value").notNull(),
|
||||
});
|
||||
|
||||
// Plate binding (optional). When a permit has plate rows, a matching plate read is
|
||||
// itself an accepted identity (card/QR OR plate). Empty = not plate-bound (any car).
|
||||
export const permitPlates = sqliteTable("permit_plates", {
|
||||
id: text("id").primaryKey(),
|
||||
permitId: text("permit_id").notNull(),
|
||||
plate: text("plate").notNull(),
|
||||
});
|
||||
|
||||
// --- Blocklist (banlist) -------------------------------------------------
|
||||
// Plates/cards refused at ENTRY (never at exit — never trap a vehicle). A hit appends
|
||||
// a signed anomaly/refused-entry ledger event. See wiki/entities/blocklist.md.
|
||||
export const blocklist = sqliteTable("blocklist", {
|
||||
id: text("id").primaryKey(),
|
||||
kind: text("kind", { enum: ["plate", "card", "qr"] }).notNull(),
|
||||
value: text("value").notNull(),
|
||||
reason: text("reason"),
|
||||
active: integer("active", { mode: "boolean" }).notNull().default(true),
|
||||
addedBy: text("added_by"),
|
||||
addedAt: text("added_at")
|
||||
.notNull()
|
||||
.default(sql`(current_timestamp)`),
|
||||
});
|
||||
|
||||
// --- Sessions (PROJECTION cache) -----------------------------------------
|
||||
// NOT a source of truth — a rebuildable fold over ledger_events for fast queries
|
||||
// (occupancy, pay-station lookup, anti-passback, plate search). Always reconstructable
|
||||
// from the signed chain; never the authority for "paid". See wiki/concepts/parking-session.md.
|
||||
export const sessions = sqliteTable("sessions", {
|
||||
// The session key = the entry's identity (ticket id or plate).
|
||||
id: text("id").primaryKey(),
|
||||
// Identity that opened the session, and how it was read.
|
||||
identity: text("identity"),
|
||||
source: text("source"),
|
||||
// null while transient; set when matched to a permit.
|
||||
permitId: text("permit_id"),
|
||||
enteredAt: text("entered_at").notNull(),
|
||||
// null until exit; presence = CLOSED.
|
||||
exitedAt: text("exited_at"),
|
||||
// Derived state for quick filtering: open | paid | closed | voided.
|
||||
state: text("state", { enum: ["open", "paid", "closed", "voided"] })
|
||||
.notNull()
|
||||
.default("open"),
|
||||
// Index of the last ledger event folded into this row (cache freshness / rebuild).
|
||||
lastEventIndex: integer("last_event_index"),
|
||||
});
|
||||
|
||||
export type UserRow = typeof users.$inferSelect;
|
||||
export type EventRow = typeof events.$inferSelect;
|
||||
export type LaneDeviceRow = typeof laneDevices.$inferSelect;
|
||||
export type LedgerEventRow = typeof ledgerEvents.$inferSelect;
|
||||
export type DeviceEventRow = typeof deviceEvents.$inferSelect;
|
||||
export type SnapshotRow = typeof snapshots.$inferSelect;
|
||||
export type DeviceRow = typeof devices.$inferSelect;
|
||||
export type SetupStateRow = typeof setupState.$inferSelect;
|
||||
export type SiteConfigRow = typeof siteConfig.$inferSelect;
|
||||
export type TariffRow = typeof tariffs.$inferSelect;
|
||||
export type TariffVersionRow = typeof tariffVersions.$inferSelect;
|
||||
export type PermitRow = typeof permits.$inferSelect;
|
||||
export type PermitCredentialRow = typeof permitCredentials.$inferSelect;
|
||||
export type PermitPlateRow = typeof permitPlates.$inferSelect;
|
||||
export type BlocklistRow = typeof blocklist.$inferSelect;
|
||||
export type SessionRow = typeof sessions.$inferSelect;
|
||||
|
||||
@@ -18,8 +18,7 @@
|
||||
"lint": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@parking/shared": "workspace:*",
|
||||
"uhppoted": "0.9.0"
|
||||
"@parking/shared": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "25.9.3",
|
||||
|
||||
@@ -0,0 +1,758 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { createSocket } from "node:dgram";
|
||||
import { request as httpRequest } from "node:http";
|
||||
import type {
|
||||
AccessControlDevice,
|
||||
DeviceHealth,
|
||||
HardenableDevice,
|
||||
HardenResult,
|
||||
InputDevice,
|
||||
InputEvent,
|
||||
PreconditionDevice,
|
||||
PreconditionResult,
|
||||
PushConfig,
|
||||
PushConfigurableDevice,
|
||||
} from "../interfaces.js";
|
||||
import type { AccessDriver, DeviceConfig } from "../registry.js";
|
||||
import { hostField, portField, stubLog } from "./common.js";
|
||||
|
||||
// Dingtian relay+input controller driver. Backed by the "Dingtian string"
|
||||
// protocol over UDP. Implements AccessControlDevice (relay/barrier) AND the
|
||||
// optional InputDevice capability (host-readable buttons, decoupled from relays)
|
||||
// — which is what makes host-in-the-loop entry possible. See
|
||||
// wiki/entities/dingtian-relay.md and access-controller-button-flow.md.
|
||||
//
|
||||
// SAFETY: pulseOpen expresses INTENT only. It uses the device's jog/pulse
|
||||
// (momentary) so the relay self-releases; we never time a close against a
|
||||
// vehicle — anti-crush/auto-reverse is the barrier operator's firmware.
|
||||
// See wiki/concepts/barrier-not-a-door.md.
|
||||
//
|
||||
// SECURITY: unauthenticated UDP — the board must sit on an isolated VLAN
|
||||
// reachable only by the host. See wiki/concepts/network-isolation.md.
|
||||
//
|
||||
// NOTE: by default Dingtian links each input to auto-fire its relay
|
||||
// (input_link_relay). That must be DISABLED on the device for ticket-first
|
||||
// entry, else the button opens the barrier before the host can act.
|
||||
|
||||
// (The string-protocol UDP helper was removed: harden() now disables the
|
||||
// password-less string protocol entirely, and status reads use the
|
||||
// authenticated binary read — see #status() / readStatusFrame.)
|
||||
|
||||
/**
|
||||
* Send a Dingtian *binary* protocol frame (UDP, default port 60000) and await
|
||||
* the reply. Used for ALL relay traffic — control AND status read — because,
|
||||
* unlike the string protocol, the binary protocol carries a password (`relay_pw`).
|
||||
* harden() disables the string protocol precisely because it has NO password and
|
||||
* can fire relays (an unauthenticated `"11"` opens relay 1). With the string path
|
||||
* closed, relay_pw actually gates control. Frame verified on hardware:
|
||||
*
|
||||
* FF AA <session> <relayCmd> <pwLo> <pwHi> <data...>
|
||||
*
|
||||
* FF = command "set relay"
|
||||
* AA = result xor (0x00 ^ 0xAA, pc→device)
|
||||
* session = echoed back
|
||||
* relayCmd = 0 read status, 1 write, 3 jogging, …
|
||||
* pwLo,pwHi = relay password, 16-bit LSB-first (0 = none)
|
||||
* data = command-specific
|
||||
*
|
||||
* NOTE: relay_pw + plaintext UDP is defence-in-depth, NOT a boundary. An attacker
|
||||
* who sniffs the VLAN can replay the password. The real guarantee is the signed
|
||||
* event log (relay open with no signed command = fraud) + VLAN isolation.
|
||||
*/
|
||||
function binaryUdp(
|
||||
host: string,
|
||||
port: number,
|
||||
frame: Buffer,
|
||||
timeoutMs: number,
|
||||
localAddress?: string,
|
||||
): Promise<Buffer> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const sock = createSocket("udp4");
|
||||
let settled = false;
|
||||
const done = (err: Error | null, val: Buffer | null) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
sock.close();
|
||||
err ? reject(err) : resolve(val!);
|
||||
};
|
||||
const timer = setTimeout(() => done(new Error("timeout"), null), timeoutMs);
|
||||
sock.on("error", (e) => done(e, null));
|
||||
sock.on("message", (m) => done(null, m));
|
||||
// Bind to a specific local address (the device-facing NIC) on multi-homed
|
||||
// hosts, so the device replies to the right source IP. See net.ts.
|
||||
const onBound = () => {
|
||||
sock.send(frame, port, host, (e) => {
|
||||
if (e) done(e, null);
|
||||
});
|
||||
};
|
||||
if (localAddress) sock.bind({ address: localAddress }, onBound);
|
||||
else sock.bind(onBound);
|
||||
});
|
||||
}
|
||||
|
||||
let binarySession = 0;
|
||||
|
||||
/**
|
||||
* Build a binary "read relay status" frame (relay command 0x00). The device
|
||||
* replies `FF AA <session> 00 <relayBytes> <inputBytes>` (status widths scale
|
||||
* with channel count). This is the *authenticated* status read — unlike the
|
||||
* string protocol's `00`, it carries the relay password, so we can disable the
|
||||
* password-less string protocol entirely. Frame: `FF AA <session> 00 <pwLo> <pwHi>`.
|
||||
* Verified on hardware (4ch): reply `ff aa 00 00 01 0f` = relay1 on, inputs 1111.
|
||||
*/
|
||||
function readStatusFrame(password: number): Buffer {
|
||||
const session = binarySession++ & 0xff;
|
||||
return Buffer.from([0xff, 0xaa, session, 0x00, password & 0xff, (password >> 8) & 0xff]);
|
||||
}
|
||||
|
||||
/** Build a binary "write relay with jogging" frame (relay on, auto-off). */
|
||||
function jogFrame(channel: number, password: number, jogMs: number): Buffer {
|
||||
const session = binarySession++ & 0xff;
|
||||
// relay index + on/off: bit0 = on, bits1..7 = (channel-1)
|
||||
const relayByte = (((channel - 1) & 0x7f) << 1) | 0x01;
|
||||
const units = Math.max(1, Math.round(jogMs / 100)); // 100ms units
|
||||
return Buffer.from([
|
||||
0xff,
|
||||
0xaa,
|
||||
session,
|
||||
0x03, // jogging
|
||||
password & 0xff,
|
||||
(password >> 8) & 0xff,
|
||||
relayByte,
|
||||
units & 0xff,
|
||||
(units >> 8) & 0xff,
|
||||
]);
|
||||
}
|
||||
|
||||
/** Build a binary "write relay" frame (latch on/off via mask+set). */
|
||||
function writeRelayFrame(channel: number, on: boolean, password: number, channels: number): Buffer {
|
||||
const session = binarySession++ & 0xff;
|
||||
const bit = 1 << (channel - 1);
|
||||
const mask = bit; // only this channel updates
|
||||
const set = on ? bit : 0;
|
||||
// 4ch: mask + set are 1 byte each (bit0→relay1).
|
||||
const widthBytes = channels <= 8 ? 1 : channels <= 16 ? 2 : channels <= 24 ? 3 : 4;
|
||||
const maskBuf = Buffer.alloc(widthBytes);
|
||||
const setBuf = Buffer.alloc(widthBytes);
|
||||
maskBuf.writeUIntLE(mask, 0, widthBytes);
|
||||
setBuf.writeUIntLE(set, 0, widthBytes);
|
||||
return Buffer.concat([
|
||||
Buffer.from([0xff, 0xaa, session, 0x01, password & 0xff, (password >> 8) & 0xff]),
|
||||
maskBuf,
|
||||
setBuf,
|
||||
]);
|
||||
}
|
||||
|
||||
const rand16 = () => randomBytes(2).readUInt16BE(0);
|
||||
|
||||
/** GET a CGI path on the device's HTTP server and return the raw response text. */
|
||||
function cgiGet(host: string, httpPort: number, path: string, timeoutMs: number, localAddress?: string): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = httpRequest({ host, port: httpPort, path, method: "GET", timeout: timeoutMs, localAddress }, (res) => {
|
||||
let data = "";
|
||||
res.on("data", (c) => (data += c));
|
||||
res.on("end", () => resolve(data));
|
||||
});
|
||||
req.on("error", reject);
|
||||
req.on("timeout", () => req.destroy(new Error("cgi timeout")));
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
interface DingtianStatus {
|
||||
relays: boolean[]; // true = on
|
||||
inputs: boolean[]; // true = active (after resting-level normalisation)
|
||||
channels: number;
|
||||
}
|
||||
|
||||
const INPUT_LINK_ISSUE = {
|
||||
key: "input_link_relay",
|
||||
message:
|
||||
"input_link_relay is ENABLED — a button press will auto-fire its relay (opening the barrier before the host can act). Disable it for ticket-first entry.",
|
||||
fixable: true,
|
||||
} as const;
|
||||
|
||||
/** GET/POST the device's JSON config API (HTTP; port is configurable). */
|
||||
function configApi(
|
||||
host: string,
|
||||
httpPort: number,
|
||||
path: string,
|
||||
method: "GET" | "POST",
|
||||
body: string | null,
|
||||
timeoutMs: number,
|
||||
sessionId?: number, // device session check: sent as Cookie: session=<id>
|
||||
localAddress?: string, // bind outbound to the device-facing NIC (multi-homed hosts)
|
||||
): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
// The device's embedded HTTP server does NOT support chunked request bodies.
|
||||
// Node uses chunked encoding when Content-Length is absent, so the device
|
||||
// silently ignores the body (POST returns {"status":0} but nothing changes).
|
||||
// Always set Content-Length explicitly.
|
||||
const headers: Record<string, string | number> = {};
|
||||
if (body) {
|
||||
headers["content-type"] = "application/json";
|
||||
headers["content-length"] = Buffer.byteLength(body);
|
||||
}
|
||||
// When the device's HTTP session check is enabled, the CGI API requires a
|
||||
// matching session cookie (a numeric magic id). See programming manual §3.8.
|
||||
if (sessionId) headers["cookie"] = `session=${sessionId}`;
|
||||
const req = httpRequest(
|
||||
{
|
||||
host,
|
||||
port: httpPort,
|
||||
path,
|
||||
method,
|
||||
timeout: timeoutMs,
|
||||
localAddress,
|
||||
headers: Object.keys(headers).length ? headers : undefined,
|
||||
},
|
||||
(res) => {
|
||||
let data = "";
|
||||
res.on("data", (c) => (data += c));
|
||||
res.on("end", () => resolve(data));
|
||||
},
|
||||
);
|
||||
req.on("error", reject);
|
||||
req.on("timeout", () => req.destroy(new Error("config api timeout")));
|
||||
if (body) req.write(body);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
class DingtianController
|
||||
implements
|
||||
AccessControlDevice,
|
||||
InputDevice,
|
||||
PreconditionDevice,
|
||||
PushConfigurableDevice,
|
||||
HardenableDevice
|
||||
{
|
||||
readonly driverId = "dingtian";
|
||||
readonly #host: string;
|
||||
readonly #port: number; // legacy string-protocol port (60001) — protocol now disabled by harden(); kept for config compat
|
||||
readonly #binaryPort: number; // binary protocol (relay control) — UDP 60000
|
||||
readonly #relayPassword: number; // relay_pw (0 = none)
|
||||
readonly #sessionId: number; // device CGI session id (0 = session check off)
|
||||
readonly #httpPort: number;
|
||||
readonly #timeout: number;
|
||||
// Local IP to source outbound device traffic from (the device-facing NIC on a
|
||||
// multi-homed host). undefined = let the OS choose. See net.ts / device-facing-ip.
|
||||
readonly #localAddress: string | undefined;
|
||||
readonly #channels: number;
|
||||
/** Input level at rest; an input is "active" when it differs from this. */
|
||||
readonly #restingHigh: boolean;
|
||||
readonly #pulseMs: number;
|
||||
/** Device web-UI login user (gates the browser UI only, not the CGI API). */
|
||||
readonly #webUser: string;
|
||||
/** The password the admin WANTS the device to have (the rotation target). If
|
||||
* blank, harden() generates a random one. */
|
||||
readonly #webPassword: string | undefined;
|
||||
/** The device's CURRENT password, used as the OLD cred for userset.cgi. Defaults
|
||||
* to "admin" (factory). Distinct from #webPassword (the desired new value) so an
|
||||
* admin typing a desired password doesn't break rotation. */
|
||||
readonly #webPasswordCurrent: string;
|
||||
|
||||
#poll: ReturnType<typeof setInterval> | null = null;
|
||||
#last: boolean[] | null = null;
|
||||
#subs = new Set<(e: InputEvent) => void>();
|
||||
|
||||
constructor(config: DeviceConfig) {
|
||||
this.#host = String(config.host);
|
||||
this.#port = config.port ? Number(config.port) : 60001;
|
||||
this.#binaryPort = config.binaryPort ? Number(config.binaryPort) : 60000;
|
||||
this.#relayPassword = config.relayPassword ? Number(config.relayPassword) : 0;
|
||||
this.#sessionId = config.sessionId ? Number(config.sessionId) : 0;
|
||||
this.#httpPort = config.httpPort ? Number(config.httpPort) : 80;
|
||||
this.#localAddress = config.localAddress ? String(config.localAddress) : undefined;
|
||||
this.#timeout = config.timeoutMs ? Number(config.timeoutMs) : 2000;
|
||||
this.#channels = config.channels ? Number(config.channels) : 4;
|
||||
// This unit idles with inputs HIGH (status "1111"); a press pulls LOW.
|
||||
this.#restingHigh = config.inputRestingHigh !== false;
|
||||
this.#pulseMs = config.pulseMs ? Number(config.pulseMs) : 500;
|
||||
this.#webUser = config.webUser ? String(config.webUser) : "admin";
|
||||
// webPassword = the DESIRED login (admin's choice; blank → harden generates).
|
||||
this.#webPassword = config.webPassword ? String(config.webPassword) : undefined;
|
||||
// webPasswordCurrent = the device's EXISTING password (the old cred userset.cgi
|
||||
// checks). Defaults to admin (factory). After a successful rotation, assign
|
||||
// stores the new value back here so a re-run can rotate again.
|
||||
this.#webPasswordCurrent = config.webPasswordCurrent
|
||||
? String(config.webPasswordCurrent)
|
||||
: "admin";
|
||||
}
|
||||
|
||||
async connect(): Promise<void> {
|
||||
await this.healthCheck();
|
||||
}
|
||||
|
||||
async disconnect(): Promise<void> {
|
||||
this.#stopPolling();
|
||||
stubLog(this.driverId, "disconnect");
|
||||
}
|
||||
|
||||
async healthCheck(): Promise<DeviceHealth> {
|
||||
try {
|
||||
await this.#status();
|
||||
return { status: "ready" };
|
||||
} catch (err) {
|
||||
return { status: "offline", detail: (err as Error).message };
|
||||
}
|
||||
}
|
||||
|
||||
// --- relay / barrier ----------------------------------------------------
|
||||
|
||||
/**
|
||||
* Pulse a relay open (momentary). Channel is 1-based. Intent only — the device
|
||||
* jogs the relay ON then auto-releases after pulseMs, so we never time a close
|
||||
* against a vehicle. Uses the binary protocol + relay password (authenticated).
|
||||
*/
|
||||
async pulseOpen(doorId: number): Promise<void> {
|
||||
this.#assertChannel(doorId);
|
||||
const frame = jogFrame(doorId, this.#relayPassword, this.#pulseMs);
|
||||
await binaryUdp(this.#host, this.#binaryPort, frame, this.#timeout, this.#localAddress);
|
||||
}
|
||||
|
||||
/** Latch a relay on/off (e.g. for a held-open mode). Channel is 1-based. */
|
||||
async setRelay(doorId: number, on: boolean): Promise<void> {
|
||||
this.#assertChannel(doorId);
|
||||
const frame = writeRelayFrame(doorId, on, this.#relayPassword, this.#channels);
|
||||
await binaryUdp(this.#host, this.#binaryPort, frame, this.#timeout, this.#localAddress);
|
||||
}
|
||||
|
||||
async getDoorStatus(doorId: number): Promise<"open" | "closed"> {
|
||||
this.#assertChannel(doorId);
|
||||
const { relays } = await this.#status();
|
||||
// "open" here = relay energised. Physical door state needs a sensor input.
|
||||
return relays[doorId - 1] ? "open" : "closed";
|
||||
}
|
||||
|
||||
// --- inputs (buttons) ---------------------------------------------------
|
||||
|
||||
async readInputs(): Promise<boolean[]> {
|
||||
return (await this.#status()).inputs;
|
||||
}
|
||||
|
||||
onInput(cb: (event: InputEvent) => void): () => void {
|
||||
this.#subs.add(cb);
|
||||
this.#startPolling();
|
||||
return () => {
|
||||
this.#subs.delete(cb);
|
||||
if (this.#subs.size === 0) this.#stopPolling();
|
||||
};
|
||||
}
|
||||
|
||||
// --- preconditions ------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Parking requires `input_link_relay` DISABLED: otherwise a button press
|
||||
* auto-fires its relay, opening the barrier before the host can act (print a
|
||||
* ticket / decide). This is the configurable version of the UHPPOTE blocker.
|
||||
*/
|
||||
async checkPreconditions(): Promise<PreconditionResult> {
|
||||
let cfg: Record<string, unknown>;
|
||||
try {
|
||||
cfg = await this.#readConfig();
|
||||
} catch (err) {
|
||||
return {
|
||||
ok: false,
|
||||
issues: [
|
||||
{
|
||||
key: "config_unreachable",
|
||||
message: `could not read device config: ${(err as Error).message}`,
|
||||
fixable: false,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
return { ok: this.#linkDisabled(cfg), issues: this.#linkDisabled(cfg) ? [] : [INPUT_LINK_ISSUE] };
|
||||
}
|
||||
|
||||
async fixPreconditions(): Promise<PreconditionResult> {
|
||||
const cfg = await this.#readConfig();
|
||||
if (this.#linkDisabled(cfg)) return { ok: true, issues: [] };
|
||||
|
||||
// Disable the master flag AND clear the per-input action maps.
|
||||
const ilr = cfg.input_link_relay as Record<string, unknown>;
|
||||
ilr.input_link_relay = 0;
|
||||
if (Array.isArray(ilr.on_action_on)) {
|
||||
ilr.on_action_on = (ilr.on_action_on as unknown[]).map(() => []);
|
||||
}
|
||||
|
||||
await this.#writeConfig(cfg, (after) => this.#linkDisabled(after));
|
||||
return this.checkPreconditions();
|
||||
}
|
||||
|
||||
/**
|
||||
* Configure the device to HTTP-push input (button) events to our backend —
|
||||
* the "Input Link URL" feature. Each input N calls `${pathBase}/<N>/on` (and
|
||||
* `/off`) on host:port via GET, authenticated with **HTTP Digest** (the device
|
||||
* does Digest but not HTTPS-to-self-signed; both verified on hardware). The
|
||||
* password is never sent on the wire and the secret is not in the URL.
|
||||
* Enables the feature, plain HTTP, active-LOW. Replaces polling.
|
||||
*/
|
||||
async configureInputPush(opts: PushConfig): Promise<void> {
|
||||
const cfg = await this.#readConfig();
|
||||
const ilu = cfg.input_link_url as Record<string, unknown>;
|
||||
const n = Number((ilu.cnt as number) ?? this.#channels);
|
||||
const fill = (v: unknown) => Array.from({ length: n }, () => v);
|
||||
|
||||
ilu.en = 1;
|
||||
ilu.active_level = fill(0); // active-LOW (matches this board's wiring)
|
||||
ilu.tls = fill(0); // plain HTTP (device can't do HTTPS to self-signed)
|
||||
ilu.auth = fill(2); // 2 = Digest
|
||||
ilu.server = fill(opts.host);
|
||||
ilu.port = fill(opts.port);
|
||||
ilu.user = fill(opts.auth.user);
|
||||
ilu.pass = fill(opts.auth.password);
|
||||
ilu.on_method = fill(0); // GET
|
||||
ilu.off_method = fill(0);
|
||||
ilu.on_path = Array.from({ length: n }, (_, i) => `${opts.pathBase}/${i + 1}/on`);
|
||||
ilu.off_path = Array.from({ length: n }, (_, i) => `${opts.pathBase}/${i + 1}/off`);
|
||||
ilu.on_body = fill("");
|
||||
ilu.off_body = fill("");
|
||||
|
||||
const wantPath = `${opts.pathBase}/1/on`;
|
||||
await this.#writeConfig(cfg, (after) => {
|
||||
const a = after.input_link_url as Record<string, unknown> | undefined;
|
||||
const paths = a?.on_path as string[] | undefined;
|
||||
const pass = a?.pass as string[] | undefined;
|
||||
// Verify both the path and the (secret) password landed — the password is
|
||||
// what the backend's Digest check depends on.
|
||||
return (
|
||||
a?.en === 1 &&
|
||||
Array.isArray(paths) &&
|
||||
paths[0] === wantPath &&
|
||||
Array.isArray(pass) &&
|
||||
pass[0] === opts.auth.password
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// --- hardening ----------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Lock the device down for a flat (no-VLAN) network:
|
||||
* - set a random relay password (`relay_pw`) so binary relay commands need it,
|
||||
* - keep ONLY UDP1 binary (password-protected relay control + status read),
|
||||
* - disable every other protocol channel: string, rs485, can, tcp×2, mqtt.
|
||||
* Returns the relay password for the backend to persist (required to keep
|
||||
* commanding the device afterwards).
|
||||
*
|
||||
* SECURITY — why the string protocol (UDP2) is now DISABLED (was a real hole):
|
||||
* the Dingtian string protocol has NO password field and can *fire* relays
|
||||
* (`"11"` = relay 1 on, `"21"` = off, `"11*"` = jog). Leaving it enabled — even
|
||||
* "just for status reads" — let anyone on the network open any barrier with one
|
||||
* unauthenticated UDP packet, completely bypassing relay_pw. Confirmed by
|
||||
* sending `"11"` to port 60001 with no credentials and watching relay 1 close.
|
||||
* So harden() sets udp2.p=255 and status reads move to the authenticated binary
|
||||
* read (relay command 0x00 — see #status()).
|
||||
*
|
||||
* NOTE: deliberately does NOT touch the device's HTTP CGI session check
|
||||
* (`session_en`). On this firmware enabling it makes the config-read API drop
|
||||
* connections, locking us out of the very API we depend on (verified the hard
|
||||
* way — required a factory reset). So we leave the config API as-is and rely on
|
||||
* relay_pw + fewer open channels + the signed event log.
|
||||
*
|
||||
* Even with the string hole closed, all of this is plaintext over UDP/HTTP →
|
||||
* defence-in-depth, NOT a boundary. The real guarantee is the signed event log
|
||||
* (a relay open with no matching signed command is the fraud signal) plus VLAN
|
||||
* isolation. See device-input-flow / network-isolation.
|
||||
*/
|
||||
async harden(): Promise<HardenResult> {
|
||||
const cfg = await this.#readConfig();
|
||||
const rc = cfg.relay_connect as Record<string, unknown>;
|
||||
|
||||
const relayPassword = 1 + (rand16() % 9999); // 1..9999 (0 = none)
|
||||
|
||||
rc.relay_pw = relayPassword;
|
||||
// Keep ONLY UDP1=Binary (p:1) — it carries relay_pw for both control AND the
|
||||
// status read. Disable everything else (p:255 = None), INCLUDING the string
|
||||
// protocol (udp2), which is password-less and can fire relays.
|
||||
(rc.udp1 as Record<string, unknown>).p = 1;
|
||||
(rc.udp2 as Record<string, unknown>).p = 255;
|
||||
(rc.rs485 as Record<string, unknown>).p = 255;
|
||||
(rc.can as Record<string, unknown>).p = 255;
|
||||
(rc.tcpc as Record<string, unknown>).p = 255;
|
||||
(rc.tcps as Record<string, unknown>).p = 255;
|
||||
(rc.mqtt as Record<string, unknown>).p = 255;
|
||||
|
||||
// NOTE: udp2 (string protocol) is set to 255 here, but it is NOT part of the
|
||||
// blocking verify. On some firmware (e.g. V3.6J) the CONFIG API silently
|
||||
// refuses to disable udp2 — it accepts the write, reboots, and clamps it back
|
||||
// to enabled — even though every other channel applies and the device's own
|
||||
// web UI CAN disable it. We don't want assign to hard-fail over a firmware
|
||||
// quirk, so we attempt it, then re-check below and warn if it didn't stick.
|
||||
const afterCfg = await this.#writeConfig(cfg, (after) => {
|
||||
const a = after.relay_connect as Record<string, unknown> | undefined;
|
||||
return (
|
||||
a?.relay_pw === relayPassword &&
|
||||
(a?.rs485 as Record<string, unknown> | undefined)?.p === 255 &&
|
||||
(a?.mqtt as Record<string, unknown> | undefined)?.p === 255
|
||||
);
|
||||
});
|
||||
|
||||
const applied = [
|
||||
"set relay password",
|
||||
"disabled rs485/can/tcp/mqtt channels (kept password-protected UDP binary)",
|
||||
];
|
||||
const warnings: string[] = [];
|
||||
const stringDisabled =
|
||||
((afterCfg.relay_connect as Record<string, unknown>)?.udp2 as Record<string, unknown> | undefined)?.p === 255;
|
||||
if (stringDisabled) {
|
||||
applied.push("disabled the password-less string protocol (udp2)");
|
||||
} else {
|
||||
warnings.push(
|
||||
"could not disable the string protocol (udp2) via the config API — this firmware ignores it. " +
|
||||
"An unauthenticated UDP packet to the string port can still fire relays. " +
|
||||
"Disable UDP2 in the device web UI, and rely on VLAN isolation + the signed event log. See dingtian-relay.md.",
|
||||
);
|
||||
}
|
||||
const secrets: Record<string, string | number> = { relayPassword };
|
||||
|
||||
// Set the device web login to the admin's chosen password (or a random one).
|
||||
// NOTE: cosmetic for the control plane — the CGI API needs NO auth (config
|
||||
// read/write + relay fire all work unauthenticated), so the login only gates
|
||||
// the interactive browser UI. We set it anyway (defence-in-depth) but it is
|
||||
// NOT a boundary; the signed event log is. See dingtian-relay.md.
|
||||
//
|
||||
// CRITICAL: only persist webPassword if the rotation VERIFIABLY took effect.
|
||||
// Otherwise the DB would claim a password the device doesn't have (the bug:
|
||||
// admin types a new pw, rotation fails on the wrong old-cred, DB still saves
|
||||
// the typed value, login stays admin/admin). On failure we warn instead.
|
||||
try {
|
||||
const newPassword = await this.#rotateWebLogin();
|
||||
secrets.webUser = this.#webUser;
|
||||
secrets.webPassword = newPassword;
|
||||
// The new password is now the device's CURRENT one — store it so a future
|
||||
// re-harden uses the right old cred.
|
||||
secrets.webPasswordCurrent = newPassword;
|
||||
applied.push("set the device web-UI login (verified on the device)");
|
||||
} catch (err) {
|
||||
warnings.push(
|
||||
`could not set the device web-UI login: ${(err as Error).message} ` +
|
||||
`The device login is UNCHANGED (still its previous password). The saved web password was NOT updated.`,
|
||||
);
|
||||
}
|
||||
|
||||
return { secrets, applied, warnings: warnings.length ? warnings : undefined };
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the device web-UI login to the DESIRED password (the admin's choice, or a
|
||||
* random one if none was given) via
|
||||
* `userset.cgi?<user>&<old_pass>&<user>&<new_pass>&`. The device validates the
|
||||
* OLD credentials, so we send #webPasswordCurrent (admin on a fresh device).
|
||||
* Response `&<code>&…&`, code 0 = success.
|
||||
*
|
||||
* After the rotation we VERIFY by attempting a no-op rotate using the NEW
|
||||
* password as the old cred — if that succeeds, the device really has the new
|
||||
* password (this is what catches the "DB says X but device is still admin/admin"
|
||||
* bug: a wrong old-cred makes the first call fail, and we never claim success).
|
||||
* Returns the password now live on the device.
|
||||
*/
|
||||
async #rotateWebLogin(): Promise<string> {
|
||||
const newPassword = this.#webPassword ?? randomBytes(12).toString("hex");
|
||||
const u = encodeURIComponent(this.#webUser);
|
||||
const setPath = (oldP: string, newP: string) =>
|
||||
`/userset.cgi?${u}&${encodeURIComponent(oldP)}&${u}&${encodeURIComponent(newP)}&`;
|
||||
|
||||
const res = await cgiGet(this.#host, this.#httpPort, setPath(this.#webPasswordCurrent, newPassword), this.#timeout, this.#localAddress);
|
||||
const code = res.split("&")[1];
|
||||
if (code !== "0") {
|
||||
throw new Error(
|
||||
`userset.cgi rejected (response "${res.trim()}") — the device's current password is probably not "${this.#webPasswordCurrent}". ` +
|
||||
`Set the correct current password, or factory-reset the device.`,
|
||||
);
|
||||
}
|
||||
|
||||
// VERIFY: a no-op rotate (new → new) only succeeds if the device truly has it.
|
||||
const verify = await cgiGet(this.#host, this.#httpPort, setPath(newPassword, newPassword), this.#timeout, this.#localAddress);
|
||||
if (verify.split("&")[1] !== "0") {
|
||||
throw new Error(`web-login change did not take effect (verify response "${verify.trim()}")`);
|
||||
}
|
||||
return newPassword;
|
||||
}
|
||||
|
||||
// --- config api internals ----------------------------------------------
|
||||
|
||||
async #readConfig(): Promise<Record<string, unknown>> {
|
||||
const raw = await configApi(this.#host, this.#httpPort, "/api/v2/config.cgi", "GET", null, this.#timeout, this.#sessionId, this.#localAddress);
|
||||
return JSON.parse(raw) as Record<string, unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write full config back, then WAIT for the device to apply it. The device
|
||||
* reboots on apply (~10s) and back-to-back writes onto a rebooting device are
|
||||
* silently lost — so we poll until the device is reachable again AND `verify`
|
||||
* confirms the change landed, retrying the write if needed.
|
||||
*
|
||||
* @param verify predicate over the re-read config; should return true once the
|
||||
* intended change is present.
|
||||
*/
|
||||
async #writeConfig(
|
||||
cfg: Record<string, unknown>,
|
||||
verify: (after: Record<string, unknown>) => boolean,
|
||||
): Promise<Record<string, unknown>> {
|
||||
// The set endpoint requires `"command":"setconfig"` injected after `status`
|
||||
// (the GET payload omits it). Rebuild preserving node order, command second.
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const [k, v] of Object.entries(cfg)) {
|
||||
out[k] = v;
|
||||
if (k === "status") out.command = "setconfig";
|
||||
}
|
||||
if (!("command" in out)) out.command = "setconfig";
|
||||
const payload = JSON.stringify(out);
|
||||
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
for (let attempt = 1; attempt <= 3; attempt++) {
|
||||
// POST. The device resets on apply, so the connection may drop — that's
|
||||
// expected, not failure.
|
||||
try {
|
||||
await configApi(this.#host, this.#httpPort, "/api/v2/config_set.cgi", "POST", payload, this.#timeout, this.#sessionId, this.#localAddress);
|
||||
} catch {
|
||||
// device likely reset on apply
|
||||
}
|
||||
|
||||
// Poll for the device to come back and the change to be present.
|
||||
for (let i = 0; i < 12; i++) {
|
||||
await sleep(2000);
|
||||
try {
|
||||
const after = await this.#readConfig();
|
||||
if (verify(after)) return after; // applied — return the landed config
|
||||
} catch {
|
||||
// still rebooting / unreachable — keep polling
|
||||
}
|
||||
}
|
||||
// Not applied within the window — likely the POST hit a rebooting device.
|
||||
// Loop and re-POST (now that it's reachable again).
|
||||
}
|
||||
throw new Error("dingtian: config write did not apply after retries");
|
||||
}
|
||||
|
||||
#linkDisabled(cfg: Record<string, unknown>): boolean {
|
||||
const ilr = cfg.input_link_relay as Record<string, unknown> | undefined;
|
||||
if (!ilr) return true; // no such block → nothing to link
|
||||
const flagOff = ilr.input_link_relay === 0;
|
||||
const mapsEmpty =
|
||||
!Array.isArray(ilr.on_action_on) ||
|
||||
(ilr.on_action_on as unknown[]).every((a) => Array.isArray(a) && a.length === 0);
|
||||
return flagOff || mapsEmpty;
|
||||
}
|
||||
|
||||
// --- internals ----------------------------------------------------------
|
||||
|
||||
#assertChannel(ch: number): void {
|
||||
if (!Number.isInteger(ch) || ch < 1 || ch > this.#channels) {
|
||||
throw new Error(`dingtian: channel ${ch} out of range (1..${this.#channels})`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read relay + input status via the AUTHENTICATED binary protocol (relay
|
||||
* command 0x00). Reply: `FF AA <session> 00 <relayBytes...> <inputBytes...>`,
|
||||
* each field `ceil(channels/8)` bytes, LSB-first (bit0 → relay/input 1).
|
||||
*
|
||||
* SECURITY: deliberately NOT the string protocol's `00` — that query has no
|
||||
* password field AND the string protocol can also *fire* relays, so leaving it
|
||||
* enabled defeats relay_pw entirely (an attacker sends `"11"` to open relay 1
|
||||
* with no auth). harden() disables the string protocol; status reads come here.
|
||||
*/
|
||||
async #status(): Promise<DingtianStatus> {
|
||||
const frame = readStatusFrame(this.#relayPassword);
|
||||
const reply = await binaryUdp(this.#host, this.#binaryPort, frame, this.#timeout, this.#localAddress);
|
||||
const width = Math.max(1, Math.ceil(this.#channels / 8));
|
||||
// header: FF AA session 00 (4 bytes) + relay field + input field
|
||||
if (reply.length < 4 + width * 2) {
|
||||
throw new Error(`dingtian: short binary status reply (${reply.length} bytes)`);
|
||||
}
|
||||
const relayVal = reply.readUIntLE(4, width);
|
||||
const inputVal = reply.readUIntLE(4 + width, width);
|
||||
const relays: boolean[] = [];
|
||||
const inputs: boolean[] = [];
|
||||
for (let i = 0; i < this.#channels; i++) {
|
||||
const high = (inputVal & (1 << i)) !== 0;
|
||||
relays.push((relayVal & (1 << i)) !== 0);
|
||||
// active = differs from the resting level (a press pulls the line).
|
||||
inputs.push(high !== this.#restingHigh);
|
||||
}
|
||||
return { relays, inputs, channels: this.#channels };
|
||||
}
|
||||
|
||||
#startPolling(): void {
|
||||
if (this.#poll) return;
|
||||
const tick = async () => {
|
||||
let inputs: boolean[];
|
||||
try {
|
||||
inputs = await this.readInputs();
|
||||
} catch {
|
||||
return; // transient; try again next tick
|
||||
}
|
||||
const prev = this.#last;
|
||||
this.#last = inputs;
|
||||
if (!prev) return; // first sample establishes a baseline, no events
|
||||
const at = new Date().toISOString();
|
||||
for (let i = 0; i < inputs.length; i++) {
|
||||
if (inputs[i] === prev[i]) continue;
|
||||
const event: InputEvent = {
|
||||
input: i + 1,
|
||||
edge: inputs[i] ? "pressed" : "released",
|
||||
at,
|
||||
};
|
||||
for (const cb of this.#subs) cb(event);
|
||||
}
|
||||
};
|
||||
// ~50ms poll: a button press is held well longer than this.
|
||||
this.#poll = setInterval(() => void tick(), 50);
|
||||
}
|
||||
|
||||
#stopPolling(): void {
|
||||
if (this.#poll) {
|
||||
clearInterval(this.#poll);
|
||||
this.#poll = null;
|
||||
this.#last = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const dingtianDriver: AccessDriver = {
|
||||
id: "dingtian",
|
||||
category: "access",
|
||||
label: "Dingtian relay controller",
|
||||
description:
|
||||
"Dingtian network relay+input board (UDP). Inputs are decoupled from relays — enables host-in-the-loop entry. Unauthenticated UDP: isolate the VLAN.",
|
||||
transports: ["udp"],
|
||||
pushesToBackend: true, // HTTP-pushes input/button events to the backend (Input Link URL)
|
||||
configFields: [
|
||||
hostField,
|
||||
{ ...portField(60001), required: false, help: "Dingtian string protocol UDP port — status read (default 60001)." },
|
||||
{ key: "binaryPort", label: "Binary protocol port", type: "port", required: false, default: 60000, help: "Dingtian binary protocol UDP port — authenticated relay control (default 60000)." },
|
||||
{ key: "httpPort", label: "HTTP config port", type: "port", required: false, default: 80, help: "Device web/config-API port (default 80)." },
|
||||
{ key: "channels", label: "Channels (relays/inputs)", type: "number", required: true, default: 4 },
|
||||
{
|
||||
key: "pulseMs",
|
||||
label: "Pulse open (ms)",
|
||||
type: "number",
|
||||
required: false,
|
||||
default: 500,
|
||||
help: "Momentary relay pulse; the barrier operator owns the close.",
|
||||
},
|
||||
{
|
||||
key: "inputRestingHigh",
|
||||
label: "Inputs idle HIGH",
|
||||
type: "boolean",
|
||||
required: false,
|
||||
default: true,
|
||||
help: "This board idles inputs HIGH (status 1111); a press pulls LOW.",
|
||||
},
|
||||
{ key: "timeoutMs", label: "Timeout (ms)", type: "number", required: false, default: 2000 },
|
||||
// Device web-UI login. webPassword = the password you WANT (blank → a random
|
||||
// one is generated). webPasswordCurrent = the device's EXISTING password, used
|
||||
// as the old credential to change it (defaults to "admin" on a fresh device).
|
||||
// On a verified change, the new password is stored as both the saved login and
|
||||
// the current one. (Gates only the browser UI — CGI control plane is open.)
|
||||
{ key: "webUser", label: "Device web username", type: "string", required: false, default: "admin", help: "Device web-UI login user (default admin)." },
|
||||
{ key: "webPassword", label: "New device web password", type: "secret", required: false, help: "The password to SET on the device web UI. Leave blank to auto-generate. Applied + verified on save." },
|
||||
{ key: "webPasswordCurrent", label: "Current device web password", type: "secret", required: false, help: "The device's existing web password (default admin on a fresh device). Needed to change it." },
|
||||
],
|
||||
create: (c) => new DingtianController(c),
|
||||
};
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { AccessControlDevice, DeviceHealth } from "../interfaces.js";
|
||||
import type { AccessDriver, DeviceConfig } from "../registry.js";
|
||||
import { stubLog } from "./common.js";
|
||||
|
||||
// Stub access controller — a no-op barrier for BENCH TESTING the entry/exit/permit
|
||||
// flows without real relay hardware. `pulseOpen` just logs "intent to open"; it
|
||||
// performs no device I/O, so it can stand in on a lane while the real
|
||||
// [[dingtian-relay]] isn't connected. NOT for production. See first-run-setup.md.
|
||||
|
||||
class StubAccess implements AccessControlDevice {
|
||||
readonly driverId = "stub-access";
|
||||
constructor(_config: DeviceConfig) {}
|
||||
async connect(): Promise<void> {}
|
||||
async disconnect(): Promise<void> {}
|
||||
async healthCheck(): Promise<DeviceHealth> {
|
||||
return { status: "ready", detail: "stub (no real barrier)" };
|
||||
}
|
||||
async pulseOpen(doorId: number): Promise<void> {
|
||||
stubLog(this.driverId, `pulseOpen door ${doorId} (stub — no relay fired)`);
|
||||
}
|
||||
async getDoorStatus(): Promise<"open" | "closed"> {
|
||||
return "closed";
|
||||
}
|
||||
}
|
||||
|
||||
export const stubAccessDriver: AccessDriver = {
|
||||
id: "stub-access",
|
||||
category: "access",
|
||||
label: "Stub barrier (bench testing — no relay)",
|
||||
description:
|
||||
"A no-op access controller for testing the flows without hardware. pulseOpen only logs; no relay is fired. Not for production.",
|
||||
transports: ["tcp-ip"],
|
||||
configFields: [],
|
||||
create: (c) => new StubAccess(c),
|
||||
};
|
||||
@@ -1,263 +0,0 @@
|
||||
import { networkInterfaces } from "node:os";
|
||||
import uhppoted, { type Controller, type Ctx } from "uhppoted";
|
||||
import type { AccessControlDevice, DeviceHealth } from "../interfaces.js";
|
||||
import type {
|
||||
AccessDriver,
|
||||
DeviceConfig,
|
||||
DiscoveredDevice,
|
||||
} from "../registry.js";
|
||||
import { hostField, stubLog } from "./common.js";
|
||||
|
||||
// `uhppoted` is CommonJS — import the default and destructure (named ESM imports
|
||||
// don't resolve off a CJS module under NodeNext).
|
||||
const { Config, getDevices, getStatus, openDoor } = uhppoted;
|
||||
|
||||
// Every uhppoted call binds a UDP listener on :60001 for replies. Concurrent
|
||||
// calls collide on that port (EACCES / dropped replies → spurious timeouts), so
|
||||
// we serialize ALL controller I/O through one queue. UDP request/response is
|
||||
// fast, so serial throughput is fine for a parking host. This is why parallel
|
||||
// discovery + health checks were timing out.
|
||||
let chain: Promise<unknown> = Promise.resolve();
|
||||
function serialize<T>(fn: () => Promise<T>): Promise<T> {
|
||||
const run = chain.then(fn, fn);
|
||||
// keep the chain alive regardless of this call's outcome
|
||||
chain = run.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
return run;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute subnet-directed broadcast addresses (e.g. 10.0.10.255) for every
|
||||
* non-internal IPv4 interface.
|
||||
*
|
||||
* Why this matters: the uhppoted lib only enables SO_BROADCAST when the target
|
||||
* matches a *subnet-directed* broadcast of a local interface — it does NOT
|
||||
* recognise the global 255.255.255.255, so broadcasting there fails with EACCES.
|
||||
* We must broadcast to the per-interface address (e.g. 10.0.10.255) instead.
|
||||
*/
|
||||
interface Iface {
|
||||
network: number[]; // ip & mask, per octet
|
||||
mask: number[];
|
||||
broadcast: string;
|
||||
}
|
||||
|
||||
function localIfaces(): Iface[] {
|
||||
const out: Iface[] = [];
|
||||
for (const ifaces of Object.values(networkInterfaces())) {
|
||||
for (const i of ifaces ?? []) {
|
||||
if (i.family !== "IPv4" || i.internal) continue;
|
||||
const ip = i.address.split(".").map(Number);
|
||||
const mask = i.netmask.split(".").map(Number);
|
||||
if (ip.length !== 4 || mask.length !== 4) continue;
|
||||
out.push({
|
||||
network: ip.map((o, k) => o & mask[k]!),
|
||||
mask,
|
||||
broadcast: ip.map((o, k) => (o & mask[k]!) | (~mask[k]! & 0xff)).join("."),
|
||||
});
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function subnetBroadcastAddrs(): string[] {
|
||||
return localIfaces().map((i) => i.broadcast);
|
||||
}
|
||||
|
||||
/** Broadcast target for discovery: explicit override, else first subnet bcast. */
|
||||
function discoveryBroadcast(): string {
|
||||
return (
|
||||
process.env.UHPPOTE_BROADCAST ?? subnetBroadcastAddrs()[0] ?? "255.255.255.255"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The subnet-directed broadcast for the interface that `host` belongs to. The
|
||||
* uhppoted Config's broadcast address governs reply routing even for unicast
|
||||
* ops, so it must match the TARGET's subnet (not just the first interface) or
|
||||
* the reply is missed → timeout.
|
||||
*/
|
||||
function broadcastForHost(host: string): string {
|
||||
const ip = host.split(".").map(Number);
|
||||
if (ip.length === 4) {
|
||||
for (const i of localIfaces()) {
|
||||
if (ip.every((o, k) => (o & i.mask[k]!) === i.network[k])) return i.broadcast;
|
||||
}
|
||||
}
|
||||
return discoveryBroadcast();
|
||||
}
|
||||
|
||||
// Real UHPPOTE access-control driver, backed by the official `uhppoted` lib.
|
||||
// Implements AccessControlDevice (intent-only relay — "a barrier is not a door";
|
||||
// the controller/barrier operator owns physical safety). See
|
||||
// wiki/entities/uhppote-controller.md and wiki/concepts/barrier-not-a-door.md.
|
||||
//
|
||||
// SECURITY: the UHPPOTE protocol is unauthenticated UDP (port 60000). This driver
|
||||
// assumes the controller sits on an isolated VLAN reachable only by the host.
|
||||
// See wiki/concepts/uhppote-udp-protocol.md and network-isolation.md.
|
||||
|
||||
/**
|
||||
* uhppoted context broadcasting to a specific address on :60000, listening for
|
||||
* replies on :60001.
|
||||
*/
|
||||
function buildCtxFor(broadcast: string, timeoutMs = 5000): Ctx {
|
||||
return {
|
||||
config: new Config(
|
||||
"parking",
|
||||
"0.0.0.0",
|
||||
`${broadcast}:60000`,
|
||||
"0.0.0.0:60001",
|
||||
timeoutMs,
|
||||
[],
|
||||
false,
|
||||
),
|
||||
locale: "en-US",
|
||||
};
|
||||
}
|
||||
|
||||
/** Default context for non-discovery ops (status/open use a unicast host). */
|
||||
function buildCtx(timeoutMs = 5000): Ctx {
|
||||
return buildCtxFor(discoveryBroadcast(), timeoutMs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Broadcast targets to try for discovery. An explicit UHPPOTE_BROADCAST wins;
|
||||
* otherwise every local subnet-directed broadcast (a host may have several
|
||||
* interfaces — LAN, VPN, docker — and the controller is on only one).
|
||||
*/
|
||||
function discoveryBroadcasts(): string[] {
|
||||
const override = process.env.UHPPOTE_BROADCAST;
|
||||
if (override) return [override];
|
||||
const addrs = subnetBroadcastAddrs();
|
||||
return addrs.length > 0 ? addrs : ["255.255.255.255"];
|
||||
}
|
||||
|
||||
class UhppoteAccessControl implements AccessControlDevice {
|
||||
readonly driverId = "uhppote";
|
||||
readonly #controller: Controller;
|
||||
readonly #ctx: Ctx;
|
||||
|
||||
constructor(config: DeviceConfig) {
|
||||
const serial = Number(config.serial);
|
||||
const address = config.host ? String(config.host) : undefined;
|
||||
const protocol = config.protocol === "tcp" ? "tcp" : "udp";
|
||||
|
||||
// Addressable descriptor when a host is given; otherwise rely on UDP
|
||||
// broadcast discovery by serial.
|
||||
this.#controller = address ? { id: serial, address, protocol } : serial;
|
||||
|
||||
// The Config broadcast must match the target host's subnet (it governs
|
||||
// reply routing even for unicast), else replies are missed → timeout.
|
||||
const timeoutMs = config.timeoutMs ? Number(config.timeoutMs) : 5000;
|
||||
this.#ctx = address
|
||||
? buildCtxFor(broadcastForHost(address), timeoutMs)
|
||||
: buildCtx(timeoutMs);
|
||||
}
|
||||
|
||||
async connect(): Promise<void> {
|
||||
// No persistent socket to open (request/response over UDP); verify reachability.
|
||||
await this.healthCheck();
|
||||
}
|
||||
|
||||
async disconnect(): Promise<void> {
|
||||
stubLog(this.driverId, "disconnect (stateless udp — nothing to close)");
|
||||
}
|
||||
|
||||
async healthCheck(): Promise<DeviceHealth> {
|
||||
try {
|
||||
await serialize(() => getStatus(this.#ctx, this.#controller));
|
||||
return { status: "ready" };
|
||||
} catch (err) {
|
||||
return { status: "offline", detail: (err as Error).message };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Express intent to open a door (1–4). NEVER timed/forced closed against a
|
||||
* vehicle — auto-close/anti-crush is the barrier operator's firmware.
|
||||
*/
|
||||
async pulseOpen(doorId: number): Promise<void> {
|
||||
const res = await serialize(() =>
|
||||
openDoor(this.#ctx, this.#controller, doorId),
|
||||
);
|
||||
if (!res.opened) {
|
||||
throw new Error(`uhppote: door ${doorId} not opened (deviceId ${res.deviceId})`);
|
||||
}
|
||||
}
|
||||
|
||||
async getDoorStatus(): Promise<"open" | "closed"> {
|
||||
// The UHPPOTE status payload carries per-door state; without a confirmed
|
||||
// wiring of door sensors we report the safe default until the real status
|
||||
// mapping is added. (Status is fetched to prove reachability.)
|
||||
await serialize(() => getStatus(this.#ctx, this.#controller));
|
||||
return "closed";
|
||||
}
|
||||
}
|
||||
|
||||
export const uhppoteDriver: AccessDriver & {
|
||||
discover(): Promise<DiscoveredDevice[]>;
|
||||
} = {
|
||||
id: "uhppote",
|
||||
category: "access",
|
||||
label: "UHPPOTE controller",
|
||||
description:
|
||||
"UHPPOTE Wiegand 26/34 network controller via the official uhppoted lib. Unauthenticated UDP — isolate the VLAN.",
|
||||
transports: ["udp", "tcp"],
|
||||
// UDP broadcast discovery (get-devices): every controller on the LAN answers
|
||||
// with its serial, IP, and firmware. Broadcasts on every local subnet (the
|
||||
// controller is on only one interface) and dedupes by serial.
|
||||
// See wiki/concepts/device-discovery.md.
|
||||
async discover(): Promise<DiscoveredDevice[]> {
|
||||
const bySerial = new Map<number, DiscoveredDevice>();
|
||||
// Serial, not parallel: each getDevices binds :60001, so concurrent scans
|
||||
// across interfaces collide (EACCES / dropped replies).
|
||||
for (const bcast of discoveryBroadcasts()) {
|
||||
let found;
|
||||
try {
|
||||
found = await serialize(() => getDevices(buildCtxFor(bcast, 3000)));
|
||||
} catch {
|
||||
continue; // a dead interface shouldn't fail the whole scan
|
||||
}
|
||||
for (const d of found) {
|
||||
bySerial.set(d.device.serialNumber, {
|
||||
id: String(d.device.serialNumber),
|
||||
label: `UHPPOTE ${d.device.serialNumber} @ ${d.device.address}`,
|
||||
config: { serial: d.device.serialNumber, host: d.device.address, protocol: "udp" },
|
||||
info: {
|
||||
address: d.device.address,
|
||||
netmask: d.device.netmask,
|
||||
gateway: d.device.gateway,
|
||||
MAC: d.device.MAC,
|
||||
firmware: d.device.version,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
return [...bySerial.values()];
|
||||
},
|
||||
configFields: [
|
||||
{
|
||||
key: "serial",
|
||||
label: "Controller serial number",
|
||||
type: "number",
|
||||
required: true,
|
||||
help: "Printed on the controller (e.g. 405419896).",
|
||||
},
|
||||
{ ...hostField, required: false, help: "Optional: target a specific IP instead of UDP broadcast. Isolated VLAN only." },
|
||||
{
|
||||
key: "protocol",
|
||||
label: "Protocol",
|
||||
type: "select",
|
||||
required: false,
|
||||
default: "udp",
|
||||
options: [
|
||||
{ value: "udp", label: "UDP (default)" },
|
||||
{ value: "tcp", label: "TCP (newer firmware)" },
|
||||
],
|
||||
},
|
||||
{ key: "doors", label: "Door count", type: "number", required: true, default: 4 },
|
||||
{ key: "timeoutMs", label: "Timeout (ms)", type: "number", required: false, default: 5000 },
|
||||
],
|
||||
create: (c) => new UhppoteAccessControl(c),
|
||||
};
|
||||
@@ -1,49 +0,0 @@
|
||||
import type { AccessControlDevice, DeviceHealth } from "../interfaces.js";
|
||||
import type { AccessDriver, DeviceConfig } from "../registry.js";
|
||||
import { hostField, portField, stubLog } from "./common.js";
|
||||
|
||||
// Access-control drivers. Each implements AccessControlDevice (intent-only relay
|
||||
// — "a barrier is not a door"). STUBS: connect/log only, no real protocol yet.
|
||||
|
||||
class StubAccessControl implements AccessControlDevice {
|
||||
constructor(
|
||||
readonly driverId: string,
|
||||
protected readonly config: DeviceConfig,
|
||||
) {}
|
||||
async connect(): Promise<void> {
|
||||
stubLog(this.driverId, `connect ${this.config.host}:${this.config.port}`);
|
||||
}
|
||||
async disconnect(): Promise<void> {
|
||||
stubLog(this.driverId, "disconnect");
|
||||
}
|
||||
async healthCheck(): Promise<DeviceHealth> {
|
||||
return { status: "ready", detail: "stub" };
|
||||
}
|
||||
async pulseOpen(doorId: number): Promise<void> {
|
||||
// Intent only — never times/forces a close against a vehicle.
|
||||
stubLog(this.driverId, `pulseOpen door=${doorId}`);
|
||||
}
|
||||
async getDoorStatus(): Promise<"open" | "closed"> {
|
||||
return "closed";
|
||||
}
|
||||
}
|
||||
|
||||
export const zktecoDriver: AccessDriver = {
|
||||
id: "zkteco",
|
||||
category: "access",
|
||||
label: "ZKTeco controller",
|
||||
description: "ZKTeco network access controller (TCP/IP). Reader + relay.",
|
||||
transports: ["tcp-ip"],
|
||||
configFields: [hostField, portField(4370), { key: "doors", label: "Door count", type: "number", required: true, default: 4 }],
|
||||
create: (c) => new StubAccessControl("zkteco", c),
|
||||
};
|
||||
|
||||
export const esp32RelayDriver: AccessDriver = {
|
||||
id: "esp32-relay",
|
||||
category: "access",
|
||||
label: "ESP32 relay controller",
|
||||
description: "Simple ESP32-based relay controller over the network.",
|
||||
transports: ["tcp-ip"],
|
||||
configFields: [hostField, portField(80), { key: "doors", label: "Relay channels", type: "number", required: true, default: 1 }],
|
||||
create: (c) => new StubAccessControl("esp32-relay", c),
|
||||
};
|
||||
@@ -1,57 +1,120 @@
|
||||
import type { CameraDevice, DeviceHealth, Snapshot, SnapshotContext } from "../interfaces.js";
|
||||
import type { CameraDriver, DeviceConfig } from "../registry.js";
|
||||
import type { CameraDriver, ConfigField, DeviceConfig } from "../registry.js";
|
||||
import { hostField, passwordField, portField, usernameField, stubLog } from "./common.js";
|
||||
import { digestGet } from "./http-digest.js";
|
||||
|
||||
// Camera drivers — entry/exit snapshot-on-event. The image is stored and
|
||||
// referenced from the signed event as an independent fraud-control record.
|
||||
// Hikvision (ISAPI) and Dahua (CGI) differ only in the snapshot URL. STUBS only.
|
||||
// Camera drivers — entry/exit snapshot-on-event. The host pulls a still over
|
||||
// HTTP when an event fires; the bytes are stored and referenced from the signed
|
||||
// event as an independent fraud-control record (the camera PULLS, it never pushes
|
||||
// to us). Hikvision (ISAPI) and Dahua (CGI) differ only in the snapshot URL and
|
||||
// channel encoding. Both use HTTP Digest auth (see ./http-digest.ts).
|
||||
//
|
||||
// VERIFIED on hardware (2026-06-15): a Hikvision unit at 10.0.10.121 returns a
|
||||
// 2688×1520 JPEG from /ISAPI/Streaming/channels/101/picture with Digest auth.
|
||||
// See wiki/entities/lpr-camera.md.
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 8000;
|
||||
|
||||
class HttpCamera implements CameraDevice {
|
||||
readonly #host: string;
|
||||
readonly #port: number;
|
||||
readonly #user: string;
|
||||
readonly #password: string;
|
||||
readonly #channel: number;
|
||||
readonly #timeout: number;
|
||||
// Source outbound from the device-facing NIC on a multi-homed host (the
|
||||
// multi-subnet source-address trap — see wiki/concepts/wsl-dev-networking.md).
|
||||
readonly #localAddress: string | undefined;
|
||||
|
||||
class StubCamera implements CameraDevice {
|
||||
constructor(
|
||||
readonly driverId: string,
|
||||
protected readonly config: DeviceConfig,
|
||||
protected readonly snapshotPath: string,
|
||||
) {}
|
||||
async connect(): Promise<void> {
|
||||
stubLog(this.driverId, `connect ${this.config.host} (${this.snapshotPath})`);
|
||||
}
|
||||
async disconnect(): Promise<void> {
|
||||
stubLog(this.driverId, "disconnect");
|
||||
config: DeviceConfig,
|
||||
/** Builds the snapshot path from the configured channel. */
|
||||
private readonly snapshotPath: (channel: number) => string,
|
||||
) {
|
||||
this.#host = String(config.host);
|
||||
this.#port = Number(config.port ?? 80);
|
||||
this.#user = String(config.username ?? "");
|
||||
this.#password = String(config.password ?? "");
|
||||
this.#channel = Number(config.channel ?? 1);
|
||||
this.#timeout = Number(config.timeoutMs ?? DEFAULT_TIMEOUT_MS);
|
||||
this.#localAddress = config.localAddress ? String(config.localAddress) : undefined;
|
||||
}
|
||||
|
||||
async connect(): Promise<void> {}
|
||||
async disconnect(): Promise<void> {}
|
||||
|
||||
async healthCheck(): Promise<DeviceHealth> {
|
||||
return { status: "ready", detail: "stub" };
|
||||
// The only honest liveness probe for a snapshot camera is to actually pull a
|
||||
// frame: it exercises reachability + auth + the path/channel in one shot.
|
||||
try {
|
||||
const res = await this.#get();
|
||||
if (res.status === 200) return { status: "ready", detail: `${res.body.length} bytes` };
|
||||
if (res.status === 401) return { status: "degraded", detail: "auth rejected (check username/password)" };
|
||||
return { status: "degraded", detail: `HTTP ${res.status}` };
|
||||
} catch (err) {
|
||||
return { status: "offline", detail: (err as Error).message };
|
||||
}
|
||||
}
|
||||
|
||||
async captureSnapshot(ctx: SnapshotContext): Promise<Snapshot> {
|
||||
// Real driver: GET http(s)://host{snapshotPath}, store bytes, return ref.
|
||||
stubLog(this.driverId, `captureSnapshot lane=${ctx.lane} ${ctx.direction}`);
|
||||
const res = await this.#get();
|
||||
if (res.status !== 200) {
|
||||
throw new Error(
|
||||
`${this.driverId} snapshot failed (${ctx.direction}): HTTP ${res.status}`,
|
||||
);
|
||||
}
|
||||
stubLog(this.driverId, `captureSnapshot ${ctx.direction} (${res.body.length} bytes)`);
|
||||
return {
|
||||
imageRef: `stub://${this.driverId}/lane${ctx.lane}/${ctx.direction}/${Date.now()}`,
|
||||
contentType: "image/jpeg",
|
||||
bytes: res.body,
|
||||
contentType: res.contentType || "image/jpeg",
|
||||
capturedAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
#get() {
|
||||
return digestGet({
|
||||
host: this.#host,
|
||||
port: this.#port,
|
||||
path: this.snapshotPath(this.#channel),
|
||||
user: this.#user,
|
||||
password: this.#password,
|
||||
timeoutMs: this.#timeout,
|
||||
localAddress: this.#localAddress,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const cameraConfigFields = [hostField, portField(80), usernameField, passwordField, { key: "channel", label: "Channel", type: "number" as const, required: false, default: 1 }];
|
||||
const channelField: ConfigField = {
|
||||
key: "channel",
|
||||
label: "Channel",
|
||||
type: "number",
|
||||
required: false,
|
||||
default: 1,
|
||||
};
|
||||
|
||||
const cameraConfigFields = [hostField, portField(80), usernameField, passwordField, channelField];
|
||||
|
||||
export const hikvisionDriver: CameraDriver = {
|
||||
id: "hikvision",
|
||||
category: "camera",
|
||||
label: "Hikvision camera",
|
||||
description: "Hikvision snapshot via ISAPI.",
|
||||
description: "Hikvision snapshot via ISAPI (HTTP Digest).",
|
||||
transports: ["tcp-ip"],
|
||||
configFields: cameraConfigFields,
|
||||
// /ISAPI/Streaming/channels/<id>/picture
|
||||
create: (c) => new StubCamera("hikvision", c, "/ISAPI/Streaming/channels/101/picture"),
|
||||
// ISAPI channel id: <channel><stream>, e.g. ch1 main = 101, ch2 main = 201.
|
||||
create: (c) =>
|
||||
new HttpCamera("hikvision", c, (ch) => `/ISAPI/Streaming/channels/${ch}01/picture`),
|
||||
};
|
||||
|
||||
export const dahuaDriver: CameraDriver = {
|
||||
id: "dahua",
|
||||
category: "camera",
|
||||
label: "Dahua camera",
|
||||
description: "Dahua snapshot via CGI.",
|
||||
description: "Dahua snapshot via CGI (HTTP Digest).",
|
||||
transports: ["tcp-ip"],
|
||||
configFields: cameraConfigFields,
|
||||
// /cgi-bin/snapshot.cgi?channel=<n>
|
||||
create: (c) => new StubCamera("dahua", c, "/cgi-bin/snapshot.cgi"),
|
||||
// Dahua channels are 0-based on the CGI; the admin enters 1-based.
|
||||
create: (c) =>
|
||||
new HttpCamera("dahua", c, (ch) => `/cgi-bin/snapshot.cgi?channel=${Math.max(0, ch - 1)}`),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { request as httpRequest } from "node:http";
|
||||
import type { IncomingMessage } from "node:http";
|
||||
|
||||
// Client-side HTTP Digest auth (RFC 2617, MD5, qop=auth) for talking TO devices
|
||||
// that challenge with `WWW-Authenticate: Digest` — e.g. Hikvision ISAPI cameras.
|
||||
// (The server-side counterpart, which VERIFIES device→backend pushes, lives in
|
||||
// apps/server/src/digest-auth.ts.) Devices on the isolated VLAN can't present a
|
||||
// trusted TLS cert, so plain-HTTP Digest is the available auth: the password is
|
||||
// never on the wire, only a nonce-keyed hash. See wiki/concepts/network-isolation.md.
|
||||
|
||||
const md5 = (s: string) => createHash("md5").update(s).digest("hex");
|
||||
|
||||
/** Parse a `WWW-Authenticate: Digest …` header into its k=v fields. */
|
||||
function parseChallenge(header: string): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
const re = /(\w+)=(?:"([^"]*)"|([^,]*))/g;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = re.exec(header))) out[m[1]!] = (m[2] ?? m[3] ?? "").trim();
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Build the `Authorization: Digest …` response value for a challenge. */
|
||||
function buildAuthHeader(
|
||||
c: Record<string, string>,
|
||||
user: string,
|
||||
password: string,
|
||||
method: string,
|
||||
uri: string,
|
||||
): string {
|
||||
const realm = c.realm ?? "";
|
||||
const nonce = c.nonce ?? "";
|
||||
const qop = c.qop?.split(",")[0]?.trim(); // server may offer "auth,auth-int"
|
||||
const ha1 = md5(`${user}:${realm}:${password}`);
|
||||
const ha2 = md5(`${method}:${uri}`);
|
||||
|
||||
const parts: string[] = [
|
||||
`username="${user}"`,
|
||||
`realm="${realm}"`,
|
||||
`nonce="${nonce}"`,
|
||||
`uri="${uri}"`,
|
||||
];
|
||||
|
||||
let response: string;
|
||||
if (qop === "auth") {
|
||||
const cnonce = randomBytes(8).toString("hex");
|
||||
const nc = "00000001";
|
||||
response = md5(`${ha1}:${nonce}:${nc}:${cnonce}:${qop}:${ha2}`);
|
||||
parts.push(`qop=${qop}`, `nc=${nc}`, `cnonce="${cnonce}"`);
|
||||
} else {
|
||||
// Legacy RFC 2069 (no qop) — Hikvision uses qop=auth, but be tolerant.
|
||||
response = md5(`${ha1}:${nonce}:${ha2}`);
|
||||
}
|
||||
parts.push(`response="${response}"`);
|
||||
if (c.opaque) parts.push(`opaque="${c.opaque}"`);
|
||||
return `Digest ${parts.join(", ")}`;
|
||||
}
|
||||
|
||||
export interface DigestGetResult {
|
||||
readonly status: number;
|
||||
readonly contentType: string;
|
||||
readonly body: Buffer;
|
||||
}
|
||||
|
||||
export interface DigestGetOptions {
|
||||
readonly host: string;
|
||||
readonly port: number;
|
||||
readonly path: string;
|
||||
readonly user: string;
|
||||
readonly password: string;
|
||||
readonly timeoutMs: number;
|
||||
/** Bind outbound to the device-facing NIC on a multi-homed host. */
|
||||
readonly localAddress?: string;
|
||||
}
|
||||
|
||||
function getOnce(
|
||||
o: DigestGetOptions,
|
||||
authHeader?: string,
|
||||
): Promise<{ res: IncomingMessage; body: Buffer }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const headers: Record<string, string> = {};
|
||||
if (authHeader) headers["authorization"] = authHeader;
|
||||
const req = httpRequest(
|
||||
{
|
||||
host: o.host,
|
||||
port: o.port,
|
||||
path: o.path,
|
||||
method: "GET",
|
||||
timeout: o.timeoutMs,
|
||||
localAddress: o.localAddress,
|
||||
headers,
|
||||
},
|
||||
(res) => {
|
||||
const chunks: Buffer[] = [];
|
||||
res.on("data", (c) => chunks.push(c as Buffer));
|
||||
res.on("end", () => resolve({ res, body: Buffer.concat(chunks) }));
|
||||
},
|
||||
);
|
||||
req.on("error", reject);
|
||||
req.on("timeout", () => req.destroy(new Error("digest GET timeout")));
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* GET a resource with HTTP Digest auth. Does the standard two-shot handshake:
|
||||
* the first request (no Authorization) draws a 401 + challenge, the second
|
||||
* carries the computed response. If the server doesn't challenge (200 straight
|
||||
* away, or no auth required), the first response is returned as-is.
|
||||
*/
|
||||
export async function digestGet(o: DigestGetOptions): Promise<DigestGetResult> {
|
||||
const first = await getOnce(o);
|
||||
if (first.res.statusCode !== 401) {
|
||||
return {
|
||||
status: first.res.statusCode ?? 0,
|
||||
contentType: String(first.res.headers["content-type"] ?? ""),
|
||||
body: first.body,
|
||||
};
|
||||
}
|
||||
|
||||
const challengeHeader = String(first.res.headers["www-authenticate"] ?? "");
|
||||
if (!/^digest/i.test(challengeHeader)) {
|
||||
// 401 but not Digest (e.g. Basic-only) — surface it; caller decides.
|
||||
return {
|
||||
status: 401,
|
||||
contentType: String(first.res.headers["content-type"] ?? ""),
|
||||
body: first.body,
|
||||
};
|
||||
}
|
||||
|
||||
const challenge = parseChallenge(challengeHeader);
|
||||
const auth = buildAuthHeader(challenge, o.user, o.password, "GET", o.path);
|
||||
const second = await getOnce(o, auth);
|
||||
return {
|
||||
status: second.res.statusCode ?? 0,
|
||||
contentType: String(second.res.headers["content-type"] ?? ""),
|
||||
body: second.body,
|
||||
};
|
||||
}
|
||||
@@ -2,10 +2,11 @@
|
||||
// module wires the catalog. Add a new device by registering it here.
|
||||
|
||||
import { registry } from "../registry.js";
|
||||
import { esp32RelayDriver, zktecoDriver } from "./access.js";
|
||||
import { uhppoteDriver } from "./access-uhppote.js";
|
||||
import { dingtianDriver } from "./access-dingtian.js";
|
||||
import { stubAccessDriver } from "./access-stub.js";
|
||||
import { dahuaDriver, hikvisionDriver } from "./camera.js";
|
||||
import { tcpipReaderDriver, wiegandReaderDriver } from "./reader.js";
|
||||
import { rongtaDriver } from "./printer-rongta.js";
|
||||
import { geeQrReaderDriver, tcpipReaderDriver, wiegandReaderDriver } from "./reader.js";
|
||||
|
||||
let registered = false;
|
||||
|
||||
@@ -13,21 +14,23 @@ let registered = false;
|
||||
export function registerBuiltinDrivers(): void {
|
||||
if (registered) return;
|
||||
registered = true;
|
||||
registry.register(uhppoteDriver);
|
||||
registry.register(zktecoDriver);
|
||||
registry.register(esp32RelayDriver);
|
||||
registry.register(dingtianDriver);
|
||||
registry.register(stubAccessDriver);
|
||||
registry.register(wiegandReaderDriver);
|
||||
registry.register(tcpipReaderDriver);
|
||||
registry.register(geeQrReaderDriver);
|
||||
registry.register(hikvisionDriver);
|
||||
registry.register(dahuaDriver);
|
||||
registry.register(rongtaDriver);
|
||||
}
|
||||
|
||||
export {
|
||||
uhppoteDriver,
|
||||
zktecoDriver,
|
||||
esp32RelayDriver,
|
||||
dingtianDriver,
|
||||
stubAccessDriver,
|
||||
wiegandReaderDriver,
|
||||
tcpipReaderDriver,
|
||||
geeQrReaderDriver,
|
||||
hikvisionDriver,
|
||||
dahuaDriver,
|
||||
rongtaDriver,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
import { Socket } from "node:net";
|
||||
import { request as httpRequest } from "node:http";
|
||||
import type {
|
||||
Device,
|
||||
DeviceHealth,
|
||||
MonitorableDevice,
|
||||
PrinterDevice,
|
||||
PrinterStatus,
|
||||
PrintReport,
|
||||
TicketData,
|
||||
} from "../interfaces.js";
|
||||
import type { ConfigField, DeviceConfig, PrinterDriver } from "../registry.js";
|
||||
import { hostField, portField, stubLog } from "./common.js";
|
||||
|
||||
// Rongta 80mm network thermal printer driver. Rongta RP-series printers (and the
|
||||
// many OEM clones that share their firmware) speak ESC/POS over a raw TCP socket
|
||||
// on port 9100 — the JetDirect/RAW convention. There is no auth on the print
|
||||
// socket; like the other field devices it lives on the isolated device VLAN.
|
||||
// See wiki/entities/rongta-printer.md and wiki/concepts/network-isolation.md.
|
||||
//
|
||||
// ROLES + FAILOVER: a lane has more than one printer. Each instance declares a
|
||||
// `role` (entry-dispenser at the lane / booth-receipt in the booth) and a
|
||||
// `failoverRank`. The entry flow prints on the highest-rank healthy printer for
|
||||
// the wanted role and falls back to the next — so if the outside dispenser is
|
||||
// offline, the booth printer prints the entry ticket as a backup. The driver
|
||||
// itself is role-agnostic; the role/rank live in config and the caller (server)
|
||||
// owns the failover selection. See wiki/concepts/printer-roles-failover.md.
|
||||
|
||||
// --- ESC/POS command bytes ----------------------------------------------------
|
||||
const ESC = 0x1b;
|
||||
const GS = 0x1d;
|
||||
const LF = 0x0a;
|
||||
|
||||
const INIT = Buffer.from([ESC, 0x40]); // ESC @ — reset to power-on defaults
|
||||
const ALIGN_CENTER = Buffer.from([ESC, 0x61, 0x01]); // ESC a 1
|
||||
const ALIGN_LEFT = Buffer.from([ESC, 0x61, 0x00]); // ESC a 0
|
||||
const BOLD_ON = Buffer.from([ESC, 0x45, 0x01]); // ESC E 1
|
||||
const BOLD_OFF = Buffer.from([ESC, 0x45, 0x00]); // ESC E 0
|
||||
const DOUBLE_ON = Buffer.from([GS, 0x21, 0x11]); // GS ! — double width+height
|
||||
const DOUBLE_OFF = Buffer.from([GS, 0x21, 0x00]);
|
||||
const FEED_AND_CUT = Buffer.from([ESC, 0x64, 0x04, GS, 0x56, 0x42, 0x00]); // feed 4, GS V B 0 partial cut
|
||||
|
||||
/** Encode a printable line as bytes (CP437/ASCII subset) + a line feed. */
|
||||
function line(text = ""): Buffer {
|
||||
return Buffer.concat([Buffer.from(text, "ascii"), Buffer.from([LF])]);
|
||||
}
|
||||
|
||||
/** Build the ESC/POS byte stream for a free-form text report (e.g. shift Z-report). */
|
||||
function renderReport(report: PrintReport): Buffer {
|
||||
return Buffer.concat([
|
||||
INIT,
|
||||
ALIGN_CENTER,
|
||||
BOLD_ON,
|
||||
line(report.title),
|
||||
BOLD_OFF,
|
||||
ALIGN_LEFT,
|
||||
line(),
|
||||
...report.lines.map((l) => line(l)),
|
||||
FEED_AND_CUT,
|
||||
]);
|
||||
}
|
||||
|
||||
/** Build the full ESC/POS byte stream for an entry ticket. */
|
||||
function renderTicket(data: TicketData): Buffer {
|
||||
return Buffer.concat([
|
||||
INIT,
|
||||
ALIGN_CENTER,
|
||||
BOLD_ON,
|
||||
DOUBLE_ON,
|
||||
line("PARKING"),
|
||||
DOUBLE_OFF,
|
||||
BOLD_OFF,
|
||||
line(),
|
||||
BOLD_ON,
|
||||
line(data.ticketId),
|
||||
BOLD_OFF,
|
||||
ALIGN_LEFT,
|
||||
line(),
|
||||
line(`Issued: ${data.issuedAt}`),
|
||||
FEED_AND_CUT,
|
||||
]);
|
||||
}
|
||||
|
||||
/** Open a TCP socket, write the bytes, wait for flush, then close. */
|
||||
function sendRaw(host: string, port: number, payload: Buffer, timeoutMs: number): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const sock = new Socket();
|
||||
let settled = false;
|
||||
const done = (err?: Error) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
sock.destroy();
|
||||
err ? reject(err) : resolve();
|
||||
};
|
||||
sock.setTimeout(timeoutMs);
|
||||
sock.on("timeout", () => done(new Error("timeout")));
|
||||
sock.on("error", done);
|
||||
sock.connect(port, host, () => {
|
||||
sock.write(payload, (err) => (err ? done(err) : done()));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// --- live status via the device's own status web page -------------------------
|
||||
// The Rongta board serves /prn_stat.htm, a small HTML table where the DEVICE has
|
||||
// already decoded the ESC/POS status bits into labelled Yes/No rows. We scrape
|
||||
// that rather than send raw `DLE EOT` ourselves: on this clone the DLE EOT reply
|
||||
// bytes don't follow the canonical bit layout (verified on hardware), so trusting
|
||||
// the device's own decode is the safe choice. See printer-status-monitoring.md.
|
||||
|
||||
/** The fault flags the status page reports (a subset of PrinterStatus). */
|
||||
type StatusFlag = "coverOpen" | "cutterError" | "paperEnd" | "paperNearEnd" | "offline";
|
||||
type StatusFlags = Partial<Record<StatusFlag, boolean>>;
|
||||
|
||||
/** Label text on the status page (NBSP/space-normalised, lowercased) → our key. */
|
||||
const STATUS_FIELDS: Record<string, StatusFlag> = {
|
||||
"cover is open": "coverOpen",
|
||||
"cutter error": "cutterError",
|
||||
"paper end": "paperEnd",
|
||||
"paper near end": "paperNearEnd",
|
||||
"printer off-line": "offline",
|
||||
};
|
||||
|
||||
/** GET the status page over HTTP and return the raw HTML. */
|
||||
function fetchStatusPage(host: string, httpPort: number, timeoutMs: number): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = httpRequest(
|
||||
{ host, port: httpPort, path: "/prn_stat.htm", method: "GET", timeout: timeoutMs },
|
||||
(res) => {
|
||||
let data = "";
|
||||
res.on("data", (c) => (data += c));
|
||||
res.on("end", () =>
|
||||
res.statusCode === 200
|
||||
? resolve(data)
|
||||
: reject(new Error(`status page HTTP ${res.statusCode}`)),
|
||||
);
|
||||
},
|
||||
);
|
||||
req.on("error", reject);
|
||||
req.on("timeout", () => req.destroy(new Error("status page timeout")));
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse /prn_stat.htm into boolean flags. Each fault is a `<TD>label</TD>
|
||||
* <TD>Yes|No</TD>` pair. Returns only the recognised fields; a missing field is
|
||||
* left undefined so the caller can detect an unexpected page (fail safe, not a
|
||||
* false "ok").
|
||||
*/
|
||||
function parseStatusPage(html: string): StatusFlags {
|
||||
const out: StatusFlags = {};
|
||||
const rowRe = /<TD[^>]*>([^<]*?)<\/TD>\s*<TD[^>]*>([^<]*?)<\/TD>/gi;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = rowRe.exec(html))) {
|
||||
if (m[1] === undefined || m[2] === undefined) continue;
|
||||
const label = m[1].replace(/ /gi, " ").replace(/\s+/g, " ").trim().toLowerCase();
|
||||
const value = m[2].replace(/ /gi, " ").trim().toLowerCase();
|
||||
const key = STATUS_FIELDS[label];
|
||||
if (key && (value === "yes" || value === "no")) {
|
||||
out[key] = value === "yes";
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** TCP connect probe — the print socket has no status protocol we rely on. */
|
||||
function probe(host: string, port: number, timeoutMs: number): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const sock = new Socket();
|
||||
let settled = false;
|
||||
const done = (err?: Error) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
sock.destroy();
|
||||
err ? reject(err) : resolve();
|
||||
};
|
||||
sock.setTimeout(timeoutMs);
|
||||
sock.on("timeout", () => done(new Error("timeout")));
|
||||
sock.on("error", done);
|
||||
sock.connect(port, host, () => done());
|
||||
});
|
||||
}
|
||||
|
||||
class RongtaPrinter implements PrinterDevice, MonitorableDevice {
|
||||
readonly driverId = "rongta";
|
||||
readonly #host: string;
|
||||
readonly #port: number;
|
||||
readonly #httpPort: number;
|
||||
readonly #timeout: number;
|
||||
|
||||
constructor(config: DeviceConfig) {
|
||||
this.#host = String(config.host);
|
||||
this.#port = config.port ? Number(config.port) : 9100;
|
||||
this.#httpPort = config.httpPort ? Number(config.httpPort) : 80;
|
||||
this.#timeout = config.timeoutMs ? Number(config.timeoutMs) : 3000;
|
||||
}
|
||||
|
||||
async connect(): Promise<void> {
|
||||
await this.healthCheck();
|
||||
}
|
||||
|
||||
async disconnect(): Promise<void> {
|
||||
stubLog(this.driverId, "disconnect");
|
||||
}
|
||||
|
||||
async healthCheck(): Promise<DeviceHealth> {
|
||||
try {
|
||||
await probe(this.#host, this.#port, this.#timeout);
|
||||
return { status: "ready" };
|
||||
} catch (err) {
|
||||
return { status: "offline", detail: (err as Error).message };
|
||||
}
|
||||
}
|
||||
|
||||
async printTicket(data: TicketData): Promise<void> {
|
||||
await sendRaw(this.#host, this.#port, renderTicket(data), this.#timeout);
|
||||
stubLog(this.driverId, `printed ticket ${data.ticketId}`);
|
||||
}
|
||||
|
||||
async printReport(report: PrintReport): Promise<void> {
|
||||
await sendRaw(this.#host, this.#port, renderReport(report), this.#timeout);
|
||||
stubLog(this.driverId, `printed report "${report.title}" (${report.lines.length} lines)`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Live operator-actionable status, scraped from the device's own status page.
|
||||
* The board decodes the ESC/POS status bits itself, so we trust its Yes/No
|
||||
* over hand-decoding this clone's non-standard DLE EOT reply.
|
||||
*
|
||||
* - status page unreachable → offline (the same signal as a dead printer),
|
||||
* - page reachable but a recognised field missing → degraded (don't claim
|
||||
* "ready" off a page we didn't fully understand — fail safe),
|
||||
* - any fault flag true → degraded,
|
||||
* - otherwise → ready.
|
||||
*/
|
||||
async readStatus(): Promise<PrinterStatus> {
|
||||
const checkedAt = new Date().toISOString();
|
||||
let html: string;
|
||||
try {
|
||||
html = await fetchStatusPage(this.#host, this.#httpPort, this.#timeout);
|
||||
} catch (err) {
|
||||
return { status: "offline", detail: (err as Error).message, checkedAt };
|
||||
}
|
||||
|
||||
const flags = parseStatusPage(html);
|
||||
const expected: StatusFlag[] = ["coverOpen", "cutterError", "paperEnd", "paperNearEnd", "offline"];
|
||||
const missing = expected.filter((k) => flags[k] === undefined);
|
||||
if (missing.length > 0) {
|
||||
return {
|
||||
status: "degraded",
|
||||
detail: `unexpected status page (missing: ${missing.join(", ")})`,
|
||||
checkedAt,
|
||||
};
|
||||
}
|
||||
|
||||
const faults = expected.filter((k) => flags[k] === true);
|
||||
const labels: Record<StatusFlag, string> = {
|
||||
paperEnd: "paper out",
|
||||
coverOpen: "cover open",
|
||||
cutterError: "cutter error",
|
||||
offline: "printer off-line",
|
||||
paperNearEnd: "paper low",
|
||||
};
|
||||
return {
|
||||
status: faults.length > 0 ? "degraded" : "ready",
|
||||
...flags,
|
||||
detail: faults.length > 0 ? faults.map((f) => labels[f]).join(", ") : undefined,
|
||||
checkedAt,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** Type guard: does this device carry a printer role (entry vs. booth)? */
|
||||
export type PrinterRole = "entry-dispenser" | "booth-receipt";
|
||||
|
||||
const roleField: ConfigField = {
|
||||
key: "role",
|
||||
label: "Role",
|
||||
type: "select",
|
||||
required: true,
|
||||
default: "entry-dispenser",
|
||||
options: [
|
||||
{ value: "entry-dispenser", label: "Entry dispenser (outside / at the lane)" },
|
||||
{ value: "booth-receipt", label: "Booth printer (receipts + backup)" },
|
||||
],
|
||||
help: "Entry tickets print on the entry dispenser, falling back to the booth printer if it is offline.",
|
||||
};
|
||||
|
||||
const rankField: ConfigField = {
|
||||
key: "failoverRank",
|
||||
label: "Failover rank",
|
||||
type: "number",
|
||||
required: false,
|
||||
default: 0,
|
||||
help: "Higher = tried first within the same role. The booth printer also backs up the entry dispenser.",
|
||||
};
|
||||
|
||||
export const rongtaDriver: PrinterDriver = {
|
||||
id: "rongta",
|
||||
category: "printer",
|
||||
label: "Rongta 80mm thermal printer",
|
||||
description:
|
||||
"Rongta RP-series 80mm thermal printer (and ESC/POS-compatible clones) over raw TCP (port 9100). No auth on the print socket — isolate the VLAN.",
|
||||
transports: ["tcp-ip"],
|
||||
configFields: [
|
||||
hostField,
|
||||
{ ...portField(9100), required: false, help: "Raw print socket (ESC/POS over JetDirect/RAW, default 9100)." },
|
||||
{ key: "httpPort", label: "Status web port", type: "port", required: false, default: 80, help: "Device status page (/prn_stat.htm) port for live monitoring (default 80)." },
|
||||
roleField,
|
||||
rankField,
|
||||
{ key: "timeoutMs", label: "Timeout (ms)", type: "number", required: false, default: 3000 },
|
||||
],
|
||||
create: (c) => new RongtaPrinter(c),
|
||||
};
|
||||
|
||||
/** Type guard exposed for callers that need to read a device's printer role. */
|
||||
export function isPrinter(device: Device): device is PrinterDevice {
|
||||
return typeof (device as Partial<PrinterDevice>).printTicket === "function";
|
||||
}
|
||||
@@ -58,3 +58,28 @@ export const tcpipReaderDriver: ReaderDriver = {
|
||||
configFields: [hostField, portField(9000)],
|
||||
create: (c) => new StubReader("tcpip-reader", c),
|
||||
};
|
||||
|
||||
// GEE/Fondvision QR access reader (e.g. GEE-QR-ER80). A PUSH device: on each scan
|
||||
// it HTTP-GETs our backend (/qa/mcardsea.<ext>) carrying its serial (cjihao); the
|
||||
// backend resolves the lane by matching that serial to this device's `serial`
|
||||
// config, decides, and replies the verdict (drives the beep). No host-side
|
||||
// connection — the adapter is a stub; the real integration is the HTTP endpoint
|
||||
// (apps/server routes/qr-reader.ts). See wiki/entities/gee-qr-er80.md.
|
||||
export const geeQrReaderDriver: ReaderDriver = {
|
||||
id: "gee-qr-reader",
|
||||
category: "reader",
|
||||
label: "GEE/Fondvision QR reader (HTTP push)",
|
||||
description:
|
||||
"QR/barcode access reader that HTTP-pushes each scan to the backend. Set its server IP/port to this host in the vendor tool; enter its serial here so scans resolve to this lane.",
|
||||
transports: ["tcp-ip"],
|
||||
configFields: [
|
||||
{
|
||||
key: "serial",
|
||||
label: "Device serial (cjihao)",
|
||||
type: "string",
|
||||
required: true,
|
||||
help: "The reader's serial as it reports in each scan (the `cjihao` field). Used to map scans to this lane.",
|
||||
},
|
||||
],
|
||||
create: (c) => new StubReader("gee-qr-reader", c),
|
||||
};
|
||||
|
||||
-83
@@ -1,83 +0,0 @@
|
||||
// Minimal ambient types for the `uhppoted` CommonJS module (no bundled types).
|
||||
// Only the surface we use; extend as we adopt more of the API.
|
||||
// Upstream: https://github.com/uhppoted/uhppoted-lib-nodejs
|
||||
declare module "uhppoted" {
|
||||
export class Config {
|
||||
constructor(
|
||||
name?: string,
|
||||
bindAddr?: string,
|
||||
broadcastAddr?: string,
|
||||
listenAddr?: string,
|
||||
timeout?: number,
|
||||
controllers?: unknown[],
|
||||
debug?: boolean,
|
||||
);
|
||||
}
|
||||
|
||||
/** Either a bare controller serial, or an addressable descriptor. */
|
||||
export type Controller =
|
||||
| number
|
||||
| { id: number; address?: string; protocol?: "udp" | "tcp" };
|
||||
|
||||
export interface Ctx {
|
||||
config: Config;
|
||||
locale?: string;
|
||||
}
|
||||
|
||||
export interface DiscoveredController {
|
||||
deviceId: number;
|
||||
device: {
|
||||
serialNumber: number;
|
||||
address: string;
|
||||
netmask: string;
|
||||
gateway: string;
|
||||
MAC: string;
|
||||
version: string;
|
||||
date: string;
|
||||
};
|
||||
}
|
||||
|
||||
/** UDP broadcast discovery — returns every controller answering on the LAN. */
|
||||
export function getDevices(ctx: Ctx): Promise<DiscoveredController[]>;
|
||||
|
||||
export function openDoor(
|
||||
ctx: Ctx,
|
||||
controller: Controller,
|
||||
door: number,
|
||||
): Promise<{ deviceId: number; opened: boolean }>;
|
||||
|
||||
export function getStatus(
|
||||
ctx: Ctx,
|
||||
controller: Controller,
|
||||
): Promise<Record<string, unknown>>;
|
||||
|
||||
export function getEvent(
|
||||
ctx: Ctx,
|
||||
controller: Controller,
|
||||
index: number,
|
||||
): Promise<Record<string, unknown>>;
|
||||
|
||||
export function getEventIndex(
|
||||
ctx: Ctx,
|
||||
controller: Controller,
|
||||
): Promise<{ deviceId: number; index: number }>;
|
||||
|
||||
export function setListener(
|
||||
ctx: Ctx,
|
||||
controller: Controller,
|
||||
address: string,
|
||||
port: number,
|
||||
): Promise<unknown>;
|
||||
|
||||
// CommonJS default export (module.exports = { ... }). Destructure from this.
|
||||
const uhppoted: {
|
||||
Config: typeof Config;
|
||||
getDevices: typeof getDevices;
|
||||
openDoor: typeof openDoor;
|
||||
getStatus: typeof getStatus;
|
||||
getEvent: typeof getEvent;
|
||||
getEventIndex: typeof getEventIndex;
|
||||
setListener: typeof setListener;
|
||||
};
|
||||
export default uhppoted;
|
||||
}
|
||||
@@ -5,5 +5,24 @@
|
||||
|
||||
export * from "./interfaces.js";
|
||||
export * from "./registry.js";
|
||||
export { registerBuiltinDrivers } from "./drivers/index.js";
|
||||
export { setDeviceLogSink, type DeviceLogSink } from "./drivers/common.js";
|
||||
// Built-in drivers: the registrar plus the individual driver objects (used by
|
||||
// hardware test scripts and any direct/programmatic device access).
|
||||
export {
|
||||
registerBuiltinDrivers,
|
||||
dingtianDriver,
|
||||
stubAccessDriver,
|
||||
wiegandReaderDriver,
|
||||
tcpipReaderDriver,
|
||||
geeQrReaderDriver,
|
||||
hikvisionDriver,
|
||||
dahuaDriver,
|
||||
rongtaDriver,
|
||||
} from "./drivers/index.js";
|
||||
export { isPrinter, type PrinterRole } from "./drivers/printer-rongta.js";
|
||||
export {
|
||||
orderForRole,
|
||||
printWithFailover,
|
||||
NoPrinterAvailableError,
|
||||
type PrinterInstance,
|
||||
} from "./printer-routing.js";
|
||||
|
||||
@@ -14,7 +14,7 @@ export type DeviceCategory = "access" | "reader" | "camera" | "printer";
|
||||
|
||||
/** Lifecycle shared by every device adapter. */
|
||||
export interface Device {
|
||||
/** Stable id of the driver that produced this instance (e.g. "zkteco"). */
|
||||
/** Stable id of the driver that produced this instance (e.g. "dingtian"). */
|
||||
readonly driverId: string;
|
||||
connect(): Promise<void>;
|
||||
disconnect(): Promise<void>;
|
||||
@@ -28,13 +28,130 @@ export interface DeviceHealth {
|
||||
}
|
||||
|
||||
// --- Access control (barrier relay) --------------------------------------
|
||||
// ZKTeco, an ESP32 relay controller, UHPPOTE, etc. all implement this.
|
||||
// The Dingtian relay board (and any future relay controller) implements this.
|
||||
export interface AccessControlDevice extends Device {
|
||||
/** Express intent to open. NEVER timed/forced closed against a vehicle. */
|
||||
pulseOpen(doorId: number): Promise<void>;
|
||||
getDoorStatus(doorId: number): Promise<"open" | "closed">;
|
||||
}
|
||||
|
||||
// --- Inputs (buttons / dry contacts) -------------------------------------
|
||||
// Optional capability for controllers that expose host-readable inputs SEPARATE
|
||||
// from their relays — e.g. the Dingtian board. This is what enables host-in-the-
|
||||
// loop entry: a button press is reported to the host, which decides (print a
|
||||
// ticket) before commanding the relay — instead of the input auto-firing the
|
||||
// relay. See wiki/decisions/access-controller-button-flow.md.
|
||||
export interface InputDevice {
|
||||
/** Read the current state of all inputs (true = active/pressed). */
|
||||
readInputs(): Promise<boolean[]>;
|
||||
/**
|
||||
* Subscribe to input edges. Returns an unsubscribe fn. Implementations may
|
||||
* back this with hardware push or polling — the consumer doesn't care.
|
||||
*/
|
||||
onInput(cb: (event: InputEvent) => void): () => void;
|
||||
}
|
||||
|
||||
export interface InputEvent {
|
||||
/** 1-based input/channel index. */
|
||||
readonly input: number;
|
||||
/** Edge: pressed = went active, released = went inactive. */
|
||||
readonly edge: "pressed" | "released";
|
||||
readonly at: string; // ISO-8601
|
||||
}
|
||||
|
||||
/** Type guard: does this device expose host-readable inputs? */
|
||||
export function hasInputs(device: Device): device is Device & InputDevice {
|
||||
return (
|
||||
typeof (device as Partial<InputDevice>).readInputs === "function" &&
|
||||
typeof (device as Partial<InputDevice>).onInput === "function"
|
||||
);
|
||||
}
|
||||
|
||||
// --- Preconditions (device must be configured a certain way) -------------
|
||||
// Optional capability: a device that depends on specific on-device configuration
|
||||
// to work correctly for parking can report it. Example: the Dingtian board must
|
||||
// have `input_link_relay` DISABLED, else a button press auto-fires the relay and
|
||||
// defeats host-in-the-loop entry (the same trap as the UHPPOTE, but fixable here).
|
||||
// The app does not own full device config (that's the vendor's web UI) — it only
|
||||
// checks the few preconditions our flow depends on, and optionally fixes them.
|
||||
// See wiki/decisions/access-controller-button-flow.md.
|
||||
export interface PreconditionDevice {
|
||||
checkPreconditions(): Promise<PreconditionResult>;
|
||||
/** Apply automatic fixes for fixable issues; returns the re-checked result. */
|
||||
fixPreconditions(): Promise<PreconditionResult>;
|
||||
}
|
||||
|
||||
export interface PreconditionResult {
|
||||
readonly ok: boolean;
|
||||
readonly issues: PreconditionIssue[];
|
||||
}
|
||||
|
||||
export interface PreconditionIssue {
|
||||
readonly key: string;
|
||||
readonly message: string;
|
||||
/** True if fixPreconditions() can correct this automatically. */
|
||||
readonly fixable: boolean;
|
||||
}
|
||||
|
||||
export function hasPreconditions(
|
||||
device: Device,
|
||||
): device is Device & PreconditionDevice {
|
||||
return typeof (device as Partial<PreconditionDevice>).checkPreconditions === "function";
|
||||
}
|
||||
|
||||
// --- Push configuration (device → backend) -------------------------------
|
||||
// Optional capability: a device that can be told to HTTP-push its input/button
|
||||
// events to our backend (vs. the host polling it). The backend configures the
|
||||
// device with where to call and a shared-secret token embedded in the path.
|
||||
// The Dingtian board implements this via its "Input Link URL" feature.
|
||||
// See wiki/concepts/device-input-flow.md.
|
||||
export interface PushConfigurableDevice {
|
||||
configureInputPush(opts: PushConfig): Promise<void>;
|
||||
}
|
||||
|
||||
export interface PushConfig {
|
||||
/** Backend host the device should call (our IP on the device's subnet). */
|
||||
readonly host: string;
|
||||
readonly port: number;
|
||||
/** Path prefix the device appends `/<input>/<on|off>` to,
|
||||
* e.g. `/api/devices/dingtian/<deviceId>/input`. */
|
||||
readonly pathBase: string;
|
||||
/** HTTP Digest credentials the device authenticates the push with. */
|
||||
readonly auth: { user: string; password: string };
|
||||
}
|
||||
|
||||
export function hasPushConfig(
|
||||
device: Device,
|
||||
): device is Device & PushConfigurableDevice {
|
||||
return typeof (device as Partial<PushConfigurableDevice>).configureInputPush === "function";
|
||||
}
|
||||
|
||||
// --- Hardening (lock the device down) ------------------------------------
|
||||
// Optional capability: a device that can be hardened against a flat (no-VLAN)
|
||||
// network — disable unused protocols/channels, set a relay password, and change
|
||||
// the default web/config login. Returns any secrets the backend must persist to
|
||||
// keep talking to the device. See wiki/concepts/device-input-flow.md.
|
||||
export interface HardenableDevice {
|
||||
harden(): Promise<HardenResult>;
|
||||
}
|
||||
|
||||
export interface HardenResult {
|
||||
/** Secrets to persist in lane_devices so the backend can keep operating the
|
||||
* device (relay password, new web login). The backend merges these into the
|
||||
* stored config. */
|
||||
readonly secrets: Record<string, string | number>;
|
||||
/** Human-readable summary of what was changed (for logging/UI). */
|
||||
readonly applied: string[];
|
||||
/** Hardening steps that could NOT be applied (e.g. a firmware quirk), so the
|
||||
* admin knows a residual risk remains. Best-effort steps report here instead
|
||||
* of failing the whole harden. */
|
||||
readonly warnings?: string[];
|
||||
}
|
||||
|
||||
export function isHardenable(device: Device): device is Device & HardenableDevice {
|
||||
return typeof (device as Partial<HardenableDevice>).harden === "function";
|
||||
}
|
||||
|
||||
// --- Readers (RF / optical; TCP-IP or Wiegand) ---------------------------
|
||||
export interface ReaderDevice extends Device {
|
||||
/** Emits when a credential is read (card number, plate, QR payload, …). */
|
||||
@@ -57,24 +174,70 @@ export interface CameraDevice extends Device {
|
||||
}
|
||||
|
||||
export interface SnapshotContext {
|
||||
readonly lane: number;
|
||||
readonly direction: "entry" | "exit";
|
||||
}
|
||||
|
||||
export interface Snapshot {
|
||||
/** Storage reference for the captured image (file path / blob id). */
|
||||
readonly imageRef: string;
|
||||
/** The captured image bytes. The DRIVER fetches them over the network; the
|
||||
* CALLER (entry/exit flow) owns storage and minting a durable reference —
|
||||
* keeping the device adapter free of any filesystem/blob-store dependency. */
|
||||
readonly bytes: Buffer;
|
||||
readonly contentType: string;
|
||||
readonly capturedAt: string; // ISO-8601
|
||||
/** Storage reference (file path / blob id), set once the caller has stored
|
||||
* the bytes. Absent on the value the driver returns. */
|
||||
readonly imageRef?: string;
|
||||
}
|
||||
|
||||
// --- Printers (ticket dispenser / booth printer) -------------------------
|
||||
export interface TicketData {
|
||||
readonly ticketId: string;
|
||||
readonly lane: number;
|
||||
readonly issuedAt: string; // ISO-8601
|
||||
}
|
||||
|
||||
export interface PrinterDevice extends Device {
|
||||
printTicket(data: TicketData): Promise<void>;
|
||||
/** Print a free-form text report (a shift Z-report, a receipt). `lines` are
|
||||
* printed as-is; the driver adds a header/cut. Kept generic so the business
|
||||
* layer composes the content. See wiki/concepts/shift.md. */
|
||||
printReport(report: PrintReport): Promise<void>;
|
||||
}
|
||||
|
||||
export interface PrintReport {
|
||||
readonly title: string;
|
||||
readonly lines: readonly string[];
|
||||
}
|
||||
|
||||
// --- Live printer status (consumable / mechanical faults) ----------------
|
||||
// Optional capability: a printer that reports the operator-actionable faults a
|
||||
// basic `healthCheck` (reachability) can't see — paper out, cover open, cutter
|
||||
// jam. Used by the live status monitor so the booth knows BEFORE a driver presses
|
||||
// the entry button and no ticket comes out. The Rongta board exposes these via
|
||||
// its own status web page (it decodes the ESC/POS bits for us — more reliable
|
||||
// than trusting a clone's DLE EOT bit layout). See wiki/concepts/printer-status-monitoring.md.
|
||||
export interface PrinterStatus {
|
||||
/** Reachable + no fault = ready; reachable + fault = degraded; unreachable = offline. */
|
||||
readonly status: "ready" | "degraded" | "offline";
|
||||
/** Out of paper — the printer cannot print. */
|
||||
readonly paperEnd?: boolean;
|
||||
/** Paper low — still prints, but warn the operator to reload. */
|
||||
readonly paperNearEnd?: boolean;
|
||||
/** Cover/lid open — will not print. */
|
||||
readonly coverOpen?: boolean;
|
||||
/** Cutter jammed/errored. */
|
||||
readonly cutterError?: boolean;
|
||||
/** Printer reports itself off-line (its own flag, distinct from unreachable). */
|
||||
readonly offline?: boolean;
|
||||
/** Human-readable summary (e.g. "paper out", or the unreachable error). */
|
||||
readonly detail?: string;
|
||||
readonly checkedAt: string; // ISO-8601
|
||||
}
|
||||
|
||||
export interface MonitorableDevice {
|
||||
/** Richer, operator-actionable status beyond reachability. */
|
||||
readStatus(): Promise<PrinterStatus>;
|
||||
}
|
||||
|
||||
export function isMonitorable(device: Device): device is Device & MonitorableDevice {
|
||||
return typeof (device as Partial<MonitorableDevice>).readStatus === "function";
|
||||
}
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
// Printer routing: pick which printer prints a given job across a lane's
|
||||
// printers, with automatic failover. A lane has more than one printer — an
|
||||
// entry dispenser outside (where the driver takes the ticket) and a booth
|
||||
// printer inside (receipts, and a BACKUP for entry tickets if the dispenser is
|
||||
// offline). See wiki/concepts/printer-roles-failover.md.
|
||||
//
|
||||
// This is pure selection logic over (config, health) — no device I/O — so the
|
||||
// entry/exit flow can decide where to print without coupling to a transport.
|
||||
|
||||
import type { PrinterDevice } from "./interfaces.js";
|
||||
import type { PrinterRole } from "./drivers/printer-rongta.js";
|
||||
|
||||
/** A configured printer instance + its live adapter, as the caller holds them. */
|
||||
export interface PrinterInstance {
|
||||
readonly id: string;
|
||||
readonly role: PrinterRole;
|
||||
/** Higher = preferred within a role. Ties broken by id for determinism. */
|
||||
readonly failoverRank: number;
|
||||
readonly device: PrinterDevice;
|
||||
}
|
||||
|
||||
/**
|
||||
* Order the candidate printers for a job targeting `wantRole`, best-first.
|
||||
*
|
||||
* Rule: printers of the wanted role come first (highest rank first); the booth
|
||||
* printer is also a fallback for entry tickets, so when an entry ticket is
|
||||
* routed, booth-receipt printers follow the entry dispensers. The reverse is
|
||||
* deliberately NOT done — a receipt never prints on the outside dispenser.
|
||||
*/
|
||||
export function orderForRole(
|
||||
printers: readonly PrinterInstance[],
|
||||
wantRole: PrinterRole,
|
||||
): PrinterInstance[] {
|
||||
const fallbackRole: PrinterRole | null =
|
||||
wantRole === "entry-dispenser" ? "booth-receipt" : null;
|
||||
|
||||
const rank = (p: PrinterInstance): number => {
|
||||
if (p.role === wantRole) return 2;
|
||||
if (p.role === fallbackRole) return 1;
|
||||
return 0;
|
||||
};
|
||||
|
||||
return printers
|
||||
.filter((p) => rank(p) > 0)
|
||||
.sort((a, b) => {
|
||||
if (rank(a) !== rank(b)) return rank(b) - rank(a); // wanted role first
|
||||
if (a.failoverRank !== b.failoverRank) return b.failoverRank - a.failoverRank;
|
||||
return a.id < b.id ? -1 : a.id > b.id ? 1 : 0; // stable tiebreak
|
||||
});
|
||||
}
|
||||
|
||||
export class NoPrinterAvailableError extends Error {
|
||||
constructor(public readonly attempts: { id: string; error: string }[]) {
|
||||
super(
|
||||
attempts.length === 0
|
||||
? "no printer configured for this job"
|
||||
: `all ${attempts.length} candidate printer(s) failed: ${attempts
|
||||
.map((a) => `${a.id} (${a.error})`)
|
||||
.join(", ")}`,
|
||||
);
|
||||
this.name = "NoPrinterAvailableError";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Print `job` on the best healthy printer for `wantRole`, failing over down the
|
||||
* ordered list. Tries each candidate's print directly: a healthCheck race is
|
||||
* pointless when the print itself is the real reachability test, so we just
|
||||
* attempt the print and move on if it throws. Returns the id that succeeded.
|
||||
*
|
||||
* Throws {@link NoPrinterAvailableError} if every candidate fails — the caller
|
||||
* (entry flow) decides what that means (e.g. raise the barrier without a paper
|
||||
* ticket vs. hold). That policy is the flow's, not the printer's.
|
||||
*/
|
||||
export async function printWithFailover(
|
||||
printers: readonly PrinterInstance[],
|
||||
wantRole: PrinterRole,
|
||||
job: (device: PrinterDevice) => Promise<void>,
|
||||
): Promise<string> {
|
||||
const ordered = orderForRole(printers, wantRole);
|
||||
const attempts: { id: string; error: string }[] = [];
|
||||
for (const p of ordered) {
|
||||
try {
|
||||
await job(p.device);
|
||||
return p.id;
|
||||
} catch (err) {
|
||||
attempts.push({ id: p.id, error: (err as Error).message });
|
||||
}
|
||||
}
|
||||
throw new NoPrinterAvailableError(attempts);
|
||||
}
|
||||
@@ -27,21 +27,39 @@ export interface ConfigField {
|
||||
readonly help?: string;
|
||||
}
|
||||
|
||||
/** A JSON-serializable config value. Mostly flat scalars (host, port, credentials),
|
||||
* but some configs carry nested structure — e.g. an access controller's
|
||||
* `relays: [{ relay, direction, button? }]` map. See entry-exit-points.md. */
|
||||
export type ConfigValue =
|
||||
| string
|
||||
| number
|
||||
| boolean
|
||||
| null
|
||||
| ConfigValue[]
|
||||
| { [k: string]: ConfigValue };
|
||||
|
||||
/** Opaque per-instance config the admin fills in (host, port, credentials…). */
|
||||
export type DeviceConfig = Record<string, string | number | boolean>;
|
||||
export type DeviceConfig = Record<string, ConfigValue>;
|
||||
|
||||
/**
|
||||
* A driver: metadata describing a supported device model/family, the config
|
||||
* fields the admin must supply, and a factory that builds a live adapter.
|
||||
*/
|
||||
export interface DeviceDriver<T extends Device = Device> {
|
||||
readonly id: string; // stable, e.g. "zkteco", "esp32-relay", "hikvision"
|
||||
readonly id: string; // stable, e.g. "dingtian", "hikvision"
|
||||
readonly category: DeviceCategory;
|
||||
readonly label: string; // human name for the picker, e.g. "ZKTeco controller"
|
||||
readonly label: string; // human name for the picker, e.g. "Dingtian relay controller"
|
||||
readonly description: string;
|
||||
/** Transports/notes surfaced in the UI, e.g. ["tcp-ip"], ["wiegand"]. */
|
||||
readonly transports: readonly string[];
|
||||
readonly configFields: readonly ConfigField[];
|
||||
/**
|
||||
* True if the device calls BACK to our backend (HTTP push) and therefore needs
|
||||
* a backend IP configured at assign time. Pull-only devices (cameras poll a
|
||||
* snapshot, the relay is commanded) leave this false so the setup wizard hides
|
||||
* the "Backend push IP" field. See wiki/concepts/device-input-flow.md.
|
||||
*/
|
||||
readonly pushesToBackend?: boolean;
|
||||
/** Build a live adapter instance from validated config. */
|
||||
create(config: DeviceConfig): T;
|
||||
}
|
||||
@@ -53,7 +71,7 @@ export type PrinterDriver = DeviceDriver<PrinterDevice>;
|
||||
|
||||
/** A device found on the LAN by a driver's discovery scan. */
|
||||
export interface DiscoveredDevice {
|
||||
/** Identifier to pre-fill (e.g. UHPPOTE serial number). */
|
||||
/** Identifier to pre-fill (e.g. a serial number). */
|
||||
readonly id: string;
|
||||
readonly label: string;
|
||||
/** Config values to auto-fill into the setup form (host, serial, …). */
|
||||
@@ -63,9 +81,10 @@ export interface DiscoveredDevice {
|
||||
}
|
||||
|
||||
/**
|
||||
* Optional capability: a driver that can find devices on the LAN. UHPPOTE
|
||||
* implements this via the protocol's UDP broadcast discovery (get-devices);
|
||||
* cameras (ONVIF) and others may add it later. See wiki/concepts/device-discovery.md.
|
||||
* Optional capability: a driver that can find devices on the LAN (e.g. UDP
|
||||
* broadcast discovery). No bundled driver implements this yet — the Dingtian
|
||||
* board uses a fixed IP; cameras (ONVIF) or other UDP-discoverable devices may
|
||||
* add it later. See wiki/concepts/device-discovery.md.
|
||||
*/
|
||||
export interface DiscoverableDriver {
|
||||
discover(): Promise<DiscoveredDevice[]>;
|
||||
@@ -129,6 +148,11 @@ class DeviceRegistry {
|
||||
}
|
||||
return byCategory;
|
||||
}
|
||||
|
||||
/** Driver ids that push to the backend (need a backend IP at assign time). */
|
||||
pushCapable(): string[] {
|
||||
return [...this.#drivers.values()].filter((d) => d.pushesToBackend).map((d) => d.id);
|
||||
}
|
||||
}
|
||||
|
||||
export interface CatalogEntry {
|
||||
|
||||
@@ -13,38 +13,232 @@ export type Direction = "entry" | "exit";
|
||||
export type IdentitySource = "wiegand" | "lpr" | "qr" | "ticket" | "manual";
|
||||
|
||||
/**
|
||||
* An append-only parking event. Records are never mutated; corrections are new
|
||||
* A signed business-LEDGER event. Records are never mutated; corrections are new
|
||||
* events. `prevHash` chains each event to the previous one; `signature` is the
|
||||
* ATECC608 signature over the event contents. See wiki/append-only-event-chain.
|
||||
* ATECC608 signature over the canonical contents (which INCLUDE `payload`).
|
||||
* Distinct from device telemetry — see wiki/decisions/event-streams-split.md.
|
||||
*/
|
||||
export interface ParkingEvent {
|
||||
export interface LedgerEvent {
|
||||
readonly id: string;
|
||||
readonly index: number;
|
||||
readonly type: ParkingEventType;
|
||||
readonly type: LedgerEventType;
|
||||
readonly direction: Direction | null;
|
||||
readonly lane: number;
|
||||
readonly source: IdentitySource | null;
|
||||
/** Card number, plate, ticket id, etc. — depends on `source`. */
|
||||
readonly identity: string | null;
|
||||
/** Type-specific business data (amount, tariffVersionId, sessionRef…). Signed. */
|
||||
readonly payload: LedgerPayload | null;
|
||||
readonly occurredAt: string; // ISO-8601
|
||||
/** Hash of the previous event in the chain (hex). Null only for genesis. */
|
||||
readonly prevHash: string | null;
|
||||
/** ATECC608 signature over the canonical event payload (hex). */
|
||||
readonly signature: string;
|
||||
/** Which signer/key produced `signature` (verifiable across a signer swap). */
|
||||
readonly keyId: string;
|
||||
}
|
||||
|
||||
export type ParkingEventType =
|
||||
/** Business/accountability events that live in the SIGNED, hash-chained ledger. */
|
||||
export type LedgerEventType =
|
||||
| "vehicle_entry"
|
||||
| "vehicle_exit"
|
||||
| "payment"
|
||||
| "void"
|
||||
// Witness-grade: a host-commanded open, and an independently-observed open
|
||||
// (loop/sensor) — reconciled against each other.
|
||||
| "barrier_open_command"
|
||||
| "barrier_open_observed"
|
||||
// Manned-mode shift boundary: an operator takes over (shift_open) / hands over
|
||||
// with a takings summary (shift_z_report). See wiki/concepts/shift.md.
|
||||
| "shift_open"
|
||||
| "shift_z_report"
|
||||
| "anomaly";
|
||||
|
||||
/** How money was tendered (for payment events + the shift Z-report). */
|
||||
export type Tender = "cash" | "card";
|
||||
|
||||
/**
|
||||
* Type-specific data carried on a ledger event's `payload`. All amounts are
|
||||
* integer minor units in the named currency — never floats. Fields are optional
|
||||
* because they're event-type-specific; the producer fills what applies.
|
||||
*/
|
||||
export interface LedgerPayload {
|
||||
/** The parking_session this event concerns (entry/exit/payment/void). */
|
||||
readonly sessionRef?: string;
|
||||
/** payment: amount in minor units, its currency, and how it was tendered. */
|
||||
readonly amountMinor?: number;
|
||||
readonly currency?: string;
|
||||
readonly tender?: Tender;
|
||||
/** payment: which tariff_version priced it (reproducible repricing). */
|
||||
readonly tariffVersionId?: string;
|
||||
/** payment: gross/discount/net split when a validation applied. */
|
||||
readonly grossMinor?: number;
|
||||
readonly discountMinor?: number;
|
||||
/** FX-ready, deferred: rate applied (null/absent now). See open-questions #8. */
|
||||
readonly fxRate?: number | null;
|
||||
/** void / anomaly / override: a human/machine reason code. */
|
||||
readonly reason?: string;
|
||||
/** plate/vehicle from the vision service (advisory). */
|
||||
readonly plate?: string;
|
||||
readonly plateConfidence?: number;
|
||||
/** Free-form for forward-compat without a schema change. */
|
||||
readonly [k: string]: unknown;
|
||||
}
|
||||
|
||||
/** Operational device telemetry — UNSIGNED, prunable. NOT the ledger. */
|
||||
export type DeviceEventKind = "input" | "relay" | "status" | "read" | "snapshot";
|
||||
|
||||
/**
|
||||
* The composable rate card stored in a tariff_version.structure. Pure data the
|
||||
* fee function interprets — no rates in code. Stepped duration blocks + caps/grace;
|
||||
* a flat rate is just one block. See wiki/concepts/tariff.md.
|
||||
*/
|
||||
export interface TariffStructure {
|
||||
/** Free if exited within this (drop-off/turnaround). */
|
||||
readonly gracePeriodEntryMin: number;
|
||||
/** Billing granularity; partial increments round UP. */
|
||||
readonly incrementMin: number;
|
||||
/** Consumed in order as duration accrues; last block may be open-ended. */
|
||||
readonly blocks: readonly TariffBlock[];
|
||||
/** Cap per rolling 24h (null = no cap). */
|
||||
readonly dailyCapMinor: number | null;
|
||||
/** Flat charge when there's no entry id (admin may override at the moment). */
|
||||
readonly lostTicketMinor: number;
|
||||
/** Pay-on-foot walk-back window: minutes after payment to reach the car. */
|
||||
readonly gracePeriodExitMin: number;
|
||||
/** How an overstay top-up is charged. "reprice" = recompute(entry→now) − paid. */
|
||||
readonly overstay: "reprice";
|
||||
}
|
||||
|
||||
export interface TariffBlock {
|
||||
/** Upper bound of this block in minutes; null = open-ended (thereafter). */
|
||||
readonly uptoMin: number | null;
|
||||
readonly priceMinorPerIncrement: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute the parking fee (integer minor units) for a stay, from a TariffStructure.
|
||||
* PURE + deterministic + offline — the pay station calls it with asOf = now; the
|
||||
* result is fixed into a signed `payment` event, so it must be reproducible.
|
||||
*
|
||||
* Algorithm (wiki/concepts/tariff.md): round duration UP to incrementMin; free if
|
||||
* within entry grace; else walk the stay one rolling-24h segment at a time, charging
|
||||
* each increment at its block's rate (blocks consumed in order by cumulative minutes),
|
||||
* capping each segment at dailyCapMinor. Times are ISO-8601; bad input → 0 (caller
|
||||
* validates the tariff exists first).
|
||||
*/
|
||||
export function computeFee(
|
||||
enteredAt: string,
|
||||
asOf: string,
|
||||
tariff: TariffStructure,
|
||||
): number {
|
||||
const ms = Date.parse(asOf) - Date.parse(enteredAt);
|
||||
if (!Number.isFinite(ms) || ms <= 0) return 0;
|
||||
const rawMinutes = ms / 60_000;
|
||||
// Grace uses the RAW duration (a 10-min stay is free even if the increment is
|
||||
// 60 min — otherwise rounding-up would defeat the grace window).
|
||||
if (rawMinutes <= tariff.gracePeriodEntryMin) return 0;
|
||||
const inc = Math.max(1, tariff.incrementMin);
|
||||
const minutes = Math.ceil(rawMinutes / inc) * inc; // round UP to the increment
|
||||
|
||||
const DAY = 24 * 60;
|
||||
let total = 0;
|
||||
for (let segStart = 0; segStart < minutes; segStart += DAY) {
|
||||
const segEnd = Math.min(segStart + DAY, minutes);
|
||||
let segFee = 0;
|
||||
// The block ladder RESETS each rolling-24h day: `within` is minutes elapsed
|
||||
// WITHIN this day, so day 2 starts at the first block again (decision 2026-06-15).
|
||||
for (let within = 0; segStart + within < segEnd; within += inc) {
|
||||
segFee += rateAt(tariff.blocks, within);
|
||||
}
|
||||
if (tariff.dailyCapMinor != null) segFee = Math.min(segFee, tariff.dailyCapMinor);
|
||||
total += segFee;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an admin-authored tariff structure. Returns [] if valid, else a list
|
||||
* of human-readable problems. Pure — used by the composer route (and any caller)
|
||||
* so a malformed rate card can never be published. See wiki/concepts/tariff.md.
|
||||
*/
|
||||
export function validateTariffStructure(s: unknown): string[] {
|
||||
const errs: string[] = [];
|
||||
if (!s || typeof s !== "object") return ["structure must be an object"];
|
||||
const t = s as Partial<TariffStructure>;
|
||||
|
||||
const nonNegInt = (v: unknown, label: string) => {
|
||||
if (typeof v !== "number" || !Number.isInteger(v) || v < 0) errs.push(`${label} must be a non-negative integer`);
|
||||
};
|
||||
nonNegInt(t.gracePeriodEntryMin, "gracePeriodEntryMin");
|
||||
nonNegInt(t.gracePeriodExitMin, "gracePeriodExitMin");
|
||||
nonNegInt(t.lostTicketMinor, "lostTicketMinor");
|
||||
if (typeof t.incrementMin !== "number" || !Number.isInteger(t.incrementMin) || t.incrementMin < 1) {
|
||||
errs.push("incrementMin must be a positive integer");
|
||||
}
|
||||
if (t.dailyCapMinor != null) nonNegInt(t.dailyCapMinor, "dailyCapMinor");
|
||||
if (t.overstay !== "reprice") errs.push('overstay must be "reprice"');
|
||||
|
||||
if (!Array.isArray(t.blocks) || t.blocks.length === 0) {
|
||||
errs.push("blocks must be a non-empty array");
|
||||
} else {
|
||||
let prevBound = 0;
|
||||
t.blocks.forEach((b, i) => {
|
||||
const last = i === t.blocks!.length - 1;
|
||||
nonNegInt(b?.priceMinorPerIncrement, `blocks[${i}].priceMinorPerIncrement`);
|
||||
if (b?.uptoMin == null) {
|
||||
if (!last) errs.push(`blocks[${i}] is open-ended (uptoMin null) but not last`);
|
||||
} else {
|
||||
if (typeof b.uptoMin !== "number" || !Number.isInteger(b.uptoMin) || b.uptoMin <= prevBound) {
|
||||
errs.push(`blocks[${i}].uptoMin must be an integer greater than the previous block's bound (${prevBound})`);
|
||||
} else {
|
||||
prevBound = b.uptoMin;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
return errs;
|
||||
}
|
||||
|
||||
/** Price of the increment that starts at `cumulativeMin` — the block whose range
|
||||
* [prevUpto, uptoMin) contains it; the open-ended (uptoMin=null) block catches the rest. */
|
||||
function rateAt(blocks: readonly TariffBlock[], cumulativeMin: number): number {
|
||||
let prev = 0;
|
||||
for (const b of blocks) {
|
||||
if (b.uptoMin == null || cumulativeMin < b.uptoMin) return b.priceMinorPerIncrement;
|
||||
prev = b.uptoMin;
|
||||
void prev;
|
||||
}
|
||||
// No open-ended block and past the last bound: charge the last block's rate.
|
||||
return blocks.length ? blocks[blocks.length - 1]!.priceMinorPerIncrement : 0;
|
||||
}
|
||||
|
||||
export const ROLES: readonly Role[] = [
|
||||
"admin",
|
||||
"operator",
|
||||
"cashier",
|
||||
"readonly",
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* Signs the canonical bytes of an event for the append-only chain. This is the
|
||||
* abstraction over the [[atecc608]] secure element: the real, non-extractable
|
||||
* hardware key is ONE implementation. Whether the chip is wired is still
|
||||
* open-question #6, so the server ships a software signer in the meantime —
|
||||
* same interface, swappable with no business-logic change (the device-adapter
|
||||
* philosophy applied to signing). See wiki/concepts/append-only-event-chain.md.
|
||||
*
|
||||
* IMPORTANT: a software signer makes the chain self-consistent and detectably
|
||||
* tamper-evident, but NOT unforgeable by someone who owns the machine — only the
|
||||
* ATECC608 provides that. Don't conflate the two.
|
||||
*/
|
||||
export interface Signer {
|
||||
/** Stable id of the signer/key (e.g. "sw-hmac-v1", "atecc608-slot0"). Stored
|
||||
* alongside events so verification knows which key to check against. */
|
||||
readonly keyId: string;
|
||||
/** Sign the canonical payload; returns a hex signature. */
|
||||
sign(payload: string): string;
|
||||
/** Verify a signature over the payload (software signers can; the ATECC608
|
||||
* verifies via its public key). */
|
||||
verify(payload: string, signature: string): boolean;
|
||||
}
|
||||
|
||||
Generated
-19
@@ -50,9 +50,6 @@ importers:
|
||||
fastify-plugin:
|
||||
specifier: 6.0.0
|
||||
version: 6.0.0
|
||||
uhppoted:
|
||||
specifier: 0.9.0
|
||||
version: 0.9.0
|
||||
devDependencies:
|
||||
'@types/bcrypt':
|
||||
specifier: 6.0.0
|
||||
@@ -122,9 +119,6 @@ importers:
|
||||
'@parking/shared':
|
||||
specifier: workspace:*
|
||||
version: link:../shared
|
||||
uhppoted:
|
||||
specifier: 0.9.0
|
||||
version: 0.9.0
|
||||
devDependencies:
|
||||
'@types/node':
|
||||
specifier: 25.9.3
|
||||
@@ -1262,9 +1256,6 @@ packages:
|
||||
once@1.4.0:
|
||||
resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==}
|
||||
|
||||
os@0.1.2:
|
||||
resolution: {integrity: sha512-ZoXJkvAnljwvc56MbvhtKVWmSkzV712k42Is2mA0+0KTSRakq5XXuXpjZjgAt9ctzl51ojhQWakQQpmOvXWfjQ==}
|
||||
|
||||
path-scurry@2.0.2:
|
||||
resolution: {integrity: sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==}
|
||||
engines: {node: 18 || 20 || >=22}
|
||||
@@ -1467,10 +1458,6 @@ packages:
|
||||
engines: {node: '>=14.17'}
|
||||
hasBin: true
|
||||
|
||||
uhppoted@0.9.0:
|
||||
resolution: {integrity: sha512-7VDPNg4x31TETgMD3xp9NwVr+NvmZJ6CO8gTpyuRrdHu/UBGXw9/9kq8yiB0vR4opaUQPdvR8Gj373Ac/QWPwQ==}
|
||||
engines: {node: '>=14.18.3'}
|
||||
|
||||
undici-types@7.24.6:
|
||||
resolution: {integrity: sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==}
|
||||
|
||||
@@ -2357,8 +2344,6 @@ snapshots:
|
||||
dependencies:
|
||||
wrappy: 1.0.2
|
||||
|
||||
os@0.1.2: {}
|
||||
|
||||
path-scurry@2.0.2:
|
||||
dependencies:
|
||||
lru-cache: 11.5.1
|
||||
@@ -2586,10 +2571,6 @@ snapshots:
|
||||
|
||||
typescript@6.0.3: {}
|
||||
|
||||
uhppoted@0.9.0:
|
||||
dependencies:
|
||||
os: 0.1.2
|
||||
|
||||
undici-types@7.24.6: {}
|
||||
|
||||
util-deprecate@1.0.2: {}
|
||||
|
||||
+2
-2
@@ -35,9 +35,9 @@ wiki/
|
||||
- **Frontmatter** (YAML) on every wiki page:
|
||||
```yaml
|
||||
---
|
||||
type: source | entity | concept | decision | overview
|
||||
type: source | entity | concept | decision | overview | reference
|
||||
tags: [parking, ...]
|
||||
sources: [parking-system-architecture] # raw source slugs this draws from
|
||||
sources: [parking-system-architecture] # raw source slugs (omit/[] if not source-derived)
|
||||
updated: 2026-06-14
|
||||
status: settled | open # decisions only
|
||||
---
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
---
|
||||
type: concept
|
||||
tags: [parking, domain, business, anti-fraud, access-control]
|
||||
sources: []
|
||||
updated: 2026-06-15
|
||||
status: open
|
||||
---
|
||||
|
||||
# Anti-Passback
|
||||
|
||||
Stop one credential/ticket from getting **two cars in** without an exit between — the classic
|
||||
"pass the card/ticket back over the fence" abuse. A control on the entry validation, leaning on the
|
||||
session projection.
|
||||
|
||||
## The rule
|
||||
|
||||
An identity (ticket id, [[permit]] credential, or plate) **must not enter while it already has an
|
||||
OPEN [[parking-session|session]].** At entry:
|
||||
|
||||
```
|
||||
identify vehicle → is there already an OPEN session for this id?
|
||||
no → proceed (mint vehicle_entry, open)
|
||||
yes → passback violation → refuse or flag (see policy)
|
||||
```
|
||||
|
||||
This is a **fold over the signed [[append-only-event-chain]]** ("does an entry for this id exist
|
||||
with no matching exit?") — not a mutable in/out flag that could be edited. Same projection that
|
||||
powers [[capacity-occupancy]] and [[permit]] `maxConcurrent`.
|
||||
|
||||
## Interaction with the limits already designed
|
||||
|
||||
- **Transient ticket** — a single ticket id is inherently one session; a second entry on the same
|
||||
id is always a violation (or a re-print/duplication attempt).
|
||||
- **Permit** — passback is the *per-car* case of the permit's `maxConcurrent` ([[permit]]): a
|
||||
multi-car permit legitimately has several open sessions, but **the same car/credential** entering
|
||||
twice is still a violation. So enforce per-identity, *under* the permit's concurrency allowance.
|
||||
|
||||
## Policy (operator choice)
|
||||
|
||||
- **Hard** — refuse the second entry (strict; risks stranding a legitimate car after a *missed
|
||||
exit*, which is common — tailgated out, sensor missed).
|
||||
- **Soft** — allow but **flag an `anomaly`** (the type exists) for review. Safer against
|
||||
false-positives from missed exits, consistent with the append-only "record + flag, don't block"
|
||||
ethos elsewhere.
|
||||
- Likely **soft by default**, hard as an opt-in for high-control sites.
|
||||
|
||||
## Honest limits
|
||||
|
||||
- Depends on **reliable exit detection** — if exits are routinely missed (no exit loop/plate read),
|
||||
passback produces false positives; tune to the site's exit fidelity.
|
||||
- A spoofed/duplicated ticket QR is caught here (same id already open) — complements
|
||||
[[ticket-encoding]]'s opaque-id requirement.
|
||||
|
||||
## Open
|
||||
|
||||
- Default policy (soft/hard) and per-site override.
|
||||
- Grace for legitimate quick re-entry vs. the missed-exit false-positive.
|
||||
@@ -2,7 +2,7 @@
|
||||
type: concept
|
||||
tags: [parking, security, integrity]
|
||||
sources: [parking-system-architecture]
|
||||
updated: 2026-06-14
|
||||
updated: 2026-06-15
|
||||
---
|
||||
|
||||
# Append-Only Event Chain
|
||||
@@ -21,6 +21,101 @@ Three layered properties:
|
||||
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.
|
||||
against an authority the operator can't alter.
|
||||
|
||||
## Two event streams — the signed ledger vs. device telemetry (decision 2026-06-15)
|
||||
|
||||
These are **different concerns and live in different tables**:
|
||||
|
||||
- **`ledger_events`** — this signed, hash-chained, [[atecc608]]-signed **business ledger**:
|
||||
`vehicle_entry` / `vehicle_exit` / `payment` / `void` / `shift_z_report`, plus the witness-grade
|
||||
`barrier_open_command` / `barrier_open_observed` and `anomaly`. This is the anti-fraud record that
|
||||
[[reconciliation]] runs against; sessions/[[tariff]]/occupancy are projections over it. (This is
|
||||
the table formerly called `events`.)
|
||||
- **`device_events`** — **unsigned operational telemetry**: relay fired, printer paper-out, camera
|
||||
offline, reader read, raw input edges. High-volume, churny, **not** anti-fraud; may rotate/prune.
|
||||
Keeping it out of the signed chain keeps the ledger small and high-value.
|
||||
|
||||
> A raw button press is **device telemetry**, not a business fact. It lands in `device_events`; the
|
||||
> entry flow then mints a **signed `vehicle_entry`** in the ledger once a ticket prints and the
|
||||
> barrier is commanded. (This supersedes the earlier "every device event lands in the chain" framing
|
||||
> and the `input_received`-as-signed-event approach — see [[device-input-flow]].)
|
||||
|
||||
## 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.
|
||||
|
||||
### Business-layer event types (the ledger)
|
||||
|
||||
The [[parking-session]] domain folds over these **signed ledger** events:
|
||||
|
||||
- `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**.
|
||||
- `shift_z_report` — the signed per-[[shift]] takings summary.
|
||||
|
||||
A session is a **projection** over this chain, never a mutable table — the same anti-fraud reason
|
||||
the chain exists. See [[parking-session]].
|
||||
|
||||
### As-built (table split done)
|
||||
|
||||
The split above is implemented: raw Dingtian **input (button) pushes** are **device telemetry** in
|
||||
**`device_events`** (unsigned, prunable), keyed to the firing `devices` instance. Only the business
|
||||
`vehicle_entry` the press drives is signed into **`ledger_events`**. The signed events carry **no
|
||||
`lane`** — the pool-of-spaces model has none (dropped 2026-06-16; see [[entry-exit-points]]), and
|
||||
the canonical form bumped `sw-hmac-v1` → `sw-hmac-v2` accordingly.
|
||||
|
||||
### ⚠️ 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.
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
---
|
||||
type: concept
|
||||
tags: [parking, domain, business, occupancy]
|
||||
sources: []
|
||||
updated: 2026-06-15
|
||||
status: open
|
||||
---
|
||||
|
||||
# Capacity & Occupancy
|
||||
|
||||
How many vehicles are inside, how many spaces remain, and what happens when the lot is full.
|
||||
|
||||
## Occupancy is a projection (like everything else)
|
||||
|
||||
`occupancy = count(open [[parking-session|sessions]])` — an entry with no matching exit. It is a
|
||||
**fold over the signed [[append-only-event-chain]]**, never a hand-maintained counter (a counter is
|
||||
editable and drifts; the chain is the truth). Spaces-free = `capacity − occupancy`.
|
||||
|
||||
- **`capacity`** is admin-set per site (and per **zone/level** if the lot has sections — model a
|
||||
`zone` on capacity + on the entry so multi-level is a later addition, not a rewrite).
|
||||
- Permit concurrency (`maxConcurrent`, see [[permit]]) is the same kind of fold, scoped to one
|
||||
permit's open sessions.
|
||||
|
||||
## Full → refuse entry + FULL sign
|
||||
|
||||
- When `occupancy ≥ capacity`, the entry flow **refuses** (no `vehicle_entry`, no barrier open) and
|
||||
can drive a **"FULL" sign** (a relay/output, via the device adapter layer).
|
||||
- **Safety/policy nuance:** "full" blocks *entry* only — **exit always works** ([[fail-state-safety]]:
|
||||
exit fails open; never trap a vehicle). Permit holders may be allowed in past a "transient full"
|
||||
threshold (reserve spaces for subscribers) — an optional policy knob.
|
||||
- **Counting drift is real:** tailgating (two cars, one entry) and missed reads make the live count
|
||||
diverge from physical reality. The count is the *system's* occupancy; periodic ground-truth (a
|
||||
loop count, or the [[opencv-anpr-service|vision]] count) reconciles it — surfaced as an anomaly,
|
||||
not silently corrected.
|
||||
|
||||
## "Full" is a soft, operator-configurable policy
|
||||
|
||||
Refusing at capacity is the **default**, not an absolute. An operator may opt into
|
||||
**[[valet-overcapacity|valet over-capacity]]** — accept the car into operator custody (keys handed
|
||||
over, stacked beyond the marked count) instead of refusing. So the FULL gate is a policy knob
|
||||
(refuse vs. valet-accept), set by the operator per site. Valet is a manned-mode feature with its
|
||||
own custody/session shape — see [[valet-overcapacity]] (deferred).
|
||||
|
||||
## As-built (2026-06-16)
|
||||
|
||||
- **Occupancy** = `occupancyCount` (`apps/server/src/occupancy.ts`): a fold over the ledger —
|
||||
entries minus exits per identity, count those `> 0`. `getOccupancy` returns `{count, capacity,
|
||||
free, full}`.
|
||||
- **Capacity** is a single-row `site_config` table (admin-set; `null` = uncapped). Routes
|
||||
(`routes/site.ts`): `GET /api/occupancy` + `GET /api/site-config` (any role), `PUT /api/site-config`
|
||||
(admin; non-negative int or null).
|
||||
- **FULL gate** is in the **transient entry flow**: `occupancy.full` → refuse (no ticket, no
|
||||
`vehicle_entry`, no open) + signed `anomaly`. **Permit entry is NOT gated** here — subscribers are
|
||||
admitted past transient-full (their own `maxConcurrent` still applies); occupancy can read
|
||||
over-capacity (`free` negative) when permits enter a full lot, as intended.
|
||||
- **UI** `SiteSettings`: live occupancy + FULL badge (everyone); capacity editor (admin).
|
||||
- Verified: fill to cap → 3rd transient refused; permit still admitted past full; exit frees a
|
||||
slot; RBAC (operator can't set capacity); verifyChain ok. Physical FULL-sign relay output is
|
||||
**deferred** (needs a sign device).
|
||||
|
||||
## Open
|
||||
|
||||
- Zone/level granularity at launch vs. single capacity number.
|
||||
- Reserve-for-permits **threshold** (a soft transient cap below the hard capacity) — currently
|
||||
permits are simply ungated; a tunable threshold is the richer version.
|
||||
- Physical FULL-sign relay output (a sign-device role).
|
||||
- The valet over-capacity mode + custody model ([[valet-overcapacity]]).
|
||||
@@ -0,0 +1,48 @@
|
||||
---
|
||||
type: concept
|
||||
tags: [parking, security, integrity, offline-first, anti-fraud]
|
||||
sources: []
|
||||
updated: 2026-06-15
|
||||
status: open
|
||||
---
|
||||
|
||||
# Clock Integrity
|
||||
|
||||
Fees are a function of **time** ([[tariff]]: `fee = f(enteredAt, asOf)`), and the event chain is
|
||||
ordered/timestamped. So **the host clock is part of the trust model** — and on an offline appliance
|
||||
([[offline-first]], no NTP guarantee) it's a real attack surface, fitting the
|
||||
[[threat-model|operator-as-adversary]] frame:
|
||||
|
||||
- **Backdating to cut a fee** — wind the clock back so a long stay computes as short, or so an exit
|
||||
timestamps before its entry.
|
||||
- **Forward/backward jumps** that corrupt durations, the rolling-24h cap, or shift boundaries
|
||||
([[shift]]).
|
||||
- An operator with host access changing the system time deliberately.
|
||||
|
||||
## What protects it
|
||||
|
||||
- **Monotonic chain order is independent of wall-clock.** The [[append-only-event-chain]] `index`
|
||||
is strictly increasing regardless of timestamps, so **reordering** is caught even if timestamps
|
||||
are forged. But the *durations* used for pricing still rely on the wall clock — so:
|
||||
- **Detect clock anomalies and record them as events.** A timestamp that goes **backwards** between
|
||||
consecutive chain events, or jumps implausibly, is an `anomaly` (the type already exists) — signed
|
||||
and surfaced to [[reconciliation]], not silently accepted.
|
||||
- **Hardware-backed time where possible.** A battery-backed RTC on the appliance; the
|
||||
[[atecc608]]/secure element and [[disk-os-hardening]] reduce casual tampering. An operator
|
||||
changing time should require privilege the booth login doesn't have.
|
||||
- **Opportunistic trusted sync** when a [[reconciliation]] channel is briefly online (the same
|
||||
USB/hotspot path) — set/check the clock against an external authority, log any correction as an
|
||||
event.
|
||||
|
||||
## Stance
|
||||
|
||||
Like the rest of the system: **prevention (hardened host, privileged-only time change) first,
|
||||
detection (anomaly on clock regression, reconciliation) as the backstop.** The clock can't be made
|
||||
unforgeable on an offline box, but a forged clock can be made **visible**.
|
||||
|
||||
## Open
|
||||
|
||||
- RTC / time source on the chosen appliance ([[bom]]).
|
||||
- Tolerance thresholds for "implausible" jumps before flagging.
|
||||
- Whether to hard-refuse an event on a backwards clock vs. record-and-flag (record-and-flag matches
|
||||
the append-only ethos — never drop).
|
||||
@@ -33,6 +33,6 @@ principle. The choice of *which* adapter to trust is the [[trust-boundary]] deci
|
||||
|
||||
> **In practice** the adapters are made *selectable*: a [[device-registry]] catalogs the
|
||||
> supported drivers (ZKTeco / ESP32 relay, Wiegand / TCP-IP readers, Hikvision / Dahua cameras),
|
||||
> and the admin assigns one per lane during [[first-run-setup]]. Adding hardware support = one
|
||||
> and the admin assigns instances during [[first-run-setup]]. Adding hardware support = one
|
||||
> more registered driver, no business-logic change. (The implemented interfaces add a
|
||||
> `CameraDevice` for entry/exit snapshots alongside reader/relay/printer.)
|
||||
|
||||
@@ -20,13 +20,39 @@ device carries an `id`, a `label`, a `config` blob to **auto-fill** the setup fo
|
||||
(firmware, MAC, …). The [[device-registry]]'s `isDiscoverable()` guard lets the system treat it
|
||||
as optional; the setup catalog returns a `discoverable` list of driver ids.
|
||||
|
||||
## UHPPOTE discovery
|
||||
> **No current driver implements discovery.** The [[dingtian-relay]] board uses a fixed IP
|
||||
> (entered/known at setup). The capability remains for future UDP-discoverable devices (cameras
|
||||
> via ONVIF, etc.). The worked example below is the (removed) UHPPOTE driver — kept because the
|
||||
> **broadcast gotchas are transferable** to any UDP discovery we add later.
|
||||
|
||||
The [[uhppote-controller]] supports discovery natively: a **UDP broadcast** (`get-devices` on
|
||||
`255.255.255.255:60000`) that **every controller on the LAN answers** with its serial, IP,
|
||||
netmask, gateway, MAC, firmware version, and date. The official `uhppoted` lib exposes this as
|
||||
`getDevices(ctx)`; the `uhppote` driver maps each result into a `DiscoveredDevice` (serial → id,
|
||||
IP → host).
|
||||
## UHPPOTE discovery (historical example)
|
||||
|
||||
The [[uhppote-controller]] supported discovery natively: a **UDP broadcast** (`get-devices` on
|
||||
port `60000`) that **every controller on the LAN answers** with its serial, IP, netmask, gateway,
|
||||
MAC, firmware version, and date. The `uhppoted` lib exposed this as `getDevices(ctx)`; the
|
||||
(now-removed) `uhppote` driver mapped each result into a `DiscoveredDevice` (serial → id, IP →
|
||||
host). **Was verified on real hardware** (serial 225088491).
|
||||
|
||||
### Broadcast gotchas (learned the hard way — see [[wsl-dev-networking]])
|
||||
|
||||
These cost real debugging time; the (removed) `uhppote` driver handled all three, and any future
|
||||
UDP-discovery driver will need to as well:
|
||||
|
||||
1. **Broadcast to the *subnet-directed* address, not the global `255.255.255.255`.** The
|
||||
`uhppoted` lib only calls `setBroadcast(true)` when the target matches a **local interface's
|
||||
subnet broadcast** (e.g. `10.0.10.255`). For the global address it skips it, so the `send`
|
||||
fails with **`EACCES`**. The driver computes the subnet broadcast from `os.networkInterfaces()`.
|
||||
2. **A host with multiple interfaces must broadcast on *all* subnets.** With several NICs (LAN,
|
||||
VPN/Tailscale, docker bridges) the controller is on only one. Picking the first interface
|
||||
misses it; the driver broadcasts on every subnet and dedupes by serial.
|
||||
3. **For *unicast* ops (status / open), the lib's `Config` broadcast must match the target's
|
||||
subnet** — it governs reply routing, so a mismatched broadcast makes `getStatus` time out even
|
||||
though `openDoor` "succeeds". The driver sets the broadcast per the target host's subnet. (This
|
||||
was the health-check "offline/timeout" bug: a 5 s timeout dropped to 24 ms once fixed.)
|
||||
|
||||
Also: concurrent `uhppoted` calls collide on the `:60001` reply-listener port (EACCES / dropped
|
||||
replies), so the driver **serializes** all controller I/O. Override the broadcast with
|
||||
`UHPPOTE_BROADCAST` for unusual setups.
|
||||
|
||||
## Flow
|
||||
|
||||
@@ -34,13 +60,13 @@ IP → host).
|
||||
2. Admin clicks **Scan** → `GET /api/setup/discover/:driverId` (admin-only).
|
||||
3. The server runs `discover()` and **health-checks each found device** so the admin sees
|
||||
reachability before assigning.
|
||||
4. Selecting a result **auto-fills serial + host**; the admin then assigns it to a lane.
|
||||
4. Selecting a result **auto-fills serial + host**; the admin then assigns + binds it.
|
||||
|
||||
## Deployment notes
|
||||
|
||||
- UHPPOTE discovery is a **broadcast** — the host socket needs broadcast permission (a raw
|
||||
`send EACCES …:60000` means the OS blocked it). Works on the isolated device VLAN
|
||||
([[network-isolation]]) where the controller and host share an L2 segment.
|
||||
- Discovery is an **L2 broadcast**: the host and controller must share a layer-2 segment. Works
|
||||
on the isolated device VLAN ([[network-isolation]]). A routed/NAT'd network (e.g. WSL2 NAT mode
|
||||
— see [[wsl-dev-networking]]) blocks it entirely.
|
||||
- Discovery shares the same unauthenticated UDP exposure as everything else UHPPOTE — another
|
||||
reason the controllers live on an isolated VLAN ([[uhppote-udp-protocol]]).
|
||||
- Cameras (Hikvision/Dahua via ONVIF/WS-Discovery) could implement the same interface later.
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
---
|
||||
type: concept
|
||||
tags: [parking, devices, monitoring, telemetry]
|
||||
sources: []
|
||||
updated: 2026-06-15
|
||||
status: open
|
||||
---
|
||||
|
||||
# Device Events (telemetry)
|
||||
|
||||
The **unsigned** operational record of what the hardware did and reported — distinct from the
|
||||
signed business [[append-only-event-chain|ledger]] (see [[event-streams-split]]). For monitoring,
|
||||
diagnostics, and live booth status — **not** anti-fraud.
|
||||
|
||||
## What lands here
|
||||
|
||||
- **Relays/barriers:** relay fired/released, pulseOpen issued (the *device-side* echo; the
|
||||
authoritative `barrier_open_command` is a signed ledger event).
|
||||
- **Printers:** paper-out / near-end / cover-open / cutter / offline (already polled —
|
||||
[[printer-status-monitoring]]).
|
||||
- **Cameras:** reachable/offline, snapshot success/failure ([[lpr-camera]]).
|
||||
- **Readers / inputs:** a raw read, raw input edges (Dingtian button `input N on/off` —
|
||||
[[device-input-flow]]).
|
||||
|
||||
## Properties
|
||||
|
||||
- **Unsigned, not chained** — no `prevHash`/`signature`. It's telemetry, so it carries none of the
|
||||
ledger's integrity machinery.
|
||||
- **Disposable** — high-volume and churny; **may rotate/prune** on a retention policy (the ledger
|
||||
never does).
|
||||
- **Device-keyed** — references the `devices` instance (raw device provenance). No `lane`
|
||||
(pool-of-spaces model — see [[entry-exit-points]]).
|
||||
|
||||
## The boundary that matters
|
||||
|
||||
A device event is *evidence the host saw something happen*; it does **not** by itself authorize or
|
||||
record a business fact. A button press here becomes a **signed `vehicle_entry`** in the ledger only
|
||||
after the entry flow runs (ticket + barrier command). This keeps device chatter on the device side
|
||||
of the [[device-adapter-pattern|adapter boundary]] and the signed ledger focused on money/access.
|
||||
|
||||
## Open
|
||||
|
||||
- Retention/rotation policy (size- or age-based).
|
||||
- Whether any witness-grade device fact (e.g. a loop-sensor `barrier_open_observed`) should *also*
|
||||
write a signed ledger entry for [[reconciliation]] — see [[append-only-event-chain]].
|
||||
@@ -0,0 +1,106 @@
|
||||
---
|
||||
type: concept
|
||||
tags: [parking, architecture, devices, entry-flow]
|
||||
sources: []
|
||||
updated: 2026-06-15
|
||||
---
|
||||
|
||||
# Device Input Flow (button → backend → relay)
|
||||
|
||||
How a physical button press drives the entry lane. The **backend is the source of truth**: the
|
||||
device only *reports* the press; the host decides and commands the relay. This is the host-in-the-
|
||||
loop flow the [[dingtian-relay]] makes possible (and the [[uhppote-controller]] could not).
|
||||
|
||||
## The path (no polling)
|
||||
|
||||
```
|
||||
car arrives → driver presses button (input I_N, dry contact to GND)
|
||||
→ device HTTP-pushes GET …/api/devices/dingtian/<deviceId>/input/<N>/on
|
||||
→ backend: emit internal device event (device-events bus)
|
||||
→ backend entry flow: create + sign an entry event, print the ticket
|
||||
→ backend: pulseOpen(N) over UDP → barrier opens
|
||||
→ (on release) device pushes …/input/<N>/off
|
||||
```
|
||||
|
||||
- **Push, not poll.** The device's `input_link_url` feature is configured (by the driver's
|
||||
`configureInputPush()`) to call the backend on each input edge — see [[dingtian-relay]]. The
|
||||
driver's poll path remains only as a dev/fallback aid.
|
||||
- **Per-input path** carries the input number in the URL (`…/input/3/on`), so routing needs no
|
||||
body parsing. Both edges (`on`/`off`) are sent.
|
||||
- **Internal event bus** (`device-events.ts`, a Node `EventEmitter`) decouples the HTTP/transport
|
||||
layer from business logic — drivers/pushes emit; the entry flow subscribes. Keeps the app
|
||||
[[device-adapter-pattern|device-agnostic]].
|
||||
|
||||
## Trust model (important — flat network, no VLAN)
|
||||
|
||||
The site is a **flat network with no VLAN** ([[network-isolation]] is not yet enforceable here),
|
||||
so we do **not** trust the device or the network. Both directions now have defence-in-depth, but
|
||||
neither is the real boundary:
|
||||
|
||||
- **Relay control (host → device)** — UDP, now via the Dingtian **binary protocol on :60000 with a
|
||||
`relay_pw`** (the only authenticated relay option; the string protocol has none). Set on the
|
||||
device + stored in `devices` by the harden step (below).
|
||||
- **Input push (device → host)** — guarded by **HTTP Digest auth** + a **source-IP allowlist**.
|
||||
- **The real guarantee is the signed log:** every barrier open is a host decision, recorded as a
|
||||
signed event BEFORE the relay fires ([[append-only-event-chain]]). An out-of-band open (which a
|
||||
flat network allows) has **no matching signed event → a detectable anomaly**. Device/network
|
||||
auth is just speed bumps; both are plaintext over a sniffable network.
|
||||
- This sharpens under the [[autonomous-direction|unmanned]] roadmap: with no operator, tamper
|
||||
detection via the signed log matters more than perimeter auth.
|
||||
|
||||
## Device hardening (on assign)
|
||||
|
||||
The assign/Save step configures the device end-to-end (admin never touches the device web UI):
|
||||
fix preconditions (disable `input_link_relay`) → **harden** → set up input push. The `harden`
|
||||
capability ([[device-registry|HardenableDevice]]):
|
||||
|
||||
- **Sets a random `relay_pw`** (1–9999) so binary relay commands need it; stores it in
|
||||
`devices` so the backend can keep commanding the relay.
|
||||
- **Disables unused protocol channels** (rs485, can, tcp×2, mqtt → `p:255`), keeping only UDP1
|
||||
binary (relay control) + UDP2 string (status read) — fewer open doors.
|
||||
|
||||
> **⚠️ Lesson (the hard way):** do **NOT** enable the device's HTTP CGI session check
|
||||
> (`session_en`). On this firmware (DT-R004) it makes the config-**read** API drop connections
|
||||
> (`ECONNRESET`), locking the backend out of the very API it depends on — it required a **factory
|
||||
> reset** to recover. The harden step deliberately leaves `session_en` off. The CGI config API
|
||||
> being open is accepted as part of the flat-network reality (the signed log is the guarantee);
|
||||
> the proper fix is network isolation, not this fragile device feature.
|
||||
|
||||
## Push authentication — Digest (decided by hardware testing)
|
||||
|
||||
The secret must not be in the URL (sniffable, logged) and the password must not cross the wire in
|
||||
the clear. We **empirically tested the device** to pick the strongest achievable option:
|
||||
|
||||
| Option | Device result |
|
||||
| --- | --- |
|
||||
| HTTPS (self-signed) | ❌ device won't push to a self-signed cert |
|
||||
| **Digest auth** (`auth=2`) | ✅ **works** — full 401-nonce challenge/response |
|
||||
| Basic auth | ✅ works (but password base64 on the wire) |
|
||||
| URL token | rejected by design (visible in URL/logs) |
|
||||
|
||||
→ **HTTP Digest** (MD5, qop=auth). The password is never sent (only a nonce-keyed hash); nonces
|
||||
are **single-use** (replay resistance). Per-device credentials (`pushUser`/`pushPassword`) are
|
||||
generated by the backend on **device assign**, written to the device's `input_link_url` config,
|
||||
and stored in `devices` — the admin never types a URL or secret. HTTPS would be stronger but
|
||||
the device can't do it here; Digest + the signed log is the practical answer on a flat network.
|
||||
See `apps/server/src/digest-auth.ts`.
|
||||
|
||||
## Dingtian config-write gotchas (cost a lot of debugging)
|
||||
|
||||
Writing the device's config API (`/api/v2/config_set.cgi`) has two non-obvious traps — both now
|
||||
handled in the driver:
|
||||
|
||||
1. **Content-Length is mandatory.** The device's embedded HTTP server does **not** accept chunked
|
||||
request bodies. Node uses chunked encoding when `Content-Length` is absent, so the device
|
||||
silently ignores the body and returns `{"status":0}` anyway — the write looks successful but
|
||||
nothing changes. Always set `Content-Length`.
|
||||
2. **The `pass` field caps at 31 chars** (longer is silently truncated → Digest mismatch). The
|
||||
generated push password is 24 hex chars (96 bits).
|
||||
3. (Also: the device reboots on apply, so the driver writes then **polls until the change is
|
||||
verified**, retrying — back-to-back writes onto a rebooting device are lost.)
|
||||
|
||||
## Status
|
||||
|
||||
Input push **verified on hardware** with Digest auth (all 4 inputs, real presses authenticated, no
|
||||
failures). The entry
|
||||
flow itself (signed event + ticket print + `pulseOpen`) is the next build — see [[dingtian-relay]].
|
||||
@@ -10,7 +10,7 @@ updated: 2026-06-15
|
||||
How the system goes from "device-agnostic in principle" ([[device-adapter-pattern]]) to
|
||||
"**admin picks the device at setup**" in practice. A **registry** holds a catalog of supported
|
||||
**drivers**, grouped by category; the [[first-run-setup]] UI reads it so an
|
||||
operator can choose a device per lane and fill in its connection config.
|
||||
operator can choose a device and fill in its connection config.
|
||||
|
||||
> Implementation-derived (from `packages/devices`), not the source doc.
|
||||
|
||||
@@ -33,12 +33,14 @@ driver; **no business-logic change** — this is the [[device-adapter-pattern]]
|
||||
|
||||
## Why a registry (not hard-coded wiring)
|
||||
|
||||
- The admin chooses between **multiple devices per category** at install time, per lane
|
||||
(mirrors the "mixable per lane" principle — see [[trust-boundary]], [[entry-exit-readers]]).
|
||||
- The admin chooses between **multiple devices per category** at install time
|
||||
(a controller's relays mix entry/exit; readers bind to them — see [[entry-exit-points]],
|
||||
[[trust-boundary]], [[entry-exit-readers]]).
|
||||
- Config is **validated against the driver's declared fields** before persisting.
|
||||
- Selections persist in the `lane_devices` table and drive runtime adapter construction.
|
||||
- Selections persist in the `devices` table and drive runtime adapter construction.
|
||||
- Drivers may optionally implement **[[device-discovery]]** (`discover()`), so the admin can scan
|
||||
the LAN instead of typing connection details — UHPPOTE does this today.
|
||||
the LAN instead of typing connection details — no current driver uses it (the UHPPOTE did,
|
||||
before removal; the [[dingtian-relay]] uses a fixed IP).
|
||||
|
||||
Cameras are modelled as **snapshot-on-event**: the host requests an image at entry/exit; it's
|
||||
stored and referenced from the signed event as an **independent record** — a fraud-control input
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
---
|
||||
type: concept
|
||||
tags: [parking, architecture, devices, setup]
|
||||
sources: []
|
||||
updated: 2026-06-16
|
||||
---
|
||||
|
||||
# Entry / Exit Points (pool-of-spaces model)
|
||||
|
||||
A parking lot is **one pool of spaces** with a flexible set of **entry points** and **exit
|
||||
points** — any number of each, in any combination (1 in + 1 out, 1 in + 2 out, 2 in + 1 out, …).
|
||||
There is **no "lane"** concept anywhere in the system (dropped 2026-06-16 — see below).
|
||||
|
||||
## Direction lives on the relay, not the controller
|
||||
|
||||
An access controller (e.g. a [[dingtian-relay]] board) has **several relays** — each relay opens
|
||||
one barrier. Direction is a property of **each relay**, declared in the controller's config:
|
||||
|
||||
```jsonc
|
||||
// access `devices` row — one Dingtian board
|
||||
config: {
|
||||
host: "192.168.1.100",
|
||||
relays: [
|
||||
{ relay: 1, direction: "entry", button: 1 }, // entry barrier; entry button on input 1
|
||||
{ relay: 2, direction: "exit" } // exit barrier; opened by a reader, no button
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
- `direction`: `entry` | `exit` | `both` (`both` = one barrier/relay serving in and out).
|
||||
- `button`: the **input terminal** the transient **entry button** is wired to. Only entry/both
|
||||
relays have one. Absent = no button at that barrier (subscriber/reader-driven only).
|
||||
|
||||
The four real layouts all fall out of this:
|
||||
|
||||
| Layout | Controllers | Relays |
|
||||
| --- | --- | --- |
|
||||
| 1 barrier, both directions | 1 | `{relay:1, both, button:1}` |
|
||||
| 2 barriers, 1 board | 1 | `{relay:1, entry, button:1}`, `{relay:2, exit}` |
|
||||
| 2 barriers far apart | 2 | board A `{relay:1, entry}`, board B `{relay:1, exit}` |
|
||||
| 1 entry + 2 exit | 3 | A entry; B, C each exit |
|
||||
|
||||
## Readers / cameras BIND to a relay
|
||||
|
||||
A reader or camera points at the barrier it physically sits at, via its config:
|
||||
|
||||
```jsonc
|
||||
config: { ...readerConfig, controllerId: "<access devices.id>", relay: 2 }
|
||||
```
|
||||
|
||||
Its **direction is inherited** from that relay. So an exit read opens **exactly that relay** —
|
||||
no ambiguity even with multiple exit barriers ("the relay at that reader", decided 2026-06-16).
|
||||
Binding is optional: an unbound device falls back to a `config.direction` + the first relay
|
||||
site-wide of that direction (keeps the single-barrier case trivial). LPR is a snapshot sink —
|
||||
an ANPR service ([[opencv-anpr-service]]) POSTs the plate as a `plate` read to the reader
|
||||
endpoint, flowing through the same dispatcher.
|
||||
|
||||
## Resolution (one module: `apps/server/src/device-resolve.ts`)
|
||||
|
||||
- **Button press** → `relayForButton(controllerId, terminal)` → the entry relay whose `button`
|
||||
matches → entry flow → `pulseOpen(relay)`.
|
||||
- **Reader/permit/LPR read** → `relayForDevice(reader)` → the bound relay → `pulseOpen(relay)`;
|
||||
direction inherited.
|
||||
- **Snapshots** → `devicesByDirection("camera", dir)` → every camera serving that direction.
|
||||
|
||||
A directional barrier that contradicts the car's open-session state (an exit barrier scanned by a
|
||||
car not inside, or an entry barrier by a car already in) is a wrong-barrier / [[anti-passback]]
|
||||
refusal. A `both` relay defers to session state.
|
||||
|
||||
## The flows
|
||||
|
||||
| Flow | Trigger | Opens |
|
||||
| --- | --- | --- |
|
||||
| Transient entry | entry **button** press | the entry relay (button-mapped) → ticket prints |
|
||||
| Transient exit | voucher scan at exit reader | the exit relay (reader-bound), if paid+grace |
|
||||
| Subscriber entry | QR/RFID/plate at entry reader | the entry relay (reader-bound), if permit valid |
|
||||
| Subscriber exit | QR/RFID/plate at exit reader | the exit relay (reader-bound), if permit valid |
|
||||
|
||||
Every open also fires a [[camera snapshot|append-only-event-chain]] (async, never blocks the open).
|
||||
|
||||
## Why no lane
|
||||
|
||||
"Lane" was a leftover from a rows-of-gates mental model. It added nothing here:
|
||||
|
||||
- **Occupancy** is a site-wide fold over the ledger (entries − exits); it never grouped by lane.
|
||||
- **Device grouping** is now done by the reader→relay binding, far more precisely than a lane key.
|
||||
- **Anti-fraud** doesn't use it — the signed chain, the "open must match a signed event" check,
|
||||
and [[reconciliation]] all work on *what happened*, not *which gate*. The relay's direction
|
||||
already catches an exit firing an entry barrier, better than a lane number would.
|
||||
|
||||
Dropping it removed `lane` from `ledger_events`, `device_events`, `sessions`, and the device
|
||||
table (renamed `lane_devices` → `devices`). Because `lane` was part of the **signed canonical
|
||||
form**, this is a versioned change: the canonical array no longer includes lane, and the signer
|
||||
keyId bumped `sw-hmac-v1` → `sw-hmac-v2`. v1 events won't verify under v2 — intentional, gated by
|
||||
each event's stored `keyId` (done pre-deployment, on throwaway data, so zero real cost). See
|
||||
[[append-only-event-chain]].
|
||||
|
||||
## Camera snapshots (evidence, not a gate)
|
||||
|
||||
Captured **after** the barrier opens, **never awaited** — a camera failure can't delay or block an
|
||||
open (the signed ledger is the decision). Stored as a **BLOB in the `snapshots` table** (single
|
||||
backed-up DB, nothing scattered on disk), in its own table so hot telemetry scans don't drag image
|
||||
bytes and images prune independently. Linked to the signed `vehicle_entry/exit` by `identity`.
|
||||
Served read-only via `GET /api/snapshots/:id`. **Retention is unresolved** — see [[open-questions]].
|
||||
|
||||
## Related
|
||||
|
||||
[[entry-exit-readers]] · [[device-events]] · [[parking-session]] · [[anti-passback]] ·
|
||||
[[append-only-event-chain]] · [[barrier-not-a-door]] · [[opencv-anpr-service]] ·
|
||||
[[dingtian-relay]] · [[first-run-setup]]
|
||||
@@ -22,6 +22,12 @@ There are **two populations** of users, and they map to **two integration paths*
|
||||
| [[wiegand]] reader → UHPPOTE port | The controller | Controller (onboard card list) | **Yes** — works if host down |
|
||||
| Pure TCP/IP reader | Host only | Host, then UDP `open` to relay | No — host on critical path |
|
||||
| [[lpr-camera|LPR]] / QR scanner | Host only | Host | No |
|
||||
| **[[gee-qr-er80]] QR reader (serial)** | Host only | Host (reads serial → `read` bus) | No |
|
||||
|
||||
> Concrete host-side reader on hand: the **[[gee-qr-er80]]** (QR over RS-232/RS-485). Note autonomy
|
||||
> is moot here anyway — the current relay ([[dingtian-relay]]) has **no onboard card list**, so even
|
||||
> a Wiegand reader would be host-decided. So we take the serial/QR path straight to the host's
|
||||
> `read` bus.
|
||||
|
||||
## Key points
|
||||
|
||||
@@ -32,6 +38,10 @@ There are **two populations** of users, and they map to **two integration paths*
|
||||
keeps autonomy + native event log.
|
||||
- **Both models can share one relay** (valid Wiegand read **or** host `open` in "controlled"
|
||||
mode), so one lane serves permit + casual.
|
||||
- **Each reader BINDS to a controller relay** (`config.controllerId` + `relay`) — the barrier it
|
||||
sits at — and inherits that relay's direction (entry/exit/both). An exit read opens exactly that
|
||||
relay; an entry read the entry relay. This is how separate in/out readers are disambiguated, with
|
||||
no "lane". See [[entry-exit-points]].
|
||||
- **Host-in-the-loop is good for fraud detection** — two independent records (host's signed
|
||||
[[append-only-event-chain]] entry + the UHPPOTE remote-open event) should reconcile 1:1; any
|
||||
mismatch is an anomaly.
|
||||
|
||||
@@ -8,8 +8,10 @@ updated: 2026-06-15
|
||||
# First-Run Setup (device selection)
|
||||
|
||||
The admin install flow that makes the system **device-agnostic in practice**: on first run, an
|
||||
admin assigns devices **per lane** by choosing from the [[device-registry]] catalog and entering
|
||||
each device's connection config.
|
||||
admin adds **controllers** (each declaring its relays — entry/exit/both — and the entry-button
|
||||
terminal) and then **readers/cameras/printers** bound to a controller relay, choosing from the
|
||||
[[device-registry]] catalog and entering each device's connection config. There is **no lane** —
|
||||
the pool-of-spaces model; see [[entry-exit-points]].
|
||||
|
||||
> Implementation-derived (from `apps/server` + `apps/web`), not the source doc.
|
||||
|
||||
@@ -18,21 +20,42 @@ each device's connection config.
|
||||
1. **Read the catalog** — `GET /api/setup/catalog` returns supported drivers per category (no
|
||||
secrets, just schema) plus a `discoverable` list. The web `SetupWizard` renders a picker + the
|
||||
driver's config fields, and a **Scan** button for discoverable drivers ([[device-discovery]]).
|
||||
2. **Assign per lane** — `POST /api/setup/assign` (admin-only, role-guarded; see
|
||||
[[local-jwt-auth]]). The server validates the chosen driver + config against the registry
|
||||
before persisting to the `lane_devices` table; unknown drivers / missing required fields are
|
||||
rejected.
|
||||
3. **Complete** — `POST /api/setup/complete` marks the single-row `setup_state`.
|
||||
2. **Test** (optional, no save) — `POST /api/setup/test` (admin-only). Validates the config,
|
||||
probes reachability (`healthCheck`), and reports preconditions (e.g. `input_link_relay`) —
|
||||
**without** saving or changing the device. The wizard's **Test connection** button shows a
|
||||
health badge + any precondition warnings.
|
||||
3. **Save & configure** — `POST /api/setup/assign` (admin-only). Validates, then **configures the
|
||||
device**: fixes preconditions (e.g. disables `input_link_relay`) and sets up the Digest-
|
||||
authenticated input push ([[device-input-flow]]) — the admin never touches the device's own web
|
||||
UI. **Fails the save** (no DB row) if the device can't be configured, so there are no
|
||||
orphan/half-configured rows. On success persists to `devices`.
|
||||
4. **Remove** — `DELETE /api/setup/assign/:id` (admin-only) drops one instance's row. Only our
|
||||
row is removed; the device itself is not un-hardened/un-configured (a stale push from an
|
||||
unknown device id is already rejected, and re-assigning reconfigures it).
|
||||
5. **Complete** — `POST /api/setup/complete` marks the single-row `setup_state`.
|
||||
|
||||
## Config granularity
|
||||
## Config granularity — multi-instance per category
|
||||
|
||||
Organized **per lane** — each lane gets an access controller, reader(s), and camera(s), each with
|
||||
its own connection settings. Matches the architecture's "mixable per lane" reality (a lane can
|
||||
serve permit holders via [[wiegand]] and casual via host-side reads on one relay — see
|
||||
[[entry-exit-readers]]).
|
||||
The data model is **multi-instance**: `devices` holds **one row per instance**, keyed by a
|
||||
generated `id`. So the site can have **more than one of every category** — multiple controllers,
|
||||
readers, cameras, and printers (e.g. an entry dispenser + a booth printer; see
|
||||
[[printer-roles-failover]]). `assign` always inserts a new row (never an upsert), and `state`
|
||||
returns the full list.
|
||||
|
||||
The `SetupWizard` reflects this: each category shows the **list of assigned instances** (with
|
||||
**Remove**) plus an **Add another** form — not a single fixed slot. `select`-type config fields
|
||||
(e.g. a printer's role) render as dropdowns.
|
||||
|
||||
There is **no lane**. Direction lives on each access **relay**; readers/cameras **bind** to a
|
||||
controller relay (`config.controllerId` + `relay`) — the barrier they serve — and inherit its
|
||||
direction. The wizard adds controllers first, then binds the other devices to a relay. See
|
||||
[[entry-exit-points]], [[entry-exit-readers]].
|
||||
|
||||
## Security notes
|
||||
|
||||
- The assign/state/complete endpoints require the **admin** role ([[local-jwt-auth]]).
|
||||
- Device **credentials are stored in `lane_devices.config`** — protect at rest
|
||||
- The assign/state/delete/complete endpoints require the **admin** role ([[local-jwt-auth]]).
|
||||
- Device **credentials are stored in `devices.config`** — protect at rest
|
||||
([[disk-os-hardening]]); device hosts belong on the isolated VLAN ([[network-isolation]]).
|
||||
- **Secrets are stripped on the way out**: `assign` and `state` both redact `pushPassword`,
|
||||
`webPassword`, and `relayPassword` from the returned config (the UI lists devices; it never
|
||||
needs the stored secrets).
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
---
|
||||
type: reference
|
||||
tags: [parking, dev-environment, workflow]
|
||||
sources: []
|
||||
updated: 2026-06-15
|
||||
---
|
||||
|
||||
# Local Dev Workflow
|
||||
|
||||
> Dev-environment reference, not product architecture. How to run the stack locally and the
|
||||
> gotchas that have bitten us. For device testing under WSL also read [[wsl-dev-networking]].
|
||||
|
||||
## First-time setup
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
cp apps/server/.env.example apps/server/.env # then fill in JWT_SECRET
|
||||
# JWT_SECRET=$(openssl rand -hex 32) # server refuses to start without a strong one
|
||||
pnpm --filter @parking/db exec drizzle-kit migrate # create the SQLite schema
|
||||
pnpm seed:admin # create the first admin (see [[local-jwt-auth]])
|
||||
```
|
||||
|
||||
`apps/server/.env` and the `*.sqlite` files are **gitignored** (local-only). Leave `NODE_ENV`
|
||||
**unset** in dev so the auth cookies aren't `Secure`-only (Vite dev is plain http).
|
||||
|
||||
## Running
|
||||
|
||||
```bash
|
||||
pnpm dev # turbo runs both: Vite (web, :5173) + Fastify (server, :3000)
|
||||
```
|
||||
|
||||
Open `http://localhost:5173`. The Vite dev proxy forwards `/api` + `/health` to the backend, so
|
||||
the SPA and API are **same-origin** and the [[local-jwt-auth|cookie auth]] works without CORS.
|
||||
Production uses an **nginx** reverse proxy (`deploy/nginx.conf`) for the same same-origin setup.
|
||||
|
||||
## Gotchas (all fixed, recorded so they don't recur)
|
||||
|
||||
- **Server dev must not be `node --experimental-strip-types src/index.ts`.** Type-stripping does
|
||||
**not** rewrite `.js` import specifiers to `.ts`, so it crashed with `ERR_MODULE_NOT_FOUND` and
|
||||
silently never started — the symptom was the SPA hanging for *minutes* (the Vite proxy waiting
|
||||
on a dead backend), then finally erroring. The `dev` script uses **`tsx watch`** instead.
|
||||
- **Vite proxy → `127.0.0.1`, not `localhost`.** `localhost` resolves to IPv6 `::1` first while
|
||||
the backend binds IPv4; Node's proxy can stall on the v6 attempt. Same class of "slow then
|
||||
works" hang, worse under WSL2 mirrored mode ([[wsl-dev-networking]]).
|
||||
- **`.env` must actually be loaded.** The server reads `process.env` only; the dev/start scripts
|
||||
load the file via Node's `--env-file-if-exists=.env`. An empty `JWT_SECRET=` makes the server
|
||||
fail-fast at boot.
|
||||
- **Seed into the DB the server reads.** `seed:admin` and the server must use the same
|
||||
`DATABASE_URL`; running via `pnpm seed:admin` (which loads `apps/server/.env`) keeps them aligned.
|
||||
|
||||
## Useful one-offs
|
||||
|
||||
- First admin: `pnpm seed:admin` (prompts; blank username → `admin`). Non-interactive:
|
||||
`ADMIN_USER=.. ADMIN_PASS=.. pnpm seed:admin`. Reset a password: add `FORCE=1`.
|
||||
- Hardware test scripts (UHPPOTE): `apps/server/scripts/uhppote-listen.mjs` (live events),
|
||||
`uhppote-relay.mjs` (guarded door-open). See [[uhppote-controller]].
|
||||
@@ -0,0 +1,129 @@
|
||||
---
|
||||
type: concept
|
||||
tags: [parking, domain, business, anti-fraud]
|
||||
sources: []
|
||||
updated: 2026-06-15
|
||||
status: open
|
||||
---
|
||||
|
||||
# Parking Session
|
||||
|
||||
The core business-domain entity: one vehicle's stay, from entry to exit, plus the money owed and
|
||||
paid for it. Everything on the business side — [[tariff|tariffs]], payment, [[reconciliation]],
|
||||
revenue reporting — hangs off the session. This page defines what a session **is** and, just as
|
||||
importantly, what it is **not**.
|
||||
|
||||
> Scope decision (2026-06-15): build the **transient** (casual, pay-for-duration) session first;
|
||||
> layer **permit holders** on top as a second identity source that short-circuits payment. Mixed
|
||||
> site, transient-first — see [[entry-exit-readers]] ("two populations, one shared relay") and
|
||||
> [[session-model]].
|
||||
|
||||
## A session is a PROJECTION over the signed event log — not a mutable table
|
||||
|
||||
This is the single most important rule, and it falls straight out of the [[threat-model]] (the
|
||||
adversary is the insider who can edit the database) and the [[append-only-event-chain]]:
|
||||
|
||||
- The **events** table is the ledger and the **only** source of truth. `vehicle_entry`,
|
||||
`vehicle_exit`, `payment`, `void` are all **appended + signed**, never updated or deleted.
|
||||
- A **session** is a **read-model folded from those events** — open when an entry has no matching
|
||||
exit, paid when a `payment` event references it, closed when an exit lands. It MAY be cached in
|
||||
a table for query speed (dashboards, "cars currently in"), but that cache is **always rebuildable
|
||||
from the chain and never authoritative** ([[append-only-event-chain]]), scaled to the business
|
||||
domain.
|
||||
- **Why this matters:** a mutable `sessions` row that stored "amount owed / paid" would reopen
|
||||
exactly the fraud hole the whole system exists to close (operator marks a session paid, pockets
|
||||
the cash). With sessions as a projection, "paid" is a **signed `payment` event** an operator
|
||||
can't forge or silently delete — a deletion breaks the chain visibly. See [[session-model]] for
|
||||
the rejected mutable-table alternative.
|
||||
|
||||
## Identity — how an entry is tied to its exit
|
||||
|
||||
A session needs a key that survives from entry to exit. Two populations, two keys
|
||||
([[entry-exit-readers]]):
|
||||
|
||||
- **Transient:** a **ticket id** (printed, ideally on pre-numbered stock — see [[reconciliation]])
|
||||
or a **plate** read by [[lpr-camera|LPR]]. This id is carried in the event's `identity` field.
|
||||
- **Permit holder:** a **credential** (card / plate / QR) matched to a [[permit]] record. A valid
|
||||
permit means the session owes nothing — the PAY step is skipped (see below).
|
||||
|
||||
## Lifecycle (pay-on-foot / pay station model)
|
||||
|
||||
Payment is **decoupled from exit** (decision 2026-06-15, matching the [[autonomous-direction|
|
||||
unmanned]] roadmap): the customer pays at a central station before walking back to the car; the
|
||||
exit lane only *validates* that the session is settled.
|
||||
|
||||
```
|
||||
ENTRY (lane) vehicle_entry event → session OPEN
|
||||
(ticket printed / plate read; barrier opens)
|
||||
PAY (pay station) payment event {sessionRef, fee, paidAt}
|
||||
→ session PAID (grace window starts)
|
||||
EXIT (lane) validate: PAID && now ≤ paidAt + graceMinutes ?
|
||||
yes → vehicle_exit event → session CLOSED → pulseOpen
|
||||
no → reject → re-pay overstay top-up at station, then exit
|
||||
```
|
||||
|
||||
States, as derived from events:
|
||||
|
||||
| State | Condition (over the event chain) |
|
||||
| --- | --- |
|
||||
| **OPEN** | a `vehicle_entry` with no later matching `vehicle_exit` |
|
||||
| **PAID** | OPEN + a `payment` event covering the fee due, within its grace window |
|
||||
| **CLOSED** | a matching `vehicle_exit` event exists |
|
||||
| **VOIDED** | a `void` event references the session (lost ticket written off, error correction) |
|
||||
|
||||
Permit sessions skip PAID: a valid [[permit]] at exit is itself the authorization to close.
|
||||
|
||||
## Edge cases the model must name (not yet designed in full)
|
||||
|
||||
- **Overstay after payment** — exited the grace window; needs a top-up payment. The one genuinely
|
||||
stateful rule; handled as a second `payment` event, fee = f(time since paid).
|
||||
- **Lost ticket** — no entry id to match. A default flat "lost ticket" fee (see [[tariff]]), **or
|
||||
an amount the admin sets at the moment** (operator judgement — e.g. they can establish entry time
|
||||
from [[opencv-anpr-service|plate]] capture or CCTV and charge accordingly, or apply a fixed
|
||||
penalty). Recorded as a `payment` (with the chosen amount + a reason) + a `void`/annotation so it
|
||||
reconciles; the admin-set amount is captured in the signed event, attributed.
|
||||
- **Manual override** — an operator/admin opens the barrier for a stuck or disputed car, or writes
|
||||
off a session, as a deliberate act. Each is a **signed, reason-coded event**
|
||||
(`barrier_open_command` / a void with reason) — so an override is *authorized and logged*, while
|
||||
an open with **no** such signed event remains the fraud signal ([[append-only-event-chain]]). The
|
||||
override is the legitimate counterpart to the out-of-band-open anomaly.
|
||||
- **Forced / fail-open exit** — barrier failed open ([[fail-state-safety]]): the vehicle leaves with
|
||||
**no `vehicle_exit`**. This is an open session that never closes — a **reconciliation anomaly by
|
||||
design** ([[append-only-event-chain]]'s "physical open with no signed command"), not something to
|
||||
paper over. (A *manual* override above is the signed, non-anomalous version.)
|
||||
- **Re-entry / never-exited** — stale open sessions (drove out tailgating, sensor missed). Surface
|
||||
as anomalies; never auto-close silently.
|
||||
|
||||
## What this unblocks (build order)
|
||||
|
||||
The device layer left the entry flow dangling — the session domain is that next step. Schema + code
|
||||
follow this page and [[tariff]]; the decision is recorded in [[session-model]].
|
||||
|
||||
### As-built (2026-06-15)
|
||||
|
||||
- **Entry flow** (`apps/server/src/entry-flow.ts`): access-device input edge → print ticket
|
||||
(failover) → signed `vehicle_entry` → `pulseOpen`. Holds (anomaly, no open, no entry) if printing
|
||||
fails. See [[device-input-flow]].
|
||||
- **Read dispatch** (`apps/server/src/read-dispatch.ts`): a credential read routes to the
|
||||
**permit flow** if it matches a permit (card/QR/bound plate), else to the transient **exit flow**.
|
||||
Lane resolved once (`readerLaneWithAccess`). See [[permit]] as-built.
|
||||
- **Exit flow** (`apps/server/src/exit-flow.ts`): a credential **read** (the `read` bus channel) →
|
||||
fold the signed ledger for that identity → validate **open + PAID + within `gracePeriodExitMin`**
|
||||
→ signed `vehicle_exit` → `pulseOpen`. Unpaid / expired / unknown → signed `anomaly`, barrier
|
||||
stays closed. Validation folds the **ledger** (authoritative), then updates the `sessions` cache.
|
||||
- **Not a fail-state:** an unpaid reject keeps the barrier closed deliberately (driver returns to
|
||||
the pay station); "exit fails open" ([[fail-state-safety]]) is about the *system* being unable
|
||||
to decide (host/power loss), not an unpaid car.
|
||||
- **Pay station** (`apps/server/src/pay-station.ts`, routes `GET /api/pay/quote` + `POST /api/pay`):
|
||||
look up the open session → resolve the active tariff version (latest `effectiveFrom ≤ entry`) →
|
||||
`computeFee` → append a signed `payment` event (amount, currency, tender, `tariffVersionId`,
|
||||
`graceExitMin`). An operator `overrideMinor` covers lost-ticket/dispute (recorded as the charged
|
||||
amount + the quoted amount). Pay-on-foot: payment is decoupled from the exit lane. PCI scope stays
|
||||
out of the app — `tender` only records cash/card; card capture is the standalone P2PE terminal.
|
||||
- **The full transient loop now passes end to end** (verified): entry → quote → pay → exit opens,
|
||||
session closed, `verifyChain` ok.
|
||||
|
||||
> **Resolved (2026-06-16):** the earlier "no entry/exit direction" gap is closed by the
|
||||
> [[entry-exit-points]] model. Direction lives on each access **relay**; readers/cameras bind to a
|
||||
> relay and inherit it. The "lane" concept was dropped entirely (pool-of-spaces) — separate in/out
|
||||
> readers are distinguished by their relay binding, not a lane.
|
||||
@@ -0,0 +1,53 @@
|
||||
---
|
||||
type: concept
|
||||
tags: [parking, printer, device, reliability]
|
||||
sources: []
|
||||
updated: 2026-06-14
|
||||
---
|
||||
|
||||
# Printer roles & failover
|
||||
|
||||
A lane runs **more than one printer**, and the system knows each one's job so it can fail over
|
||||
automatically. This is a reliability decision, not a threat-model one: an entry ticket must
|
||||
still print when the outside dispenser jams or drops off the network.
|
||||
|
||||
## Roles
|
||||
|
||||
Each printer instance (a `devices` row, category `printer`) declares a **role** in its
|
||||
config:
|
||||
|
||||
- **`entry-dispenser`** — outside, at the lane. Prints the entry ticket the driver takes.
|
||||
- **`booth-receipt`** — inside the booth. Prints receipts at exit/payment, AND serves as the
|
||||
**backup** for entry tickets.
|
||||
|
||||
It also declares a **`failoverRank`** (higher = preferred within a role) to order multiple
|
||||
printers of the same role deterministically (ties broken by id).
|
||||
|
||||
## Failover rule (asymmetric, on purpose)
|
||||
|
||||
For an **entry ticket** (`wantRole = entry-dispenser`): try the entry dispensers (best rank
|
||||
first), then fall back to the **booth printer**. So a driver still gets a ticket when the
|
||||
outside unit is offline — the operator hands it over from the booth.
|
||||
|
||||
The reverse is **deliberately not** done: a **receipt** never prints on the outside dispenser.
|
||||
Receipts are a booth-only job; an entry dispenser falling back to print receipts makes no
|
||||
physical sense.
|
||||
|
||||
## Where the logic lives
|
||||
|
||||
- The driver (`rongta`) is **role-agnostic** — role/rank are just config; the transport doesn't
|
||||
care. Keeps [[device-adapter-pattern|adapters]] swappable.
|
||||
- Selection is pure logic in `packages/devices/printer-routing.ts`: `orderForRole()` ranks
|
||||
candidates; `printWithFailover()` attempts the print down the list and throws
|
||||
`NoPrinterAvailableError` only when every candidate fails.
|
||||
- It **attempts the print directly** rather than racing a `healthCheck` first — the print is
|
||||
the real reachability test, and a health probe that passes can still be followed by a failed
|
||||
print.
|
||||
|
||||
## Open: the all-printers-down policy
|
||||
|
||||
When `printWithFailover` exhausts every candidate, what should entry do — raise the barrier
|
||||
with no paper ticket (the plate/[[lpr-camera]] is the independent record), or hold? That policy
|
||||
belongs to the **entry flow** ([[device-input-flow]], [[fail-state-safety]]), not the printer
|
||||
layer, and is **not yet decided**. The signed event ([[append-only-event-chain]]) is created
|
||||
regardless of whether paper prints.
|
||||
@@ -0,0 +1,74 @@
|
||||
---
|
||||
type: concept
|
||||
tags: [parking, printer, device, monitoring, reliability]
|
||||
sources: []
|
||||
updated: 2026-06-14
|
||||
---
|
||||
|
||||
# Printer status monitoring
|
||||
|
||||
The booth must know a printer is in trouble **before** a driver presses the entry button and no
|
||||
ticket comes out. So the system polls each printer's live status (paper out, cover open, cutter
|
||||
jam, off-line) and pushes changes to the operator UI. A reliability control, like
|
||||
[[printer-roles-failover]] — not a threat-model one.
|
||||
|
||||
## Where the status comes from (the safe-decode decision)
|
||||
|
||||
The raw print socket (TCP 9100) is write-only for us — it returns no paper/cover feedback. ESC/POS
|
||||
printers expose status via real-time queries (`DLE EOT n`). On the [[rongta-printer]] clone we
|
||||
probed, **`DLE EOT` replies do NOT follow the canonical ESC/POS bit layout** (the spec's fixed
|
||||
validation bits were wrong, verified on hardware 2026-06-14). Decoding those bits ourselves risked
|
||||
a **false-healthy** — reporting "paper OK" when it's empty — which is the dangerous direction for
|
||||
an entry lane.
|
||||
|
||||
Instead we scrape the device's **own status web page** (`http://<host>/prn_stat.htm`). The board
|
||||
decodes the bits itself into labelled Yes/No rows (Cover Is Open, Cutter Error, Paper End, Paper
|
||||
Near End, Printer Off-Line). We trust the device's decode over hand-decoding an undocumented clone.
|
||||
|
||||
This is captured as a device capability: `MonitorableDevice.readStatus(): PrinterStatus` in
|
||||
`packages/devices`. The Rongta driver implements it; the monitor is device-agnostic via
|
||||
`isMonitorable()`. A future printer with a different status mechanism just implements the same
|
||||
interface.
|
||||
|
||||
## Status mapping (fail safe)
|
||||
|
||||
`readStatus()` maps to `ready | degraded | offline`:
|
||||
|
||||
- status page unreachable / times out → **offline** (same signal as a dead printer; never throws),
|
||||
- page reachable but a recognised field is missing → **degraded** ("unexpected status page") —
|
||||
we do NOT claim "ready" off a page we didn't fully parse,
|
||||
- any fault flag true (paper end, cover open, cutter error, off-line) → **degraded** + a detail
|
||||
string ("paper out", …),
|
||||
- all five clear → **ready**.
|
||||
|
||||
## The monitor (server)
|
||||
|
||||
`PrinterMonitor` (`apps/server/src/printer-monitor.ts`):
|
||||
|
||||
- reloads the monitored set from `devices` each tick (so a newly-assigned printer is picked
|
||||
up without a restart), keeping only enabled, monitorable printers;
|
||||
- polls every `PRINTER_POLL_MS` (default 5000ms), never overlapping ticks;
|
||||
- caches the latest status per device id;
|
||||
- emits a `printer-status` event on the device bus **only when status changes** (deduped).
|
||||
|
||||
## API / live UI
|
||||
|
||||
- `GET /api/printers/status` — cached snapshot of all printers (no device round-trip).
|
||||
- `GET /api/printers/status/stream` — **Server-Sent Events**: full snapshot on connect, then one
|
||||
event per change. The booth SPA subscribes for real-time paper-out / offline indicators.
|
||||
- Any authenticated role may read (operational, not a setup action).
|
||||
|
||||
## Verified on hardware (2026-06-14)
|
||||
|
||||
`readStatus()` against 10.0.10.6 → `ready` (all flags false); against an unreachable host →
|
||||
`offline` with "status page timeout" (no throw); bus emits on change and suppresses unchanged
|
||||
reads. Full repo typechecks.
|
||||
|
||||
## Open / not yet done
|
||||
|
||||
- **Fault-state capture**: we've only observed the all-clear page. The exact label text for an
|
||||
active fault (e.g. does "Paper End" flip to "Yes"?) should be confirmed by physically removing
|
||||
paper / opening the cover, to be 100% sure the scrape catches it. The parser is built to match
|
||||
Yes/No and degrade on anything unexpected, so this is a confidence check, not a blocker.
|
||||
- Tying a `degraded`/`offline` entry-dispenser into [[printer-roles-failover]] failover and the
|
||||
(not-yet-built) entry flow's all-printers-down policy ([[device-input-flow]]).
|
||||
@@ -0,0 +1,48 @@
|
||||
---
|
||||
type: concept
|
||||
tags: [parking, domain, business, reporting]
|
||||
sources: []
|
||||
updated: 2026-06-15
|
||||
status: open
|
||||
---
|
||||
|
||||
# Reporting & Analytics
|
||||
|
||||
Turning the signed event log into the numbers an owner runs the business on. All reports are
|
||||
**projections over the [[append-only-event-chain]]** — the chain is the single source, reports are
|
||||
derived and rebuildable, never a separate ledger.
|
||||
|
||||
## Reports (driven by the events already designed)
|
||||
|
||||
- **Revenue** — by day/week/shift, by tender (cash vs. card), gross vs. discounts vs. net. Source:
|
||||
`payment` events + [[validation-discounts|discount]] events + `shift_z_report` ([[shift]]).
|
||||
- **Occupancy** — current ([[capacity-occupancy]]) and historical curve; peak times; turnover.
|
||||
- **Stay analytics** — average/median duration, distribution; transient vs. [[permit]] split.
|
||||
- **Permit usage** — active permits, utilisation, concurrency vs. `maxConcurrent`.
|
||||
- **Anomalies** — out-of-band opens, never-exited sessions, occupancy drift, over-validation —
|
||||
the `anomaly` events + reconciliation findings ([[reconciliation]]).
|
||||
|
||||
## Plate / entry search (admin lookup) — user-requested 2026-06-15
|
||||
|
||||
The admin can **search for an entry/session by licence plate** — *if the plate was captured* (by
|
||||
the [[opencv-anpr-service|vision service]] or an LPR read; a pure-ticket transient has no plate).
|
||||
Returns the matching session(s): entry/exit times, fee, payment, snapshot image. Useful for
|
||||
disputes ("I was charged for a car that left earlier"), lost-ticket lookup, and incident review.
|
||||
|
||||
- Search keys: plate (when captured), ticket id, session id, time range.
|
||||
- Read-only over the chain; surfaces the linked snapshot ([[lpr-camera]] `imageRef`) as evidence.
|
||||
- Honest limit: **no plate → no plate-search hit.** The UI must say "not captured", not "no such
|
||||
car", so the absence isn't mistaken for a missing record.
|
||||
|
||||
## Properties
|
||||
|
||||
- **Offline** ([[offline-first]]): all computed locally from the local DB; no cloud BI dependency.
|
||||
- **Reproducible**: a report run twice over the same chain gives the same answer; figures trace to
|
||||
signed events.
|
||||
- **Export** for [[reconciliation]] / accounting (CSV/PDF) — the periodic external-authority path
|
||||
([[open-questions]] #4).
|
||||
|
||||
## Open
|
||||
|
||||
- Which reports matter at launch vs. later; the export format/cadence.
|
||||
- Dashboard (live) vs. on-demand reports.
|
||||
@@ -0,0 +1,95 @@
|
||||
---
|
||||
type: concept
|
||||
tags: [parking, domain, business, shifts, anti-fraud]
|
||||
sources: []
|
||||
updated: 2026-06-15
|
||||
status: open
|
||||
---
|
||||
|
||||
# Shift (manned mode) & the Z-Report
|
||||
|
||||
A **shift** is one operator's accountability period at a manned booth: from the moment they take
|
||||
over to the moment they hand over, however long that is. At the end, the system signs and **prints
|
||||
a Z-report** — the cash and POS totals taken during the shift. (Decisions 2026-06-15.)
|
||||
|
||||
## Shifts exist ONLY in manned mode
|
||||
|
||||
A shift is fundamentally a **human accountability boundary** — "this person was responsible for the
|
||||
takings from here to here." In the [[autonomous-direction|fully-automated / unmanned]] system there
|
||||
is **no operator and no shift**; what replaces it is the pay station's **cash-collection cycle**
|
||||
(who emptied the vault, when, how much vs. what the signed log expected) plus ongoing
|
||||
[[reconciliation]] — a separate concept, not a shift. So shifts are scoped to manned operation;
|
||||
don't force one model across both.
|
||||
|
||||
## A shift is NOT time-based
|
||||
|
||||
It is delimited by **explicit operator action**, never by a clock:
|
||||
|
||||
- Booth reality: relief comes late, doesn't show, or one operator is **forced to work two shifts in
|
||||
a row**. A fixed 8h boundary (or an 8h token expiry) would be wrong — it could strand an active
|
||||
operator. So the [[local-jwt-auth|login token has no time expiry]] (valid until logout).
|
||||
- **Start Shift / End Shift are explicit, and independent of login.** One login can span many
|
||||
shifts; a back-to-back double is simply *End Shift → Start Shift again*, no re-login. The
|
||||
operator (the same person or the next) marks the boundary.
|
||||
|
||||
```
|
||||
login ——————————————————————————————————————————————→ (until logout)
|
||||
[Start shift] … takings … [End shift→sign+print Z] [Start shift] … [End shift] …
|
||||
```
|
||||
|
||||
## What End Shift does
|
||||
|
||||
1. Determine the shift's payment set: the signed `payment` events ([[parking-session]],
|
||||
[[append-only-event-chain]]) between this shift's start mark and now.
|
||||
2. Sum by **tender**: `cashTotal`, and `cardTotal` from the POS/terminal **if a POS is configured**
|
||||
(the card line is omitted when there's no terminal).
|
||||
3. Append a signed **`shift_z_report`** event (type already in `packages/shared`): `{ operator,
|
||||
startedAt, endedAt, cashTotal, cardTotal?, paymentCount, eventRange, prevZHash }` — chained to
|
||||
the prior Z so a missing/out-of-order Z-report is itself visible.
|
||||
4. **Print the Z-report** (cash total, POS total if any, counts, shift window, operator) on the
|
||||
booth printer.
|
||||
|
||||
That's the whole human-side requirement: **print the cash and the POS (if any).** No blind count,
|
||||
no variance gate, no manager override.
|
||||
|
||||
### As-built (2026-06-16)
|
||||
|
||||
- A shift is **two signed ledger events**, no mutable table (decision): `shift_open` (new event
|
||||
type) at start, `shift_z_report` at close. The operator is the **logged-in user**, carried in the
|
||||
event `identity`; a shift is **open** iff that operator's most recent shift event is a
|
||||
`shift_open`. `ShiftService` (`apps/server/src/shift-service.ts`).
|
||||
- **Close** sums `payment` events in `[startedAt, endedAt]` by tender (cash vs. card, by **payment
|
||||
time**), appends the signed `shift_z_report` (totals + counts + window), then **prints** via the
|
||||
new generic `PrinterDevice.printReport(title, lines)` (Rongta ESC/POS text) to a booth-receipt
|
||||
printer. Printing is best-effort — a failed print does **not** undo the signed close (the event is
|
||||
the record; `printed:false` is returned).
|
||||
- **Routes** (`routes/shift.ts`, cashier/operator/admin): `GET /api/shift/current`,
|
||||
`POST /api/shift/open` (409 if already open), `POST /api/shift/close` (409 if none open).
|
||||
**UI** `ShiftControl` in the app shell (non-readonly): Start/End + the Z-report totals.
|
||||
- Verified: open → double-open 409 → payments (cash+card, one dated outside the window excluded) →
|
||||
close totals correct + signed + printed → close-again 409 → re-open works; readonly 403;
|
||||
verifyChain ok.
|
||||
|
||||
## Where the fraud control actually lives
|
||||
|
||||
Deliberately **not** in a shift-close ceremony. Because every payment is a **signed event in the
|
||||
append-only chain**, the printed cash figure *is* the system's tamper-evident truth. A manager
|
||||
reconciles the signed Z-report against the actual drawer and the bank/POS batch **later** — that's
|
||||
[[reconciliation]], the real control (deferred). The tradeoff vs. a heavier control is purely
|
||||
*when* a skim is caught (after the fact, by a human), not *whether*.
|
||||
|
||||
> **Optional enhancement (not building now): blind cash count.** Have the operator enter the
|
||||
> counted cash *before* the system reveals the expected figure, and record the variance into the
|
||||
> `shift_z_report`. Blindness removes the operator's ability to back-fill their declaration to match
|
||||
> expectation, catching a skim **at close** rather than later. Explicitly out of scope per
|
||||
> 2026-06-15; documented as a clean add-on if ever wanted.
|
||||
|
||||
## Open
|
||||
|
||||
- **Shift ↔ session boundary:** a vehicle may enter under one shift and pay under another — the
|
||||
Z-report sums by **payment time** (when cash/card was taken), which is the operator who handled
|
||||
the money. Confirm that's the intended accountability (vs. by entry).
|
||||
- **Mid-shift report / X-report** (read-only "so far" total without closing) — add if booths want
|
||||
it; the sum is the same projection.
|
||||
- **Multiple lanes/booths** — whether a shift is per-operator, per-booth, or per-site
|
||||
(relates to [[open-questions]] #1 lane topology).
|
||||
@@ -0,0 +1,180 @@
|
||||
---
|
||||
type: concept
|
||||
tags: [parking, domain, business, pricing]
|
||||
sources: []
|
||||
updated: 2026-06-15
|
||||
status: open
|
||||
---
|
||||
|
||||
# Tariff (Fee Model)
|
||||
|
||||
How a [[parking-session]]'s fee is computed from its duration. A tariff is **admin-composed data,
|
||||
not code** — the park owner builds and constantly edits the rate card at runtime (like a
|
||||
[[permit]]), in a selectable currency, with **no numbers hard-coded anywhere** and no code change to
|
||||
reprice. The computation is **pure and offline** ([[offline-first]]: no network, no clock authority
|
||||
beyond the host).
|
||||
|
||||
> Decisions (2026-06-15): (1) tariffs are **effective-dated, immutable versions** — editing
|
||||
> publishes a new version, never mutates an old one; (2) **one active tariff per site** (versioned
|
||||
> over time), modelled with an id/scope so multiple rate cards can be added later without migration;
|
||||
> (3) **currency is selectable** (ISO 4217) and the money model is **FX-ready but FX is deferred**.
|
||||
|
||||
## Design principles
|
||||
|
||||
- **Pure function of (entry time, charge time, tariff).** `fee = f(enteredAt, asOf, tariff)`. No
|
||||
side effects, deterministic, unit-testable. The pay station calls it with `asOf = now`; the exit
|
||||
lane re-checks against the recorded payment.
|
||||
- **Data-driven.** The tariff lives as a config record (its own table or seeded config), versioned,
|
||||
so a historical session always reprices against the tariff in force when it was incurred. Never
|
||||
hard-code rates (this is an [[open-questions|open-question]]-adjacent procurement input — sites
|
||||
differ).
|
||||
- **Integer minor units.** Money is integer cents (or the site currency's minor unit) — never
|
||||
floats. Avoids rounding drift across a revenue ledger.
|
||||
- **The fee, once paid, is a signed `payment` event** ([[parking-session]]) — the computation is
|
||||
reproducible, but the *charged* amount is fixed in the chain.
|
||||
|
||||
## The composable structure — stepped blocks + daily cap
|
||||
|
||||
The admin composes a **rate card** the fee function interprets. The general model is an **ordered
|
||||
list of duration blocks** (flat rate is just one block) plus a daily cap — chosen because it
|
||||
expresses every common operator shape (first-hour pricing, tapering, caps) with no special cases in
|
||||
code. All amounts are **integer minor units** in the tariff's currency.
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"currency": "EUR", // ISO 4217; selectable per tariff version
|
||||
"gracePeriodEntryMin": 15, // free if exited within this (drop-off/turnaround)
|
||||
"incrementMin": 60, // billing granularity; partial increments round UP
|
||||
"blocks": [ // consumed in order as duration accrues
|
||||
{ "uptoMin": 60, "priceMinorPerIncrement": 200 }, // first hour
|
||||
{ "uptoMin": 180, "priceMinorPerIncrement": 150 }, // 60→180 min
|
||||
{ "uptoMin": null, "priceMinorPerIncrement": 100 } // null = open-ended, thereafter
|
||||
],
|
||||
"dailyCapMinor": 1200, // cap per rolling 24h (null = no cap)
|
||||
"lostTicketMinor": 2000, // flat charge when there's no entry id
|
||||
"gracePeriodExitMin": 15, // pay-on-foot walk-back window
|
||||
"overstay": "reprice" // top-up = recompute(entry→now) − alreadyPaid (decided)
|
||||
}
|
||||
```
|
||||
|
||||
> **The numbers above are illustrative, not defaults to ship.** "No one knows the pricing and it
|
||||
> changes constantly" — so the admin authors all of it; the system ships with **no rate card** and
|
||||
> the owner must compose + publish one before the lot can charge (until then: free, or gated —
|
||||
> operator policy, see Open).
|
||||
|
||||
**Lost ticket** is not just the flat `lostTicketMinor`: the admin may **override with an arbitrary
|
||||
amount** at the moment (operator judgement — establish entry time from [[opencv-anpr-service|plate]]
|
||||
capture/CCTV and charge real duration, or apply a set penalty). The configured flat fee is the
|
||||
default; the chosen amount is recorded in the signed `payment` event ([[parking-session]]).
|
||||
|
||||
## The fee algorithm (pure, integer, offline)
|
||||
|
||||
```
|
||||
fee(enteredAt, asOf, tariff):
|
||||
minutes = roundUp(asOf − enteredAt, incrementMin)
|
||||
if minutes ≤ gracePeriodEntryMin: return 0
|
||||
total = 0
|
||||
for each rolling 24h segment of the stay:
|
||||
segMinutes = minutes within this segment
|
||||
segFee = walk `blocks` in order, charging priceMinorPerIncrement for each
|
||||
incrementMin that falls in each block's [prevUpto, uptoMin) range
|
||||
if dailyCapMinor: segFee = min(segFee, dailyCapMinor)
|
||||
total += segFee
|
||||
return total
|
||||
```
|
||||
|
||||
Deterministic, side-effect-free, unit-testable; the daily cap is applied **per rolling 24h** (so an
|
||||
overnight stay doesn't hit the cap twice). Rounding and segment edges are part of the settled spec
|
||||
because the chain + reconciliation depend on the result being reproducible.
|
||||
|
||||
**Settled edges (2026-06-15, with tests):**
|
||||
- **Grace uses RAW duration** — a stay within `gracePeriodEntryMin` is free even though the
|
||||
increment would round it up (else rounding defeats the grace window).
|
||||
- **The block ladder RESETS each rolling-24h day** — day 2 starts at the first block again (a 25h
|
||||
stay = day-1 capped + day-2 first-hour rate), so the "daily" rate truly resets daily.
|
||||
|
||||
**As-built:** `computeFee(enteredAt, asOf, structure)` in `packages/shared` (pure). Unit-tested
|
||||
across grace, block steps, daily cap, and multi-day reset.
|
||||
|
||||
### Composer (as-built 2026-06-15)
|
||||
|
||||
The admin authors the rate card at runtime — no hand-seeding:
|
||||
|
||||
- **API** (`apps/server/src/routes/tariffs.ts`): `GET /api/tariff` (active version + history; any
|
||||
signed-in role) and `POST /api/tariff/versions` (publish a new immutable version; **admin only**).
|
||||
Publishing validates the structure via `validateTariffStructure` (shared) — non-negative integers,
|
||||
ordered/ascending block bounds, only the last block open-ended — so a malformed card can never be
|
||||
published. The single site `tariffs` row is created lazily on first read/publish.
|
||||
- **UI** (`apps/web/src/TariffComposer.tsx`, admin shell): edit currency, grace windows, increment,
|
||||
daily cap, lost-ticket fee, and add/remove rate blocks; amounts entered in major units, converted
|
||||
to integer minor units on submit. Shows the active version + history; "Publish" creates a new
|
||||
version (past sessions keep their pricing).
|
||||
- Ships **blank** — until a version is published, `GET /api/tariff` returns `active: null` and the
|
||||
pay station returns `409 no active tariff`. Verified end to end (publish → pay station prices).
|
||||
|
||||
## The pay-on-foot consequence
|
||||
|
||||
Because payment is decoupled from exit ([[parking-session]] lifecycle), the tariff has **two
|
||||
time references**, not one:
|
||||
|
||||
1. At the **pay station**: `fee = f(enteredAt, now, tariff)` — charge for time parked so far.
|
||||
2. At the **exit lane**: the session is valid to leave iff `now ≤ paidAt + gracePeriodExit`.
|
||||
Past that, an **overstay top-up** = `f(paidAt, now, tariff.overstayRate)` is due before exit.
|
||||
|
||||
`gracePeriodExit` is therefore a real revenue/UX parameter, not a nicety: too short traps people
|
||||
who paid; too long gives free parking between pay and exit.
|
||||
|
||||
## Permit holders
|
||||
|
||||
A valid [[permit]] bypasses tariff computation entirely for the covered period (subscription
|
||||
already paid out-of-band). A permit that has lapsed mid-stay falls back to the transient tariff for
|
||||
the uncovered time — an edge case to design with [[permit]].
|
||||
|
||||
## Versioning — edits publish immutable, effective-dated versions
|
||||
|
||||
Prices change constantly, **and** a historical [[parking-session]] must reprice against the rate
|
||||
that was in force when it was incurred — never today's. So a tariff is **never edited in place**:
|
||||
|
||||
- Each save **publishes a new version** with an `effectiveFrom` timestamp; prior versions are
|
||||
**immutable**. Picking the version for a session = "the latest version with `effectiveFrom ≤
|
||||
session entry time`".
|
||||
- The session's **`payment` event records the `tariffVersionId`** it was priced under
|
||||
([[parking-session]], [[append-only-event-chain]]). The charged amount is then both reproducible
|
||||
*and* fixed in the signed chain — an admin can't retroactively rewrite prices to alter what a past
|
||||
session "should have" paid without it being visible.
|
||||
- An **in-progress** session that crosses a version boundary uses the version in force at **entry**
|
||||
(consistent, predictable) — confirm vs. pro-rating if an operator ever wants the latter.
|
||||
|
||||
## Data model (first cut — with [[session-model]])
|
||||
|
||||
| Table / field | Notes |
|
||||
| --- | --- |
|
||||
| `tariffs` | a logical rate card: `id`, `scope` (site/lane/zone — only "site" used now), `name`. |
|
||||
| `tariff_versions` | `id`, `tariffId`, `effectiveFrom`, `currency`, `structure` (the JSON above), `createdBy`, `createdAt`. **Immutable.** |
|
||||
| (active) | "one active tariff per site" = one `tariffs` row; multiple `tariff_versions` over time. The `scope`/`id` exist so multiple rate cards can be added later **without migration**. |
|
||||
|
||||
Unlike the event log, tariff data is **mutable master data** in the sense that new versions are
|
||||
*added*; but each version row, once published, is never changed — close to append-only, and the
|
||||
*use* of it is fixed in the signed `payment` event.
|
||||
|
||||
## Currency & FX — selectable now, FX deferred
|
||||
|
||||
- Each `tariff_version` names its **`currency`** (ISO 4217), admin-selectable. Amounts everywhere
|
||||
are `{ minorUnits, currency }` — never a bare number, never a float.
|
||||
- A `payment` event stores its **`currency`** and a reserved **`fxRate` (null for now)** + optional
|
||||
`baseCurrency`. So when an exchange-rate system is added later, historical payments stay
|
||||
reproducible (you know the currency charged and, once FX exists, the rate applied) — **no
|
||||
migration** of stored amounts.
|
||||
- **FX engine is NOT built now.** When it is, it needs an *offline* rate source (rates can't depend
|
||||
on the network — [[offline-first]]), a base currency, and a rounding policy. Deferred to
|
||||
[[open-questions]].
|
||||
|
||||
## Open
|
||||
|
||||
- The **actual rate cards** are owner-authored at runtime — nothing to confirm at build time; the
|
||||
composer UI + validation (sane blocks, non-negative, ordered `uptoMin`) is the work.
|
||||
- **Time-of-day / weekday tiers** — not in the block model yet; add as a tier wrapper if a site
|
||||
needs day/night/weekend cards (deferred until asked).
|
||||
- **Blank-tariff policy** — free vs. gated until a rate card is published (operator policy).
|
||||
- **In-progress version-boundary** — entry-version (decided) vs. pro-rate (revisit if needed).
|
||||
- **FX** — exchange-rate system, offline rate source, base currency ([[open-questions]]).
|
||||
@@ -35,3 +35,9 @@ The controls that actually address insider/operator fraud are different in kind:
|
||||
The same reframing recurs at the device layer: the [[uhppote-controller]]'s real problem is
|
||||
unauthenticated commands ([[uhppote-udp-protocol]]), addressed by detection
|
||||
([[event-log-ingestion]]) or prevention ([[esp32-custom-controller]]).
|
||||
|
||||
> **Direction shift:** the system is heading toward **fully unmanned operation** — no operator, no
|
||||
> booth ([[autonomous-direction]]). That removes the booth-operator as the *primary* adversary, but
|
||||
> swaps in **unattended-machine threats** (tailgating, plate spoofing, physical tampering, forced
|
||||
> entry). The append-only signed log + reconciliation controls carry over; the emphasis moves from
|
||||
> "catch the cashier" to "trust the automated record and detect tampering."
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
---
|
||||
type: concept
|
||||
tags: [parking, domain, business, devices, entry-flow]
|
||||
sources: []
|
||||
updated: 2026-06-15
|
||||
status: open
|
||||
---
|
||||
|
||||
# Ticket Encoding & Scanning
|
||||
|
||||
How a transient [[parking-session]]'s **ticket id** is printed, carried by the customer, and read
|
||||
back at the pay station and exit. This is the **physical backbone of the transient flow** — the
|
||||
thing that links entry → pay → exit when there's no plate.
|
||||
|
||||
## The ticket id is the session key
|
||||
|
||||
At entry the system mints a `vehicle_entry` event with a **ticket id** (`identity`) and prints a
|
||||
ticket the customer keeps. That same id is read back later to find the session. Properties the id
|
||||
must have:
|
||||
|
||||
- **Opaque + unguessable** — a random id (not a sequential count an attacker could iterate to claim
|
||||
someone else's cheaper session). Sequential **physical** stock numbering is a separate
|
||||
reconciliation aid ([[reconciliation]] pre-numbered stock), not the scan key.
|
||||
- **Single logical session** — scanning it at the pay station finds the open session; after payment
|
||||
it's the proof-of-paid the exit checks.
|
||||
|
||||
## Encoding: QR (preferred) — printed by the booth dispenser
|
||||
|
||||
- The [[rongta-printer]] prints the ticket id as a **2D barcode (QR)** plus human-readable text and
|
||||
entry time. QR over 1D barcode: denser, tolerant of crumpling/partial reads, easy for a cheap
|
||||
camera/imager to read.
|
||||
- **Scan points** (both host-side reads — [[entry-exit-readers]]):
|
||||
- **Pay station** — customer scans the ticket → host finds the session → shows fee → takes
|
||||
payment ([[tariff]], pay-on-foot) → appends `payment`.
|
||||
- **Exit lane** — customer scans the (now paid) ticket → host validates paid + within
|
||||
`gracePeriodExit` → `vehicle_exit` → `pulseOpen`.
|
||||
- The **scanner is a device behind an adapter** ([[device-adapter-pattern]]): a new `ReaderDevice`
|
||||
kind (QR/barcode imager) — likely the same `IdentitySource = "ticket"` / `"qr"` path. Keeps the
|
||||
app device-agnostic; hardware model is procurement ([[bom]], [[open-questions]]).
|
||||
- **On hand:** the **[[gee-qr-er80]]** QR access reader (`-Q-W`: QR scanner, Wiegand/RS-232/RS-485,
|
||||
Linux-supported) — the concrete scanner for this path. A serial `ReaderDevice` adapter feeds the
|
||||
`read` bus; pending the reader's RS-232 frame/baud (see [[gee-qr-er80]] open questions).
|
||||
|
||||
## Ticketless alternative (plate as the ticket)
|
||||
|
||||
Where the [[opencv-anpr-service|vision service]]/LPR captures the plate, the **plate can be the
|
||||
session key** instead of a printed ticket — drive in, plate read, drive to pay station and enter
|
||||
plate (or it's looked up), pay, exit by plate. No paper. The two can coexist per lane
|
||||
([[entry-exit-readers]] "both share a relay"); a printed QR ticket is the fallback when a plate
|
||||
isn't captured or is low-confidence (recognition is advisory — [[opencv-anpr-service]]).
|
||||
|
||||
## Open
|
||||
|
||||
- QR symbology/error-correction level + what else prints (site name, tariff summary, help number).
|
||||
- Scanner hardware (imager model; same unit at pay station and exit?).
|
||||
- Lost/damaged ticket → the lost-ticket path ([[parking-session]], [[tariff]] admin-arbitrary
|
||||
amount).
|
||||
@@ -7,6 +7,11 @@ updated: 2026-06-14
|
||||
|
||||
# UHPPOTE vs. Custom ESP32 — Detection vs. Prevention
|
||||
|
||||
> **Historical comparison.** Neither is the current device — the [[uhppote-controller]] was
|
||||
> **rejected** (entry-flow blocker → [[dingtian-relay]] chosen) and the [[esp32-custom-controller]]
|
||||
> is **deferred**. Kept because the **detection-vs-prevention** framing on the [[trust-boundary]]
|
||||
> fork is a durable lens that applies to any access device.
|
||||
|
||||
A head-to-head on the [[trust-boundary]] fork: the off-the-shelf [[uhppote-controller]] versus
|
||||
the [[esp32-custom-controller]]. (Synthesized from [[parking-system-architecture]] §6–7.)
|
||||
|
||||
@@ -23,9 +28,10 @@ the [[esp32-custom-controller]]. (Synthesized from [[parking-system-architecture
|
||||
|
||||
## Bottom line
|
||||
|
||||
- The UHPPOTE is the **current choice**: good enough as a detection/audit layer **when only the
|
||||
host can reach it** (isolation) and every event lands in the [[append-only-event-chain]].
|
||||
- The ESP32 is the **documented upgrade** when you need a control path that holds even against an
|
||||
attacker on the wire. They're **mixable per lane**.
|
||||
- The UHPPOTE was the **detection-grade** option: good enough as a detection/audit layer **when
|
||||
only the host can reach it** (isolation) and every event lands in the [[append-only-event-chain]]
|
||||
— but it was rejected for the entry lane (the button blocker).
|
||||
- The ESP32 is the **prevention-grade** option when you need a control path that holds even against
|
||||
an attacker on the wire. Deferred.
|
||||
- Both still rely on host-side integrity ([[append-only-event-chain]]) and external
|
||||
[[reconciliation]] as the ultimate anti-fraud control.
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
---
|
||||
type: concept
|
||||
tags: [parking, domain, business, capacity, manned]
|
||||
sources: []
|
||||
updated: 2026-06-15
|
||||
status: open
|
||||
---
|
||||
|
||||
# Valet / Over-Capacity Mode
|
||||
|
||||
"Full" is **not** necessarily a hard stop. If the operator opts in, a lot at nominal capacity can
|
||||
still accept cars via **valet**: the customer hands over the keys and leaves, and the operator
|
||||
stacks/double-parks the vehicle beyond the marked space count. (User direction, 2026-06-15.)
|
||||
|
||||
## "Full" is a soft, operator-configurable policy
|
||||
|
||||
The [[capacity-occupancy]] FULL gate is therefore a **policy knob**, not a physical absolute:
|
||||
|
||||
- **Refuse** — hard stop at nominal capacity (the default/strict behaviour).
|
||||
- **Valet over-capacity** — accept beyond capacity into operator custody.
|
||||
|
||||
The choice is the operator's, per site (and possibly per time/condition).
|
||||
|
||||
## Valet is a manned-mode feature with a different session shape
|
||||
|
||||
Valet only exists when there's an operator (cf. [[shift]] — manned-only). It adds a **custody**
|
||||
dimension the normal [[parking-session]] doesn't have:
|
||||
|
||||
- The **operator takes custody** of the car — identity is a **claim/valet ticket**, and the
|
||||
operator (not the driver) is accountable for the vehicle between handover and return.
|
||||
- New facts to record (as signed [[append-only-event-chain]] events when built): **key handover**,
|
||||
where/when parked, and **return** to the customer. The operator's accountability ties into the
|
||||
[[shift]] Z-report and [[reconciliation]] (a valet car with no return record is an anomaly).
|
||||
- Payment still flows through the normal [[tariff]] (duration-based) unless a separate valet fee
|
||||
applies.
|
||||
|
||||
## Status — deferred
|
||||
|
||||
Captured now so the [[capacity-occupancy]] design treats "full" as soft and the entry flow leaves a
|
||||
clean seam. **Not** built into the current transient entry flow (decision 2026-06-15). Full design —
|
||||
the valet session/custody model, the claim ticket, the over-capacity accept path — is future work.
|
||||
|
||||
## Open
|
||||
|
||||
- Valet session/custody data model (claim ticket, parked location, return event).
|
||||
- Whether a distinct valet fee/tariff applies, or normal duration pricing.
|
||||
- Operator UI for handover/return; how it ties to the [[shift]] accountability record.
|
||||
@@ -0,0 +1,46 @@
|
||||
---
|
||||
type: concept
|
||||
tags: [parking, domain, business, pricing, revenue]
|
||||
sources: []
|
||||
updated: 2026-06-15
|
||||
status: open
|
||||
---
|
||||
|
||||
# Validation & Discounts
|
||||
|
||||
A merchant (shop, hotel, clinic) **validates** a customer's parking so they pay less or nothing —
|
||||
a common revenue/retention feature that modifies what a [[parking-session]] owes.
|
||||
|
||||
## Model: a discount is a signed event, applied at fee time
|
||||
|
||||
A validation is **not** an edit to the session or a mutable "discount applied" flag — same reason
|
||||
as everything else ([[threat-model]]: an operator/merchant could otherwise fake free parking). It's
|
||||
recorded so the fee computation and the audit both see it:
|
||||
|
||||
- A **discount/validation event** references the session: `{ sessionRef, kind, value, issuedBy,
|
||||
ts }` — e.g. *2 hours free*, *€5 off*, *flat €1*, *100% off*. Appended + signed
|
||||
([[append-only-event-chain]]).
|
||||
- The [[tariff]] fee function applies eligible validations when computing what's due at the pay
|
||||
station: `due = max(0, tariff_fee − discounts)` (or time-based: subtract validated minutes before
|
||||
pricing). Pure + reproducible, like the base fee.
|
||||
- The `payment` event then records gross fee, discount total, and net paid — so revenue reporting
|
||||
([[reporting-analytics]]) can show **discount leakage** (how much was given away, by whom).
|
||||
|
||||
## How a validation is presented
|
||||
|
||||
- **Merchant terminal / portal** stamps the customer's ticket id (or plate) — issues the validation
|
||||
event for that session.
|
||||
- Or a **validation code** the customer enters at the pay station.
|
||||
- Either way it ties to the session by **ticket id or plate** ([[parking-session]] identity).
|
||||
|
||||
## Anti-abuse
|
||||
|
||||
Because each validation is signed and attributed (`issuedBy`), over-validation by a colluding
|
||||
merchant is **visible to [[reconciliation]]** (a merchant validating far more than their footfall is
|
||||
an anomaly), rather than invisible free parking.
|
||||
|
||||
## Open
|
||||
|
||||
- Validation types the site needs (free hours / fixed amount / percentage / flat rate).
|
||||
- Whether merchants self-serve (portal/terminal) or the operator applies it.
|
||||
- Caps (max discount, max per merchant/day).
|
||||
@@ -0,0 +1,118 @@
|
||||
---
|
||||
type: reference
|
||||
tags: [parking, dev-environment, networking, wsl, troubleshooting]
|
||||
sources: []
|
||||
updated: 2026-06-15
|
||||
---
|
||||
|
||||
# WSL2 Dev Networking (for device testing)
|
||||
|
||||
> Dev-environment note, not product architecture. Recorded because reaching real
|
||||
> hardware (the [[uhppote-controller]]) from a dev box running under **WSL2** took
|
||||
> significant debugging. If you test devices from WSL, read this first.
|
||||
|
||||
## The problem
|
||||
|
||||
By default WSL2 uses **NAT networking**: the Linux VM sits on its own virtual subnet
|
||||
(e.g. `172.x`), not the Windows host's LAN. Consequences for device work:
|
||||
|
||||
- **UDP broadcast (UHPPOTE discovery) cannot leave the VM** — a `get-devices` broadcast gets
|
||||
`EACCES` / never reaches a controller on the physical LAN. The device is reachable from
|
||||
*Windows* but not from *inside WSL*.
|
||||
- Even unicast to a LAN device may not route, depending on setup.
|
||||
|
||||
## The fix: mirrored networking
|
||||
|
||||
Switch WSL to **mirrored** mode so it shares the Windows host's interfaces (and thus the real
|
||||
LAN). Requires **Windows 11 22H2+** and **WSL ≥ 2.0**.
|
||||
|
||||
`%UserProfile%\.wslconfig` (create it; it doesn't exist by default):
|
||||
|
||||
```ini
|
||||
[wsl2]
|
||||
networkingMode=mirrored
|
||||
firewall=false # Windows Firewall otherwise filters WSL traffic (can drop UDP replies)
|
||||
|
||||
[experimental]
|
||||
hostAddressLoopback=true # host <-> WSL over the host's IP
|
||||
```
|
||||
|
||||
Apply: in **PowerShell** `wsl --shutdown`, wait ~10 s, reopen WSL. Verify with `ip -4 addr` —
|
||||
interfaces should now show the **real LAN subnet** (e.g. `10.0.10.x`) instead of `172.x`.
|
||||
(Microsoft recommends editing via the **WSL Settings** GUI rather than the file by hand.)
|
||||
|
||||
> `wsl --shutdown` kills the dev servers — restart `pnpm dev` afterward.
|
||||
|
||||
## After mirrored mode: app-level gotchas that remained
|
||||
|
||||
Mirrored networking is necessary but **not sufficient** — these still bit us:
|
||||
|
||||
- **Multiple interfaces.** Mirrored WSL exposes *all* host NICs (LAN, Tailscale/CGNAT `100.x`,
|
||||
docker bridges). UHPPOTE discovery must broadcast on **every** subnet, not the first one — see
|
||||
[[device-discovery]].
|
||||
- **Subnet-directed broadcast** (`10.0.10.255`, not `255.255.255.255`) — the lib won't enable
|
||||
`SO_BROADCAST` otherwise. See [[device-discovery]].
|
||||
- **`localhost` → IPv6 first.** `localhost` resolves to `::1`, but the backend binds IPv4
|
||||
(`127.0.0.1`). Node's Vite proxy can stall on the v6 attempt before falling back — point the
|
||||
proxy at `127.0.0.1` explicitly. (See [[local-dev-workflow]].)
|
||||
|
||||
## Multi-subnet source-address trap (the "ARP works but ping/TCP dies" bug)
|
||||
|
||||
Field devices arrive **statically configured on assorted `/24`s** by whoever installed them last
|
||||
(e.g. a camera on `10.0.10.121`, a printer on `10.0.10.6`, others on `192.168.1.x`). The host
|
||||
copes by carrying **one IP per device subnet on a single NIC** (this is correct — you do **not**
|
||||
need a NIC per subnet). But stacking subnets on one interface exposes a Linux source-selection
|
||||
trap:
|
||||
|
||||
- Connected routes come up as `proto kernel scope link` **with no preferred source**. With two
|
||||
such subnets on one NIC, the kernel may pick the **wrong source address** — e.g. sourcing
|
||||
traffic to `10.0.10.121` from `192.168.1.123`.
|
||||
- Symptom is baffling: **ARP resolves and the neighbor shows `REACHABLE`** (L2 is fine, source
|
||||
address is irrelevant to ARP) while **every ping and TCP connect times out** (replies have a
|
||||
wrong/unroutable source → dropped, possibly by uRPF). Looks like "the device is down / the whole
|
||||
subnet is unreachable" when nothing is actually broken.
|
||||
- **Diagnose:** `ip route get <device-ip>` shows the chosen `src` — if it's an address on a
|
||||
*different* subnet, that's the bug. Confirm by forcing the right source:
|
||||
`ping -I <correct-src> <device-ip>` (or `curl --interface <correct-src> …`) — instant replies.
|
||||
- **Fix (runtime):** pin the preferred source on the connected route, per subnet:
|
||||
`sudo ip route replace <subnet>/24 dev <nic> proto kernel scope link src <correct-host-ip> metric <m>`
|
||||
(use `replace`, not `change` — `change` errors `RTNETLINK: No such file` if the route isn't up
|
||||
yet). Do **not** delete the other subnet's address unless it's genuinely unwanted — you need all
|
||||
of them to reach all the devices.
|
||||
|
||||
- **Fix (permanent, this box):** `deploy/wsl-fix-route-source.sh` + `deploy/parking-net.service`.
|
||||
The script walks each `proto kernel scope link` route on the NIC and pins `src` to THIS host's own
|
||||
address in that same subnet — **no hardcoded IPs**, so it also covers future device subnets; it's
|
||||
idempotent, preserves the route metric, and tolerates a missing route. The systemd unit (oneshot,
|
||||
`enabled`) reapplies it on every WSL boot — which is the point, since `wsl --shutdown` otherwise
|
||||
wipes the runtime fix (mirrored mode re-clones the Windows addresses fresh each boot, see below).
|
||||
Install once: copy the unit to `/etc/systemd/system/`, `systemctl enable --now parking-net`.
|
||||
Gotchas hit while building it: `network.target` is too early for mirrored-mode addresses (the
|
||||
script waits up to 15s for a route to appear); and it must NOT `set -e` or one failed `ip` call
|
||||
aborts the whole boot fixer.
|
||||
|
||||
> **Root cause is on the Windows side.** Mirrored mode clones the Windows host NIC's addresses into
|
||||
> Linux at every boot, so the stray `192.168.1.x` lives on Windows — the truly permanent fix is to
|
||||
> remove/reconfigure it there (or set `SkipAsSource`/interface metric). The systemd hook is the
|
||||
> self-contained Linux-side answer that needs no Windows changes.
|
||||
|
||||
Verified on hardware (2026-06-15): after the hook, `10.0.10.121` pings and the real [[lpr-camera]]
|
||||
Hikvision driver pulls a snapshot with **no** source-forcing (`localAddress` becomes optional).
|
||||
|
||||
## On the real appliance: multi-subnet is a deployment config, not a WSL hack
|
||||
|
||||
Production is a **dedicated hardened Linux appliance** ([[disk-os-hardening]]), so the WSL story
|
||||
above is dev-only. The device-subnet problem persists, though, and is solved the same way at the
|
||||
OS level: the appliance NIC carries **one address per device subnet**, each connected route with a
|
||||
pinned `src`, made persistent (systemd-networkd / netplan). Per the threat model this still rides
|
||||
on **[[network-isolation]]** — device subnets are isolated segments reachable only by the host.
|
||||
The long-term clean answer is to **re-IP the devices onto one planned parking-system subnet** at
|
||||
install so the host needs only one address; the multi-subnet config is what you run until then.
|
||||
|
||||
## Alternative if you can't use mirrored mode
|
||||
|
||||
Windows 10 / old WSL can't do mirrored mode. Options: run the **backend natively on Windows**
|
||||
(shares the LAN), or use **unicast by IP** instead of broadcast discovery (target the controller's
|
||||
known IP — the driver supports an explicit host). On the real **appliance** (a dedicated hardened
|
||||
Linux box, [[disk-os-hardening]]) none of this applies — it's bare-metal on the device VLAN
|
||||
([[network-isolation]]).
|
||||
@@ -1,17 +1,22 @@
|
||||
---
|
||||
type: decision
|
||||
tags: [parking, hardware, access-control, blocker, open]
|
||||
tags: [parking, hardware, access-control, resolved]
|
||||
sources: [parking-system-architecture]
|
||||
updated: 2026-06-15
|
||||
status: open
|
||||
status: settled
|
||||
---
|
||||
|
||||
# Blocker: Push-Button → Auto-Open Defeats the Ticket-First Entry Flow
|
||||
# Push-Button → Auto-Open: the Ticket-First Entry Blocker (RESOLVED)
|
||||
|
||||
> **Procurement-blocking finding (2026-06-15), from on-hardware testing.** The UHPPOTE and
|
||||
> ZKTeco access controllers **on hand** cannot, as wired/configured, deliver the required entry
|
||||
> flow. This blocks the entry lane and needs a hardware/wiring resolution before that lane ships.
|
||||
> Work paused here to focus on the business side. See [[entry-exit-readers]], [[trust-boundary]].
|
||||
> **✅ RESOLVED (2026-06-15) by the [[dingtian-relay]] controller.** Its inputs are decoupled from
|
||||
> its relays (`input_link_relay` configurable off — done & verified on hardware), so a button on an
|
||||
> input reports to the host **without** firing a relay. Host-in-the-loop entry
|
||||
> (`button → host → ticket → host opens relay`) now works. The original blocker (below) stands as
|
||||
> the record of why the UHPPOTE/ZKTeco units couldn't do it.
|
||||
>
|
||||
> **Original procurement-blocking finding (2026-06-15), from on-hardware testing:** the UHPPOTE and
|
||||
> ZKTeco controllers on hand could not, as wired/configured, deliver the required entry flow.
|
||||
> See [[entry-exit-readers]], [[trust-boundary]].
|
||||
|
||||
## The required flow
|
||||
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
---
|
||||
type: decision
|
||||
tags: [parking, direction, roadmap]
|
||||
sources: []
|
||||
updated: 2026-06-15
|
||||
status: open
|
||||
---
|
||||
|
||||
# Project Direction: Toward Fully Autonomous (Unmanned)
|
||||
|
||||
> Stated goal (2026-06-15): the system will evolve to **fully automatic operation — no human
|
||||
> operator, no booth at all**. Recorded because "unmanned" is an architectural force that shapes
|
||||
> several existing decisions, not just a feature.
|
||||
|
||||
## What "unmanned" changes
|
||||
|
||||
- **Threat model shift.** The original primary adversary was *"the legitimate operator at the
|
||||
booth"* ([[threat-model]]). Remove the operator and that specific fraud vector (take cash → void
|
||||
the record) largely disappears — but it's replaced by **unattended-machine threats**: tailgating,
|
||||
plate spoofing/obscuring, physical tampering with a box nobody is watching, and forced entry.
|
||||
The [[append-only-event-chain]] + [[reconciliation]] controls still apply; the emphasis moves
|
||||
from "catch the cashier" to "trust the automated record + detect tampering."
|
||||
- **Host-in-the-loop entry becomes mandatory, not optional.** With no person to hand over a ticket
|
||||
or wave a car through, the machine must own the whole flow: detect arrival → issue ticket / read
|
||||
plate → open. This is exactly why the [[access-controller-button-flow]] blocker matters and why
|
||||
a controller whose input does **not** auto-fire the relay (see [[dingtian-relay]]) is required.
|
||||
- **Reliability / fail-state get more critical** ([[fail-state-safety]]). No operator to recover a
|
||||
stuck barrier or a trapped car ⇒ watchdogs, **exit-fails-open**, and hardware manual override
|
||||
stop being nice-to-haves. Unattended uptime is a hard requirement.
|
||||
- **Payment goes unmanned.** Pay-station / pay-on-foot or in-lane unmanned terminal rather than a
|
||||
booth P2PE + cash drawer — sharpens [[open-questions]] #3 toward the unmanned option (PCI scope
|
||||
still kept out of the app via a certified terminal).
|
||||
- **Identity leans on automation.** Plate recognition ([[lpr-camera]]) and permit reads become the
|
||||
primary identity sources, since there's no one to issue/inspect a paper ticket by hand.
|
||||
|
||||
## Near-term stance
|
||||
|
||||
Build for the unmanned target but don't over-engineer ahead of it. Current concrete step: the
|
||||
**[[dingtian-relay]]** controller over **HTTP** (device pushes input events to the host; host
|
||||
commands relays) — see [[dingtian-vs-mqtt]] for why HTTP over a message bus for now.
|
||||
|
||||
## Open
|
||||
|
||||
Lane topology, payment subsystem, and reconciliation channel ([[open-questions]]) should all be
|
||||
(re)evaluated through the **unmanned** lens before procurement.
|
||||
@@ -0,0 +1,46 @@
|
||||
---
|
||||
type: decision
|
||||
tags: [parking, decision, devices, transport]
|
||||
sources: []
|
||||
updated: 2026-06-15
|
||||
status: settled
|
||||
---
|
||||
|
||||
# Transport for the Relay Controller: HTTP/UDP now, MQTT parked
|
||||
|
||||
**Decision (2026-06-15): use direct HTTP + UDP for the [[dingtian-relay]] controller now. MQTT is
|
||||
deliberately skipped, but kept on the radar** for when the system scales.
|
||||
|
||||
## Options the device supports
|
||||
|
||||
The Dingtian relay board speaks several protocols: Dingtian string (UDP/TCP), Dingtian binary
|
||||
(UDP, optional multicast/password), **HTTP CGI**, **HTTP input-link push** (`input_link_url`),
|
||||
**Modbus** (RTU/TCP/ASCII), and **MQTT**.
|
||||
|
||||
## Why not MQTT (yet)
|
||||
|
||||
- **A broker is new infrastructure** on a deliberately **single-purpose hardened appliance**
|
||||
([[disk-os-hardening]]) — another service to install, secure, supervise, and keep alive.
|
||||
- **Extra failure mode on the critical path.** Today host→UDP→relay. MQTT inserts a broker on both
|
||||
control and event paths; if it stalls, the lane stalls — and there are 3 processes to debug, not 2.
|
||||
- **Doesn't fit [[offline-first]] for this scale.** MQTT earns its keep with *many* devices/consumers
|
||||
and intermittent links. Here it's **one host + a few devices on one isolated LAN, metres apart** —
|
||||
request/response control + a single input event, no fleet.
|
||||
- **The device's MQTT input publish is periodic** ("default every 30 s"), so it's not even a clean
|
||||
on-press event without relying on unverified on-change behaviour.
|
||||
|
||||
## Why HTTP/UDP fits
|
||||
|
||||
- **Relay control:** direct **UDP string protocol** (port 60001) — `11`=relay1 on, `21`=off,
|
||||
`T1`=toggle, `11*`=jog/pulse. No deps, no broker.
|
||||
- **Input/button events:** the device's **`input_link_url`** can **HTTP POST to the host backend
|
||||
when an input fires** — real push, device calls our existing Fastify server directly, no broker.
|
||||
(Polling `00` status over UDP every ~50 ms is the self-contained fallback.)
|
||||
- Fewest moving parts; matches the local same-origin model already in use.
|
||||
|
||||
## When to revisit MQTT
|
||||
|
||||
If the system grows to **many lanes / many controllers**, or multiple subsystems (LPR, payment,
|
||||
signage) all need to share events, a broker becomes a worthwhile central event bus. That aligns
|
||||
with the [[autonomous-direction|unmanned]] roadmap at multi-lane scale — re-evaluate then. Until
|
||||
then, direct HTTP/UDP wins on simplicity and reliability.
|
||||
@@ -0,0 +1,57 @@
|
||||
---
|
||||
type: decision
|
||||
tags: [parking, decisions, integrity, devices, schema]
|
||||
sources: []
|
||||
updated: 2026-06-15
|
||||
status: open
|
||||
---
|
||||
|
||||
# Decision: Split the signed business ledger from device telemetry
|
||||
|
||||
Taken 2026-06-15, at the start of the business-layer schema work.
|
||||
|
||||
## The problem
|
||||
|
||||
The existing `events` table (signed, hash-chained — [[append-only-event-chain]]) had grown to carry
|
||||
**two unrelated concerns**: the financial/accountability ledger *and* raw device telemetry (button
|
||||
pushes recorded as `input_received`). They have opposite requirements — the ledger must be small,
|
||||
signed, and reconciled; telemetry is high-volume, churny, and disposable.
|
||||
|
||||
## Decision — two tables
|
||||
|
||||
- **`ledger_events`** — the signed, hash-chained, [[atecc608]]-signed **business ledger** (rename of
|
||||
`events`). Holds only business/accountability facts: `vehicle_entry`, `vehicle_exit`, `payment`,
|
||||
`void`, `shift_z_report`, and the witness-grade `barrier_open_command` / `barrier_open_observed` /
|
||||
`anomaly`. [[reconciliation]] runs against this; sessions/[[tariff]]/occupancy are projections of
|
||||
it.
|
||||
- **`device_events`** — **unsigned** operational telemetry (see [[device-events]]): relay fired,
|
||||
printer paper-out, camera offline, reader read, raw input edges. May rotate/prune. Never signed,
|
||||
never reconciled.
|
||||
|
||||
A raw button press is **telemetry** → `device_events`. The entry flow then mints a **signed
|
||||
`vehicle_entry`** in the ledger once a ticket prints + the barrier is commanded. So
|
||||
`input_received`-as-a-signed-event is **dropped** (it was transitional).
|
||||
|
||||
## Why
|
||||
|
||||
- Keeps the **signed ledger small and high-value** — fewer rows to sign, hash, verify, reconcile,
|
||||
and export; signal isn't drowned in device noise.
|
||||
- Right **durability semantics per stream**: the ledger is precious + append-only forever; telemetry
|
||||
can age out.
|
||||
- Clean separation matches the [[device-adapter-pattern]] philosophy — device chatter stays on the
|
||||
device side of the boundary.
|
||||
|
||||
## Consequences / migration (no production data yet)
|
||||
|
||||
- No `.sqlite` with real chain data exists, so renaming + restructuring is safe now (no signatures
|
||||
to invalidate). This is the moment to do it.
|
||||
- Code: rename `events` → `ledger_events`; `EventLog`/`canonicalize`/`verifyChain` and the
|
||||
`/api/events` routes follow the rename; add an unsigned `device_events` writer; move the Dingtian
|
||||
input-push handler to emit `device_events` (+ the entry flow signs `vehicle_entry`).
|
||||
- `ParkingEventType` in `packages/shared` splits into ledger types vs. a device-event type set.
|
||||
|
||||
## Open
|
||||
|
||||
- `device_events` retention/rotation policy.
|
||||
- Which device facts (if any) are witness-grade enough to *also* warrant a signed ledger entry
|
||||
(e.g. `barrier_open_observed` from a loop sensor) — see [[append-only-event-chain]] witness gap.
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user