Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f5fd61984a | |||
| 7db5cfa0e4 | |||
| add5fc0166 | |||
| 39d4bac419 |
@@ -0,0 +1,147 @@
|
|||||||
|
import { createHash, randomUUID } from "node:crypto";
|
||||||
|
import { desc, events, type Db, type EventRow } from "@parking/db";
|
||||||
|
import type { Direction, IdentitySource, ParkingEventType, 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: ParkingEventType;
|
||||||
|
readonly lane: number;
|
||||||
|
readonly direction?: Direction | null;
|
||||||
|
readonly source?: IdentitySource | null;
|
||||||
|
readonly identity?: string | 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;
|
||||||
|
lane: number;
|
||||||
|
source: string | null;
|
||||||
|
identity: string | null;
|
||||||
|
occurredAt: string;
|
||||||
|
prevHash: string | null;
|
||||||
|
}): string {
|
||||||
|
return JSON.stringify([
|
||||||
|
e.index,
|
||||||
|
e.type,
|
||||||
|
e.direction ?? null,
|
||||||
|
e.lane,
|
||||||
|
e.source ?? null,
|
||||||
|
e.identity ?? null,
|
||||||
|
e.occurredAt,
|
||||||
|
e.prevHash ?? null,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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<EventRow> {
|
||||||
|
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): EventRow {
|
||||||
|
const prev = this.#db
|
||||||
|
.select()
|
||||||
|
.from(events)
|
||||||
|
.orderBy(desc(events.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 canonical = canonicalize({
|
||||||
|
index,
|
||||||
|
type: input.type,
|
||||||
|
direction: input.direction ?? null,
|
||||||
|
lane: input.lane,
|
||||||
|
source: input.source ?? null,
|
||||||
|
identity: input.identity ?? null,
|
||||||
|
occurredAt,
|
||||||
|
prevHash,
|
||||||
|
});
|
||||||
|
|
||||||
|
const row = {
|
||||||
|
id: randomUUID(),
|
||||||
|
index,
|
||||||
|
type: input.type,
|
||||||
|
direction: input.direction ?? null,
|
||||||
|
lane: input.lane,
|
||||||
|
source: input.source ?? null,
|
||||||
|
identity: input.identity ?? null,
|
||||||
|
occurredAt,
|
||||||
|
prevHash,
|
||||||
|
signature: this.#signer.sign(canonical),
|
||||||
|
};
|
||||||
|
|
||||||
|
this.#db.insert(events).values(row).run();
|
||||||
|
return row as EventRow;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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(events).orderBy(events.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,38 @@
|
|||||||
|
import type { FastifyInstance } from "fastify";
|
||||||
|
import { desc, events, 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(events).orderBy(desc(events.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(),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -32,6 +32,22 @@ interface TestBody {
|
|||||||
config: Record<string, string | number | boolean>;
|
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> {
|
export async function setupRoutes(app: FastifyInstance, db: Db): Promise<void> {
|
||||||
registerBuiltinDrivers();
|
registerBuiltinDrivers();
|
||||||
setDeviceLogSink((line) => app.log.info(line));
|
setDeviceLogSink((line) => app.log.info(line));
|
||||||
@@ -79,13 +95,15 @@ 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(
|
app.get(
|
||||||
"/api/setup/state",
|
"/api/setup/state",
|
||||||
{ preHandler: adminGuard },
|
{ preHandler: adminGuard },
|
||||||
async () => {
|
async () => {
|
||||||
const state = await db.select().from(setupState).where(eq(setupState.id, 1)).get();
|
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(laneDevices).all();
|
||||||
|
const assignments = rows.map((r) => ({ ...r, config: redactSecrets(r.config) }));
|
||||||
return { completedAt: state?.completedAt ?? null, assignments };
|
return { completedAt: state?.completedAt ?? null, assignments };
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -144,6 +162,18 @@ export async function setupRoutes(app: FastifyInstance, db: Db): Promise<void> {
|
|||||||
|
|
||||||
const id = randomUUID();
|
const id = randomUUID();
|
||||||
const fullConfig: Record<string, unknown> = { ...config };
|
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;
|
let device;
|
||||||
try {
|
try {
|
||||||
@@ -171,8 +201,14 @@ export async function setupRoutes(app: FastifyInstance, db: Db): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (isHardenable(device)) {
|
if (isHardenable(device)) {
|
||||||
const { secrets } = await device.harden();
|
const { secrets, warnings } = await device.harden();
|
||||||
Object.assign(fullConfig, secrets); // e.g. relayPassword
|
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)) {
|
if (hasPushConfig(device)) {
|
||||||
@@ -215,9 +251,38 @@ export async function setupRoutes(app: FastifyInstance, db: Db): Promise<void> {
|
|||||||
enabled: true,
|
enabled: true,
|
||||||
};
|
};
|
||||||
await db.insert(laneDevices).values(row);
|
await db.insert(laneDevices).values(row);
|
||||||
// Don't echo device secrets back (push Digest password, web-UI login).
|
// Don't echo device secrets back (push Digest password, web-UI login, …).
|
||||||
const { pushPassword: _pw, webPassword: _wp, ...safeConfig } = fullConfig;
|
return reply.code(201).send({
|
||||||
return reply.code(201).send({ ...row, config: safeConfig });
|
...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(laneDevices)
|
||||||
|
.where(eq(laneDevices.id, req.params.id))
|
||||||
|
.get();
|
||||||
|
if (!existing) return reply.code(404).send({ error: "no such device assignment" });
|
||||||
|
await db.delete(laneDevices).where(eq(laneDevices.id, req.params.id));
|
||||||
|
app.log.info(`unassigned device ${req.params.id} (${existing.category}/${existing.driverId}, lane ${existing.lane})`);
|
||||||
|
return reply.code(204).send();
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -3,9 +3,13 @@ import jwt from "@fastify/jwt";
|
|||||||
import Fastify, { type FastifyInstance } from "fastify";
|
import Fastify, { type FastifyInstance } from "fastify";
|
||||||
import { createDb, type Db } from "@parking/db";
|
import { createDb, type Db } from "@parking/db";
|
||||||
import { TOKEN_COOKIE, requireJwtSecret } from "./auth.js";
|
import { TOKEN_COOKIE, requireJwtSecret } from "./auth.js";
|
||||||
|
import { deviceEvents } from "./device-events.js";
|
||||||
|
import { EventLog } from "./event-log.js";
|
||||||
import { PrinterMonitor } from "./printer-monitor.js";
|
import { PrinterMonitor } from "./printer-monitor.js";
|
||||||
|
import { buildSigner } from "./signer.js";
|
||||||
import { authRoutes } from "./routes/auth.js";
|
import { authRoutes } from "./routes/auth.js";
|
||||||
import { deviceRoutes } from "./routes/devices.js";
|
import { deviceRoutes } from "./routes/devices.js";
|
||||||
|
import { eventRoutes } from "./routes/events.js";
|
||||||
import { printerRoutes } from "./routes/printers.js";
|
import { printerRoutes } from "./routes/printers.js";
|
||||||
import { setupRoutes } from "./routes/setup.js";
|
import { setupRoutes } from "./routes/setup.js";
|
||||||
|
|
||||||
@@ -59,7 +63,27 @@ export async function buildServer(opts: BuildOptions = {}): Promise<FastifyInsta
|
|||||||
app.addHook("onReady", async () => printerMonitor.start());
|
app.addHook("onReady", async () => printerMonitor.start());
|
||||||
app.addHook("onClose", async () => printerMonitor.stop());
|
app.addHook("onClose", async () => printerMonitor.stop());
|
||||||
|
|
||||||
// TODO: entry flow (input event → signed event → print → relay), event-log routes.
|
// Append-only signed event log. Subscribe device pushes (e.g. Dingtian button
|
||||||
|
// presses) into the hash-chained, signed `events` table — the anti-fraud audit
|
||||||
|
// trail. The device is NOT trusted; the host record is the source of truth, and
|
||||||
|
// a relay open with no matching signed event is itself the anomaly. We record
|
||||||
|
// the raw input faithfully as `input_received` (not yet a `vehicle_entry` — that
|
||||||
|
// comes with the full entry flow). See wiki/concepts/append-only-event-chain.md.
|
||||||
|
const eventLog = new EventLog(db, buildSigner(app.log));
|
||||||
|
await eventRoutes(app, db, eventLog);
|
||||||
|
const unsubscribeInput = deviceEvents.onInput((e) => {
|
||||||
|
eventLog
|
||||||
|
.append({
|
||||||
|
type: "input_received",
|
||||||
|
lane: 0, // lane mapping is a TODO — device->lane lookup arrives with setup/lane wiring
|
||||||
|
identity: `${e.driverId}:${e.deviceId} input:${e.input}/${e.edge}`,
|
||||||
|
occurredAt: e.at,
|
||||||
|
})
|
||||||
|
.catch((err) => app.log.error(`event-log append failed: ${(err as Error).message}`));
|
||||||
|
});
|
||||||
|
app.addHook("onClose", async () => unsubscribeInput());
|
||||||
|
|
||||||
|
// TODO: entry flow (input event → signed event → print → relay); map device→lane.
|
||||||
|
|
||||||
return app;
|
return app;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
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;
|
||||||
|
|
||||||
|
constructor(secret: string, keyId = "sw-hmac-v1") {
|
||||||
|
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.",
|
||||||
|
);
|
||||||
|
}
|
||||||
+212
-39
@@ -1,10 +1,13 @@
|
|||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect, useCallback } from "react";
|
||||||
import {
|
import {
|
||||||
assignDevice,
|
assignDevice,
|
||||||
discoverDevices,
|
discoverDevices,
|
||||||
fetchBackendIps,
|
fetchBackendIps,
|
||||||
fetchCatalog,
|
fetchCatalog,
|
||||||
|
fetchState,
|
||||||
testDevice,
|
testDevice,
|
||||||
|
unassignDevice,
|
||||||
|
type Assignment,
|
||||||
type BackendIpCandidate,
|
type BackendIpCandidate,
|
||||||
type Catalog,
|
type Catalog,
|
||||||
type CatalogEntry,
|
type CatalogEntry,
|
||||||
@@ -13,32 +16,39 @@ import {
|
|||||||
type TestResult,
|
type TestResult,
|
||||||
} from "./api.js";
|
} from "./api.js";
|
||||||
|
|
||||||
// First-run setup wizard (scaffold). The admin picks a device per category for a
|
// First-run setup wizard (scaffold). The admin assigns devices per lane from the
|
||||||
// lane from the driver catalog and fills in its connection config. Drivers that
|
// driver catalog. The data model is multi-instance — one lane_devices row per
|
||||||
// support LAN discovery (e.g. UHPPOTE) get a "Scan" button that lists found
|
// instance — so EVERY category supports more than one device: each section lists
|
||||||
// devices; selecting one auto-fills the config. Auth is via the admin's session
|
// the already-assigned instances (with Remove) and an "Add" form. Drivers that
|
||||||
// cookie (the SPA only renders this for admins). See wiki/concepts/first-run-setup.md
|
// support LAN discovery get a "Scan" button. Auth is via the admin's session
|
||||||
// and device-discovery.md.
|
// cookie. See wiki/concepts/first-run-setup.md and device-discovery.md.
|
||||||
|
|
||||||
const CATEGORIES: { key: DeviceCategory; title: string }[] = [
|
const CATEGORIES: { key: DeviceCategory; title: string; noun: string }[] = [
|
||||||
{ key: "access", title: "Access controller" },
|
{ key: "access", title: "Access controllers", noun: "access controller" },
|
||||||
{ key: "reader", title: "Reader" },
|
{ key: "reader", title: "Readers", noun: "reader" },
|
||||||
{ key: "camera", title: "Camera (entry/exit snapshot)" },
|
{ key: "camera", title: "Cameras (entry/exit snapshot)", noun: "camera" },
|
||||||
{ key: "printer", title: "Printer" },
|
{ key: "printer", title: "Printers", noun: "printer" },
|
||||||
];
|
];
|
||||||
|
|
||||||
export function SetupWizard() {
|
export function SetupWizard() {
|
||||||
const [catalog, setCatalog] = useState<Catalog | null>(null);
|
const [catalog, setCatalog] = useState<Catalog | null>(null);
|
||||||
|
const [assignments, setAssignments] = useState<Assignment[] | null>(null);
|
||||||
const [lane, setLane] = useState(1);
|
const [lane, setLane] = useState(1);
|
||||||
const [picked, setPicked] = useState<Partial<Record<DeviceCategory, string>>>({});
|
|
||||||
const [error, setError] = useState<string | 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(() => {
|
useEffect(() => {
|
||||||
fetchCatalog().then(setCatalog).catch((e: Error) => setError(e.message));
|
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 (error) return <p style={{ color: "crimson" }}>Failed to load setup: {error}</p>;
|
||||||
if (!catalog) return <p>Loading device catalog…</p>;
|
if (!catalog || !assignments) return <p>Loading device catalog…</p>;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section>
|
<section>
|
||||||
@@ -54,41 +64,180 @@ export function SetupWizard() {
|
|||||||
style={{ width: "4rem" }}
|
style={{ width: "4rem" }}
|
||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
|
<span style={{ color: "#666", fontSize: "0.85em" }}>
|
||||||
|
Devices are added per lane. Switch lanes to configure another.
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{CATEGORIES.map(({ key, title }) => (
|
{CATEGORIES.map(({ key, title, noun }) => (
|
||||||
<CategoryPicker
|
<CategorySection
|
||||||
key={key}
|
key={key}
|
||||||
lane={lane}
|
lane={lane}
|
||||||
category={key}
|
category={key}
|
||||||
title={title}
|
title={title}
|
||||||
|
noun={noun}
|
||||||
entries={catalog[key]}
|
entries={catalog[key]}
|
||||||
discoverableIds={catalog.discoverable}
|
discoverableIds={catalog.discoverable}
|
||||||
selectedId={picked[key]}
|
assignments={assignments.filter((a) => a.category === key && a.lane === lane)}
|
||||||
onSelect={(id) => setPicked((p) => ({ ...p, [key]: id }))}
|
onChanged={reloadState}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function CategoryPicker({
|
function CategorySection({
|
||||||
lane,
|
lane,
|
||||||
category,
|
category,
|
||||||
title,
|
title,
|
||||||
|
noun,
|
||||||
entries,
|
entries,
|
||||||
discoverableIds,
|
discoverableIds,
|
||||||
selectedId,
|
assignments,
|
||||||
onSelect,
|
onChanged,
|
||||||
}: {
|
}: {
|
||||||
lane: number;
|
lane: number;
|
||||||
category: DeviceCategory;
|
category: DeviceCategory;
|
||||||
title: string;
|
title: string;
|
||||||
|
noun: string;
|
||||||
entries: CatalogEntry[];
|
entries: CatalogEntry[];
|
||||||
discoverableIds: string[];
|
discoverableIds: string[];
|
||||||
selectedId: string | undefined;
|
assignments: Assignment[];
|
||||||
onSelect: (id: string) => void;
|
onChanged: () => Promise<void> | void;
|
||||||
}) {
|
}) {
|
||||||
|
// Show the add-form automatically when nothing is assigned yet; otherwise it's
|
||||||
|
// collapsed behind "Add another" so the list stays the focus.
|
||||||
|
const [adding, setAdding] = useState(false);
|
||||||
|
// Warnings from the most recent save (e.g. "string protocol could not be
|
||||||
|
// disabled — finish in the device web UI"). Persist after the form closes.
|
||||||
|
const [warnings, setWarnings] = useState<string[]>([]);
|
||||||
|
const showForm = adding || assignments.length === 0;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<fieldset style={{ marginTop: "1rem" }}>
|
||||||
|
<legend>
|
||||||
|
{title} <span style={{ color: "#888", fontWeight: 400 }}>· lane {lane}</span>
|
||||||
|
</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} onChanged={onChanged} />
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{showForm ? (
|
||||||
|
<DeviceForm
|
||||||
|
lane={lane}
|
||||||
|
category={category}
|
||||||
|
entries={entries}
|
||||||
|
discoverableIds={discoverableIds}
|
||||||
|
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,
|
||||||
|
onChanged,
|
||||||
|
}: {
|
||||||
|
assignment: Assignment;
|
||||||
|
onChanged: () => Promise<void> | void;
|
||||||
|
}) {
|
||||||
|
const [removing, setRemoving] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// A short, human summary of the instance: role (if any) + host.
|
||||||
|
const cfg = assignment.config;
|
||||||
|
const role = typeof cfg.role === "string" ? cfg.role : null;
|
||||||
|
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>
|
||||||
|
{role && <span style={{ color: "#0369a1" }}>{role}</span>}
|
||||||
|
{host && <span style={{ color: "#666" }}>{host}</span>}
|
||||||
|
{!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>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function DeviceForm({
|
||||||
|
lane,
|
||||||
|
category,
|
||||||
|
entries,
|
||||||
|
discoverableIds,
|
||||||
|
onSaved,
|
||||||
|
onCancel,
|
||||||
|
}: {
|
||||||
|
lane: number;
|
||||||
|
category: DeviceCategory;
|
||||||
|
entries: CatalogEntry[];
|
||||||
|
discoverableIds: string[];
|
||||||
|
onSaved: (warnings: string[]) => Promise<void> | void;
|
||||||
|
onCancel?: () => void;
|
||||||
|
}) {
|
||||||
|
const [selectedId, setSelectedId] = useState<string>("");
|
||||||
const selected = entries.find((e) => e.id === selectedId);
|
const selected = entries.find((e) => e.id === selectedId);
|
||||||
const canDiscover = selected != null && discoverableIds.includes(selected.id);
|
const canDiscover = selected != null && discoverableIds.includes(selected.id);
|
||||||
|
|
||||||
@@ -98,7 +247,6 @@ function CategoryPicker({
|
|||||||
const [testing, setTesting] = useState(false);
|
const [testing, setTesting] = useState(false);
|
||||||
const [testError, setTestError] = useState<string | null>(null);
|
const [testError, setTestError] = useState<string | null>(null);
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
const [saved, setSaved] = useState(false);
|
|
||||||
const [saveError, setSaveError] = useState<string | null>(null);
|
const [saveError, setSaveError] = useState<string | null>(null);
|
||||||
const [found, setFound] = useState<DiscoveredDevice[] | null>(null);
|
const [found, setFound] = useState<DiscoveredDevice[] | null>(null);
|
||||||
const [scanning, setScanning] = useState(false);
|
const [scanning, setScanning] = useState(false);
|
||||||
@@ -124,8 +272,6 @@ function CategoryPicker({
|
|||||||
.then(({ candidates }) => {
|
.then(({ candidates }) => {
|
||||||
if (!live) return;
|
if (!live) return;
|
||||||
setBackendIps(candidates);
|
setBackendIps(candidates);
|
||||||
// Pre-fill with the on-subnet auto-pick (the first candidate, since the
|
|
||||||
// server sorts on-subnet first), unless the admin already chose one.
|
|
||||||
setBackendIp((cur) => cur || candidates.find((c) => c.onDeviceSubnet)?.ip || "");
|
setBackendIp((cur) => cur || candidates.find((c) => c.onDeviceSubnet)?.ip || "");
|
||||||
})
|
})
|
||||||
.catch(() => {
|
.catch(() => {
|
||||||
@@ -137,6 +283,13 @@ function CategoryPicker({
|
|||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [testedHost]);
|
}, [testedHost]);
|
||||||
|
|
||||||
|
function selectDriver(id: string) {
|
||||||
|
setSelectedId(id);
|
||||||
|
setConfig({});
|
||||||
|
setFound(null);
|
||||||
|
resetStatus();
|
||||||
|
}
|
||||||
|
|
||||||
async function scan() {
|
async function scan() {
|
||||||
if (!selected) return;
|
if (!selected) return;
|
||||||
setScanning(true);
|
setScanning(true);
|
||||||
@@ -165,11 +318,10 @@ function CategoryPicker({
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Editing config invalidates a prior test/save.
|
// Editing config invalidates a prior test.
|
||||||
function resetStatus() {
|
function resetStatus() {
|
||||||
setTested(null);
|
setTested(null);
|
||||||
setTestError(null);
|
setTestError(null);
|
||||||
setSaved(false);
|
|
||||||
setSaveError(null);
|
setSaveError(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -192,14 +344,15 @@ function CategoryPicker({
|
|||||||
setSaving(true);
|
setSaving(true);
|
||||||
setSaveError(null);
|
setSaveError(null);
|
||||||
try {
|
try {
|
||||||
await assignDevice({
|
const result = await assignDevice({
|
||||||
lane,
|
lane,
|
||||||
category,
|
category,
|
||||||
driverId: selected.id,
|
driverId: selected.id,
|
||||||
config: mergedConfig(),
|
config: mergedConfig(),
|
||||||
...(backendIp ? { backendIp } : {}),
|
...(backendIp ? { backendIp } : {}),
|
||||||
});
|
});
|
||||||
setSaved(true);
|
// Hand warnings to the parent so they persist after this form unmounts.
|
||||||
|
await onSaved(result.warnings ?? []);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setSaveError((e as Error).message);
|
setSaveError((e as Error).message);
|
||||||
} finally {
|
} finally {
|
||||||
@@ -208,12 +361,11 @@ function CategoryPicker({
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<fieldset style={{ marginTop: "1rem" }}>
|
<div style={{ padding: "0.5rem", background: "#fafafa", borderRadius: 6 }}>
|
||||||
<legend>{title}</legend>
|
|
||||||
{entries.length === 0 ? (
|
{entries.length === 0 ? (
|
||||||
<em>No drivers registered.</em>
|
<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>
|
<option value="" disabled>
|
||||||
Choose a device…
|
Choose a device…
|
||||||
</option>
|
</option>
|
||||||
@@ -258,6 +410,22 @@ function CategoryPicker({
|
|||||||
<label>
|
<label>
|
||||||
{f.label}
|
{f.label}
|
||||||
{f.required ? " *" : ""}{" "}
|
{f.required ? " *" : ""}{" "}
|
||||||
|
{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
|
<input
|
||||||
type={f.type === "secret" ? "password" : f.type === "number" || f.type === "port" ? "number" : "text"}
|
type={f.type === "secret" ? "password" : f.type === "number" || f.type === "port" ? "number" : "text"}
|
||||||
value={config[f.key] ?? (f.default as string | number | undefined) ?? ""}
|
value={config[f.key] ?? (f.default as string | number | undefined) ?? ""}
|
||||||
@@ -268,6 +436,7 @@ function CategoryPicker({
|
|||||||
resetStatus();
|
resetStatus();
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
)}
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
@@ -277,9 +446,14 @@ function CategoryPicker({
|
|||||||
<button type="button" onClick={test} disabled={testing}>
|
<button type="button" onClick={test} disabled={testing}>
|
||||||
{testing ? "Testing…" : "Test connection"}
|
{testing ? "Testing…" : "Test connection"}
|
||||||
</button>
|
</button>
|
||||||
<button type="button" onClick={save} disabled={saving || saved}>
|
<button type="button" onClick={save} disabled={saving}>
|
||||||
{saving ? "Saving…" : saved ? "Saved ✓" : "Save & configure"}
|
{saving ? "Saving…" : "Save & configure"}
|
||||||
</button>
|
</button>
|
||||||
|
{onCancel && (
|
||||||
|
<button type="button" onClick={onCancel} disabled={saving}>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{testError && <p style={{ color: "crimson", margin: "0.5rem 0 0" }}>Test failed: {testError}</p>}
|
{testError && <p style={{ color: "crimson", margin: "0.5rem 0 0" }}>Test failed: {testError}</p>}
|
||||||
@@ -332,10 +506,9 @@ function CategoryPicker({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{saveError && <p style={{ color: "crimson", margin: "0.5rem 0 0" }}>Save failed: {saveError}</p>}
|
{saveError && <p style={{ color: "crimson", margin: "0.5rem 0 0" }}>Save failed: {saveError}</p>}
|
||||||
{saved && <p style={{ color: "#16a34a", margin: "0.5rem 0 0" }}>Saved and configured ✓</p>}
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</fieldset>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+33
-1
@@ -160,6 +160,38 @@ export interface AssignBody {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Save + configure the device (preconditions, push setup), then persist. */
|
/** Save + configure the device (preconditions, push setup), then persist. */
|
||||||
export function assignDevice(body: AssignBody): Promise<{ id: string }> {
|
export function assignDevice(body: AssignBody): Promise<AssignResult> {
|
||||||
return apiFetch("/api/setup/assign", { method: "POST", body: JSON.stringify(body) });
|
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;
|
||||||
|
lane: number;
|
||||||
|
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" });
|
||||||
|
}
|
||||||
|
|||||||
@@ -34,59 +34,37 @@ import { hostField, portField, stubLog } from "./common.js";
|
|||||||
// (input_link_relay). That must be DISABLED on the device for ticket-first
|
// (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.
|
// entry, else the button opens the barrier before the host can act.
|
||||||
|
|
||||||
/** Send one UDP datagram and (optionally) await a single reply. */
|
// (The string-protocol UDP helper was removed: harden() now disables the
|
||||||
function udpRequest(
|
// password-less string protocol entirely, and status reads use the
|
||||||
host: string,
|
// authenticated binary read — see #status() / readStatusFrame.)
|
||||||
port: number,
|
|
||||||
payload: string,
|
|
||||||
timeoutMs: number,
|
|
||||||
expectReply: boolean,
|
|
||||||
): Promise<string | null> {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
const sock = createSocket("udp4");
|
|
||||||
let settled = false;
|
|
||||||
const done = (err: Error | null, val: string | null) => {
|
|
||||||
if (settled) return;
|
|
||||||
settled = true;
|
|
||||||
clearTimeout(timer);
|
|
||||||
sock.close();
|
|
||||||
err ? reject(err) : resolve(val);
|
|
||||||
};
|
|
||||||
const timer = setTimeout(
|
|
||||||
() => done(expectReply ? new Error("timeout") : null, null),
|
|
||||||
timeoutMs,
|
|
||||||
);
|
|
||||||
sock.on("error", (e) => done(e, null));
|
|
||||||
sock.on("message", (m) => done(null, m.toString()));
|
|
||||||
sock.bind(() => {
|
|
||||||
sock.send(Buffer.from(payload), port, host, (e) => {
|
|
||||||
if (e) done(e, null);
|
|
||||||
else if (!expectReply) done(null, null);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Send a Dingtian *binary* protocol frame (UDP, default port 60000) and await
|
* Send a Dingtian *binary* protocol frame (UDP, default port 60000) and await
|
||||||
* the reply. Used for relay control because — unlike the string protocol — the
|
* the reply. Used for ALL relay traffic — control AND status read — because,
|
||||||
* binary protocol supports a password (`relay_pw`), so an attacker on a flat
|
* unlike the string protocol, the binary protocol carries a password (`relay_pw`).
|
||||||
* network can't fire a relay without it. Frame verified on hardware:
|
* 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 AA <session> <relayCmd> <pwLo> <pwHi> <data...>
|
||||||
*
|
*
|
||||||
* FF = command "set relay"
|
* FF = command "set relay"
|
||||||
* AA = result xor (0x00 ^ 0xAA, pc→device)
|
* AA = result xor (0x00 ^ 0xAA, pc→device)
|
||||||
* session = echoed back
|
* session = echoed back
|
||||||
* relayCmd = 1 write, 3 jogging, …
|
* relayCmd = 0 read status, 1 write, 3 jogging, …
|
||||||
* pwLo,pwHi = relay password, 16-bit LSB-first (0 = none)
|
* pwLo,pwHi = relay password, 16-bit LSB-first (0 = none)
|
||||||
* data = command-specific
|
* 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(
|
function binaryUdp(
|
||||||
host: string,
|
host: string,
|
||||||
port: number,
|
port: number,
|
||||||
frame: Buffer,
|
frame: Buffer,
|
||||||
timeoutMs: number,
|
timeoutMs: number,
|
||||||
|
localAddress?: string,
|
||||||
): Promise<Buffer> {
|
): Promise<Buffer> {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const sock = createSocket("udp4");
|
const sock = createSocket("udp4");
|
||||||
@@ -101,15 +79,33 @@ function binaryUdp(
|
|||||||
const timer = setTimeout(() => done(new Error("timeout"), null), timeoutMs);
|
const timer = setTimeout(() => done(new Error("timeout"), null), timeoutMs);
|
||||||
sock.on("error", (e) => done(e, null));
|
sock.on("error", (e) => done(e, null));
|
||||||
sock.on("message", (m) => done(null, m));
|
sock.on("message", (m) => done(null, m));
|
||||||
sock.bind(() => {
|
// 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) => {
|
sock.send(frame, port, host, (e) => {
|
||||||
if (e) done(e, null);
|
if (e) done(e, null);
|
||||||
});
|
});
|
||||||
});
|
};
|
||||||
|
if (localAddress) sock.bind({ address: localAddress }, onBound);
|
||||||
|
else sock.bind(onBound);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
let binarySession = 0;
|
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). */
|
/** Build a binary "write relay with jogging" frame (relay on, auto-off). */
|
||||||
function jogFrame(channel: number, password: number, jogMs: number): Buffer {
|
function jogFrame(channel: number, password: number, jogMs: number): Buffer {
|
||||||
const session = binarySession++ & 0xff;
|
const session = binarySession++ & 0xff;
|
||||||
@@ -151,9 +147,9 @@ function writeRelayFrame(channel: number, on: boolean, password: number, channel
|
|||||||
const rand16 = () => randomBytes(2).readUInt16BE(0);
|
const rand16 = () => randomBytes(2).readUInt16BE(0);
|
||||||
|
|
||||||
/** GET a CGI path on the device's HTTP server and return the raw response text. */
|
/** 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): Promise<string> {
|
function cgiGet(host: string, httpPort: number, path: string, timeoutMs: number, localAddress?: string): Promise<string> {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const req = httpRequest({ host, port: httpPort, path, method: "GET", timeout: timeoutMs }, (res) => {
|
const req = httpRequest({ host, port: httpPort, path, method: "GET", timeout: timeoutMs, localAddress }, (res) => {
|
||||||
let data = "";
|
let data = "";
|
||||||
res.on("data", (c) => (data += c));
|
res.on("data", (c) => (data += c));
|
||||||
res.on("end", () => resolve(data));
|
res.on("end", () => resolve(data));
|
||||||
@@ -186,6 +182,7 @@ function configApi(
|
|||||||
body: string | null,
|
body: string | null,
|
||||||
timeoutMs: number,
|
timeoutMs: number,
|
||||||
sessionId?: number, // device session check: sent as Cookie: session=<id>
|
sessionId?: number, // device session check: sent as Cookie: session=<id>
|
||||||
|
localAddress?: string, // bind outbound to the device-facing NIC (multi-homed hosts)
|
||||||
): Promise<string> {
|
): Promise<string> {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
// The device's embedded HTTP server does NOT support chunked request bodies.
|
// The device's embedded HTTP server does NOT support chunked request bodies.
|
||||||
@@ -207,6 +204,7 @@ function configApi(
|
|||||||
path,
|
path,
|
||||||
method,
|
method,
|
||||||
timeout: timeoutMs,
|
timeout: timeoutMs,
|
||||||
|
localAddress,
|
||||||
headers: Object.keys(headers).length ? headers : undefined,
|
headers: Object.keys(headers).length ? headers : undefined,
|
||||||
},
|
},
|
||||||
(res) => {
|
(res) => {
|
||||||
@@ -232,19 +230,28 @@ class DingtianController
|
|||||||
{
|
{
|
||||||
readonly driverId = "dingtian";
|
readonly driverId = "dingtian";
|
||||||
readonly #host: string;
|
readonly #host: string;
|
||||||
readonly #port: number; // string protocol (status read) — UDP 60001
|
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 #binaryPort: number; // binary protocol (relay control) — UDP 60000
|
||||||
readonly #relayPassword: number; // relay_pw (0 = none)
|
readonly #relayPassword: number; // relay_pw (0 = none)
|
||||||
readonly #sessionId: number; // device CGI session id (0 = session check off)
|
readonly #sessionId: number; // device CGI session id (0 = session check off)
|
||||||
readonly #httpPort: number;
|
readonly #httpPort: number;
|
||||||
readonly #timeout: 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;
|
readonly #channels: number;
|
||||||
/** Input level at rest; an input is "active" when it differs from this. */
|
/** Input level at rest; an input is "active" when it differs from this. */
|
||||||
readonly #restingHigh: boolean;
|
readonly #restingHigh: boolean;
|
||||||
readonly #pulseMs: number;
|
readonly #pulseMs: number;
|
||||||
/** Current device web-UI login (gates the browser UI only, not the CGI API). */
|
/** Device web-UI login user (gates the browser UI only, not the CGI API). */
|
||||||
readonly #webUser: string;
|
readonly #webUser: string;
|
||||||
readonly #webPassword: 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;
|
#poll: ReturnType<typeof setInterval> | null = null;
|
||||||
#last: boolean[] | null = null;
|
#last: boolean[] | null = null;
|
||||||
@@ -257,16 +264,21 @@ class DingtianController
|
|||||||
this.#relayPassword = config.relayPassword ? Number(config.relayPassword) : 0;
|
this.#relayPassword = config.relayPassword ? Number(config.relayPassword) : 0;
|
||||||
this.#sessionId = config.sessionId ? Number(config.sessionId) : 0;
|
this.#sessionId = config.sessionId ? Number(config.sessionId) : 0;
|
||||||
this.#httpPort = config.httpPort ? Number(config.httpPort) : 80;
|
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.#timeout = config.timeoutMs ? Number(config.timeoutMs) : 2000;
|
||||||
this.#channels = config.channels ? Number(config.channels) : 4;
|
this.#channels = config.channels ? Number(config.channels) : 4;
|
||||||
// This unit idles with inputs HIGH (status "1111"); a press pulls LOW.
|
// This unit idles with inputs HIGH (status "1111"); a press pulls LOW.
|
||||||
this.#restingHigh = config.inputRestingHigh !== false;
|
this.#restingHigh = config.inputRestingHigh !== false;
|
||||||
this.#pulseMs = config.pulseMs ? Number(config.pulseMs) : 500;
|
this.#pulseMs = config.pulseMs ? Number(config.pulseMs) : 500;
|
||||||
// The device ships with admin/admin. After harden() rotates it, the new
|
|
||||||
// creds are stored back in config so a re-created driver knows the current
|
|
||||||
// login (needed to rotate again — userset.cgi checks the old credentials).
|
|
||||||
this.#webUser = config.webUser ? String(config.webUser) : "admin";
|
this.#webUser = config.webUser ? String(config.webUser) : "admin";
|
||||||
this.#webPassword = config.webPassword ? String(config.webPassword) : "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> {
|
async connect(): Promise<void> {
|
||||||
@@ -297,14 +309,14 @@ class DingtianController
|
|||||||
async pulseOpen(doorId: number): Promise<void> {
|
async pulseOpen(doorId: number): Promise<void> {
|
||||||
this.#assertChannel(doorId);
|
this.#assertChannel(doorId);
|
||||||
const frame = jogFrame(doorId, this.#relayPassword, this.#pulseMs);
|
const frame = jogFrame(doorId, this.#relayPassword, this.#pulseMs);
|
||||||
await binaryUdp(this.#host, this.#binaryPort, frame, this.#timeout);
|
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. */
|
/** Latch a relay on/off (e.g. for a held-open mode). Channel is 1-based. */
|
||||||
async setRelay(doorId: number, on: boolean): Promise<void> {
|
async setRelay(doorId: number, on: boolean): Promise<void> {
|
||||||
this.#assertChannel(doorId);
|
this.#assertChannel(doorId);
|
||||||
const frame = writeRelayFrame(doorId, on, this.#relayPassword, this.#channels);
|
const frame = writeRelayFrame(doorId, on, this.#relayPassword, this.#channels);
|
||||||
await binaryUdp(this.#host, this.#binaryPort, frame, this.#timeout);
|
await binaryUdp(this.#host, this.#binaryPort, frame, this.#timeout, this.#localAddress);
|
||||||
}
|
}
|
||||||
|
|
||||||
async getDoorStatus(doorId: number): Promise<"open" | "closed"> {
|
async getDoorStatus(doorId: number): Promise<"open" | "closed"> {
|
||||||
@@ -421,19 +433,30 @@ class DingtianController
|
|||||||
/**
|
/**
|
||||||
* Lock the device down for a flat (no-VLAN) network:
|
* Lock the device down for a flat (no-VLAN) network:
|
||||||
* - set a random relay password (`relay_pw`) so binary relay commands need it,
|
* - set a random relay password (`relay_pw`) so binary relay commands need it,
|
||||||
* - disable unused protocol channels (rs485/can/tcp×2/mqtt) — keep only UDP1
|
* - keep ONLY UDP1 binary (password-protected relay control + status read),
|
||||||
* binary (relay control) and UDP2 string (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
|
* Returns the relay password for the backend to persist (required to keep
|
||||||
* commanding the device afterwards).
|
* 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
|
* 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
|
* (`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
|
* 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
|
* 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.
|
* relay_pw + fewer open channels + the signed event log.
|
||||||
*
|
*
|
||||||
* All are plaintext over HTTP/UDP on a flat network → defence-in-depth, not a
|
* Even with the string hole closed, all of this is plaintext over UDP/HTTP →
|
||||||
* boundary; the signed event log is the real guarantee. See device-input-flow.
|
* 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> {
|
async harden(): Promise<HardenResult> {
|
||||||
const cfg = await this.#readConfig();
|
const cfg = await this.#readConfig();
|
||||||
@@ -442,17 +465,24 @@ class DingtianController
|
|||||||
const relayPassword = 1 + (rand16() % 9999); // 1..9999 (0 = none)
|
const relayPassword = 1 + (rand16() % 9999); // 1..9999 (0 = none)
|
||||||
|
|
||||||
rc.relay_pw = relayPassword;
|
rc.relay_pw = relayPassword;
|
||||||
// Keep UDP1=Binary (p:1) for relay control, UDP2=String (p:0) for status.
|
// Keep ONLY UDP1=Binary (p:1) — it carries relay_pw for both control AND the
|
||||||
// Disable everything else (p:255 = None).
|
// 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.udp1 as Record<string, unknown>).p = 1;
|
||||||
(rc.udp2 as Record<string, unknown>).p = 0;
|
(rc.udp2 as Record<string, unknown>).p = 255;
|
||||||
(rc.rs485 as Record<string, unknown>).p = 255;
|
(rc.rs485 as Record<string, unknown>).p = 255;
|
||||||
(rc.can as Record<string, unknown>).p = 255;
|
(rc.can as Record<string, unknown>).p = 255;
|
||||||
(rc.tcpc as Record<string, unknown>).p = 255;
|
(rc.tcpc as Record<string, unknown>).p = 255;
|
||||||
(rc.tcps as Record<string, unknown>).p = 255;
|
(rc.tcps as Record<string, unknown>).p = 255;
|
||||||
(rc.mqtt as Record<string, unknown>).p = 255;
|
(rc.mqtt as Record<string, unknown>).p = 255;
|
||||||
|
|
||||||
await this.#writeConfig(cfg, (after) => {
|
// 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;
|
const a = after.relay_connect as Record<string, unknown> | undefined;
|
||||||
return (
|
return (
|
||||||
a?.relay_pw === relayPassword &&
|
a?.relay_pw === relayPassword &&
|
||||||
@@ -463,47 +493,82 @@ class DingtianController
|
|||||||
|
|
||||||
const applied = [
|
const applied = [
|
||||||
"set relay password",
|
"set relay password",
|
||||||
"disabled rs485/can/tcp/mqtt channels (kept UDP binary + string)",
|
"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 };
|
const secrets: Record<string, string | number> = { relayPassword };
|
||||||
|
|
||||||
// Rotate the default admin/admin web login. NOTE: cosmetic — this device's
|
// Set the device web login to the admin's chosen password (or a random one).
|
||||||
// CGI API needs NO auth (config read/write + relay fire + this very call all
|
// NOTE: cosmetic for the control plane — the CGI API needs NO auth (config
|
||||||
// work unauthenticated), so the login only gates the interactive browser UI,
|
// read/write + relay fire all work unauthenticated), so the login only gates
|
||||||
// not the control plane. We rotate it anyway (defence-in-depth: stops a
|
// the interactive browser UI. We set it anyway (defence-in-depth) but it is
|
||||||
// casual browser reaching the settings page), but it is NOT a boundary; the
|
// NOT a boundary; the signed event log is. See dingtian-relay.md.
|
||||||
// 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 {
|
try {
|
||||||
const newPassword = await this.#rotateWebLogin();
|
const newPassword = await this.#rotateWebLogin();
|
||||||
secrets.webUser = this.#webUser;
|
secrets.webUser = this.#webUser;
|
||||||
secrets.webPassword = newPassword;
|
secrets.webPassword = newPassword;
|
||||||
applied.push("rotated the admin/admin web-UI login (cosmetic — CGI API is unauthenticated)");
|
// 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) {
|
} catch (err) {
|
||||||
// Don't fail the whole harden over a cosmetic step — log and continue.
|
warnings.push(
|
||||||
stubLog(this.driverId, `web-login rotate skipped: ${(err as Error).message}`);
|
`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 };
|
return { secrets, applied, warnings: warnings.length ? warnings : undefined };
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Rotate the device web-UI login password (keeps the username) via
|
* Set the device web-UI login to the DESIRED password (the admin's choice, or a
|
||||||
* `userset.cgi?<old_user>&<old_pass>&<new_user>&<new_pass>&`. Returns the new
|
* random one if none was given) via
|
||||||
* password. The device validates the OLD credentials in the query, so we send
|
* `userset.cgi?<user>&<old_pass>&<user>&<new_pass>&`. The device validates the
|
||||||
* the current ones (admin/admin on first run, the stored pair afterwards).
|
* OLD credentials, so we send #webPasswordCurrent (admin on a fresh device).
|
||||||
* Response is `&<code>&<redirect>&` with code 0 = success. Password is hex
|
* Response `&<code>&…&`, code 0 = success.
|
||||||
* (URL-safe, no escaping) and ≤31 chars (the device truncates longer).
|
*
|
||||||
|
* 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> {
|
async #rotateWebLogin(): Promise<string> {
|
||||||
const newPassword = randomBytes(12).toString("hex"); // 24 hex chars
|
const newPassword = this.#webPassword ?? randomBytes(12).toString("hex");
|
||||||
const u = encodeURIComponent(this.#webUser);
|
const u = encodeURIComponent(this.#webUser);
|
||||||
const oldP = encodeURIComponent(this.#webPassword);
|
const setPath = (oldP: string, newP: string) =>
|
||||||
const path = `/userset.cgi?${u}&${oldP}&${u}&${newPassword}&`;
|
`/userset.cgi?${u}&${encodeURIComponent(oldP)}&${u}&${encodeURIComponent(newP)}&`;
|
||||||
const res = await cgiGet(this.#host, this.#httpPort, path, this.#timeout);
|
|
||||||
// "&0&/&" = success; anything else (e.g. "&-5&/&" bad params / wrong old pw).
|
const res = await cgiGet(this.#host, this.#httpPort, setPath(this.#webPasswordCurrent, newPassword), this.#timeout, this.#localAddress);
|
||||||
const code = res.split("&")[1];
|
const code = res.split("&")[1];
|
||||||
if (code !== "0") {
|
if (code !== "0") {
|
||||||
throw new Error(`userset.cgi rejected (response "${res.trim()}")`);
|
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;
|
return newPassword;
|
||||||
}
|
}
|
||||||
@@ -511,7 +576,7 @@ class DingtianController
|
|||||||
// --- config api internals ----------------------------------------------
|
// --- config api internals ----------------------------------------------
|
||||||
|
|
||||||
async #readConfig(): Promise<Record<string, unknown>> {
|
async #readConfig(): Promise<Record<string, unknown>> {
|
||||||
const raw = await configApi(this.#host, this.#httpPort, "/api/v2/config.cgi", "GET", null, this.#timeout, this.#sessionId);
|
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>;
|
return JSON.parse(raw) as Record<string, unknown>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -527,7 +592,7 @@ class DingtianController
|
|||||||
async #writeConfig(
|
async #writeConfig(
|
||||||
cfg: Record<string, unknown>,
|
cfg: Record<string, unknown>,
|
||||||
verify: (after: Record<string, unknown>) => boolean,
|
verify: (after: Record<string, unknown>) => boolean,
|
||||||
): Promise<void> {
|
): Promise<Record<string, unknown>> {
|
||||||
// The set endpoint requires `"command":"setconfig"` injected after `status`
|
// The set endpoint requires `"command":"setconfig"` injected after `status`
|
||||||
// (the GET payload omits it). Rebuild preserving node order, command second.
|
// (the GET payload omits it). Rebuild preserving node order, command second.
|
||||||
const out: Record<string, unknown> = {};
|
const out: Record<string, unknown> = {};
|
||||||
@@ -543,7 +608,7 @@ class DingtianController
|
|||||||
// POST. The device resets on apply, so the connection may drop — that's
|
// POST. The device resets on apply, so the connection may drop — that's
|
||||||
// expected, not failure.
|
// expected, not failure.
|
||||||
try {
|
try {
|
||||||
await configApi(this.#host, this.#httpPort, "/api/v2/config_set.cgi", "POST", payload, this.#timeout, this.#sessionId);
|
await configApi(this.#host, this.#httpPort, "/api/v2/config_set.cgi", "POST", payload, this.#timeout, this.#sessionId, this.#localAddress);
|
||||||
} catch {
|
} catch {
|
||||||
// device likely reset on apply
|
// device likely reset on apply
|
||||||
}
|
}
|
||||||
@@ -552,7 +617,8 @@ class DingtianController
|
|||||||
for (let i = 0; i < 12; i++) {
|
for (let i = 0; i < 12; i++) {
|
||||||
await sleep(2000);
|
await sleep(2000);
|
||||||
try {
|
try {
|
||||||
if (verify(await this.#readConfig())) return; // applied
|
const after = await this.#readConfig();
|
||||||
|
if (verify(after)) return after; // applied — return the landed config
|
||||||
} catch {
|
} catch {
|
||||||
// still rebooting / unreachable — keep polling
|
// still rebooting / unreachable — keep polling
|
||||||
}
|
}
|
||||||
@@ -581,21 +647,35 @@ class DingtianController
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Query "00" → parse "0000:1111:4" into relays/inputs/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> {
|
async #status(): Promise<DingtianStatus> {
|
||||||
const reply = await udpRequest(this.#host, this.#port, "00", this.#timeout, true);
|
const frame = readStatusFrame(this.#relayPassword);
|
||||||
if (!reply) throw new Error("dingtian: empty status reply");
|
const reply = await binaryUdp(this.#host, this.#binaryPort, frame, this.#timeout, this.#localAddress);
|
||||||
const [relayStr, inputStr, countStr] = reply.trim().split(":");
|
const width = Math.max(1, Math.ceil(this.#channels / 8));
|
||||||
if (relayStr === undefined || inputStr === undefined) {
|
// header: FF AA session 00 (4 bytes) + relay field + input field
|
||||||
throw new Error(`dingtian: bad status reply "${reply}"`);
|
if (reply.length < 4 + width * 2) {
|
||||||
|
throw new Error(`dingtian: short binary status reply (${reply.length} bytes)`);
|
||||||
}
|
}
|
||||||
const bit = (c: string) => c === "1";
|
const relayVal = reply.readUIntLE(4, width);
|
||||||
return {
|
const inputVal = reply.readUIntLE(4 + width, width);
|
||||||
relays: [...relayStr].map(bit),
|
const relays: boolean[] = [];
|
||||||
// active = differs from the resting level (press pulls the line).
|
const inputs: boolean[] = [];
|
||||||
inputs: [...inputStr].map((c) => bit(c) !== this.#restingHigh),
|
for (let i = 0; i < this.#channels; i++) {
|
||||||
channels: countStr ? Number(countStr) : this.#channels,
|
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 {
|
#startPolling(): void {
|
||||||
@@ -664,11 +744,14 @@ export const dingtianDriver: AccessDriver = {
|
|||||||
help: "This board idles inputs HIGH (status 1111); a press pulls LOW.",
|
help: "This board idles inputs HIGH (status 1111); a press pulls LOW.",
|
||||||
},
|
},
|
||||||
{ key: "timeoutMs", label: "Timeout (ms)", type: "number", required: false, default: 2000 },
|
{ key: "timeoutMs", label: "Timeout (ms)", type: "number", required: false, default: 2000 },
|
||||||
// Current device web-UI login. Defaults to admin/admin; harden() rotates the
|
// Device web-UI login. webPassword = the password you WANT (blank → a random
|
||||||
// password and stores the new pair back here so a re-run can rotate again.
|
// one is generated). webPasswordCurrent = the device's EXISTING password, used
|
||||||
// (Gates only the browser UI — the CGI control plane is unauthenticated.)
|
// 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: "webUser", label: "Device web username", type: "string", required: false, default: "admin", help: "Device web-UI login user (default admin)." },
|
||||||
{ key: "webPassword", label: "Device web password", type: "secret", required: false, help: "Device web-UI login password (default admin; rotated on save)." },
|
{ 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),
|
create: (c) => new DingtianController(c),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -142,6 +142,10 @@ export interface HardenResult {
|
|||||||
readonly secrets: Record<string, string | number>;
|
readonly secrets: Record<string, string | number>;
|
||||||
/** Human-readable summary of what was changed (for logging/UI). */
|
/** Human-readable summary of what was changed (for logging/UI). */
|
||||||
readonly applied: string[];
|
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 {
|
export function isHardenable(device: Device): device is Device & HardenableDevice {
|
||||||
|
|||||||
@@ -34,6 +34,10 @@ export interface ParkingEvent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export type ParkingEventType =
|
export type ParkingEventType =
|
||||||
|
// A raw device input (e.g. a Dingtian button press) was received and recorded.
|
||||||
|
// NOT a confirmed entry — the richer `vehicle_entry` is appended later by the
|
||||||
|
// entry flow once a ticket prints and the barrier is commanded.
|
||||||
|
| "input_received"
|
||||||
| "vehicle_entry"
|
| "vehicle_entry"
|
||||||
| "vehicle_exit"
|
| "vehicle_exit"
|
||||||
| "void"
|
| "void"
|
||||||
@@ -48,3 +52,26 @@ export const ROLES: readonly Role[] = [
|
|||||||
"cashier",
|
"cashier",
|
||||||
"readonly",
|
"readonly",
|
||||||
] as const;
|
] 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;
|
||||||
|
}
|
||||||
|
|||||||
@@ -24,3 +24,64 @@ It only becomes trustworthy as an external fraud control when paired with [[reco
|
|||||||
against an authority the operator can't alter. Every device event — including those ingested
|
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
|
from the [[uhppote-controller]] via [[event-log-ingestion]] — should land in this host-side
|
||||||
chain.
|
chain.
|
||||||
|
|
||||||
|
## Implementation (apps/server)
|
||||||
|
|
||||||
|
> Implementation-derived. The schema (`packages/db` `events`) and types
|
||||||
|
> (`packages/shared` `ParkingEvent`) predate this; the writer/signer are new.
|
||||||
|
|
||||||
|
- **`EventLog`** (`apps/server/src/event-log.ts`) is the append primitive. `append()` reads the
|
||||||
|
latest row, sets `index = prev + 1`, `prevHash = sha256(canonical(prev))` (genesis = null),
|
||||||
|
signs the canonical form, and inserts. There are **no update/delete paths**.
|
||||||
|
- **Serialized appends.** SQLite is single-writer, but read-prev → compute-hash → insert is
|
||||||
|
multi-step, so `EventLog` also guards it with an in-process async lock — otherwise two near-
|
||||||
|
simultaneous events could claim the same `index` or chain off a stale `prevHash`. Verified:
|
||||||
|
5 concurrent appends produced indices 1..5 with an intact chain.
|
||||||
|
- **Canonical form** is a fixed-order JSON array (`index,type,direction,lane,source,identity,
|
||||||
|
occurredAt,prevHash`) — byte-stable, since the chain + signatures depend on it. The volatile
|
||||||
|
row `id` is excluded; chain identity is `index` + content.
|
||||||
|
- **`verifyChain()`** walks oldest→newest, recomputing hashes + signatures. Catches tampered
|
||||||
|
content (bad signature), reordering / a deleted row (`index` gap), and a `prevHash` mismatch.
|
||||||
|
Exposed at `GET /api/events/verify` (admin). Read access to the log: `GET /api/events`.
|
||||||
|
|
||||||
|
### The `Signer` abstraction (software now, ATECC608 later)
|
||||||
|
|
||||||
|
Signing goes through a **`Signer`** interface (`packages/shared`) — the abstraction over the
|
||||||
|
[[atecc608]]. Because the chip being wired is still [[open-questions|open-question #6]], the
|
||||||
|
server ships a **`SoftwareSigner`** (HMAC-SHA256, key from `EVENT_SIGNING_KEY`). Swapping to the
|
||||||
|
secure element is a new `Signer` impl with no `EventLog` change; each event stores its `keyId`
|
||||||
|
so old events stay verifiable.
|
||||||
|
|
||||||
|
> ⚠️ The software signer makes the chain **self-consistent + tamper-evident**, but **not
|
||||||
|
> unforgeable by someone who owns the host** — only the ATECC608's non-extractable key gives
|
||||||
|
> property (3) above. Until the chip is wired, the chain detects tampering by *outsiders* and
|
||||||
|
> *accidental* corruption, but an operator with the signing key + DB access could re-sign a
|
||||||
|
> forged chain. This is the central reason #6 matters.
|
||||||
|
|
||||||
|
### What currently feeds the log
|
||||||
|
|
||||||
|
Dingtian **input (button) pushes** → bus → `input_received` events (see [[device-input-flow]],
|
||||||
|
[[dingtian-relay]]). These are recorded faithfully as raw inputs, **not** as `vehicle_entry` —
|
||||||
|
the richer entry event waits for the entry flow (ticket print + barrier command). Device→lane
|
||||||
|
mapping is still a TODO (logged with `lane: 0`).
|
||||||
|
|
||||||
|
### ⚠️ 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 [[lpr-camera]]; payment/Z-report). **A physical open with no matching
|
||||||
|
signed command is the fraud signal.** 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.
|
||||||
|
|||||||
@@ -27,17 +27,33 @@ each device's connection config.
|
|||||||
authenticated input push ([[device-input-flow]]) — the admin never touches the device's own web
|
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
|
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 `lane_devices`.
|
orphan/half-configured rows. On success persists to `lane_devices`.
|
||||||
4. **Complete** — `POST /api/setup/complete` marks the single-row `setup_state`.
|
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
|
The data model is **multi-instance**: `lane_devices` holds **one row per instance**, keyed by a
|
||||||
its own connection settings. Matches the architecture's "mixable per lane" reality (a lane can
|
generated `id`, with no one-per-(lane, category) constraint. So a lane can have **more than one of
|
||||||
serve permit holders via [[wiegand]] and casual via host-side reads on one relay — see
|
every category** — e.g. two printers (an entry dispenser + a booth printer; see
|
||||||
[[entry-exit-readers]]).
|
[[printer-roles-failover]]), multiple readers, multiple cameras. `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** for the
|
||||||
|
current lane (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.
|
||||||
|
|
||||||
|
Organized **per lane** — each lane gets its access controller(s), reader(s), camera(s), and
|
||||||
|
printer(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]]).
|
||||||
|
|
||||||
## Security notes
|
## Security notes
|
||||||
|
|
||||||
- The assign/state/complete endpoints require the **admin** role ([[local-jwt-auth]]).
|
- The assign/state/delete/complete endpoints require the **admin** role ([[local-jwt-auth]]).
|
||||||
- Device **credentials are stored in `lane_devices.config`** — protect at rest
|
- Device **credentials are stored in `lane_devices.config`** — protect at rest
|
||||||
([[disk-os-hardening]]); device hosts belong on the isolated VLAN ([[network-isolation]]).
|
([[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).
|
||||||
|
|||||||
@@ -79,17 +79,53 @@ the relay via UDP. See [[device-input-flow]] for the full path + trust model.
|
|||||||
> real path** — lower latency, and it can be authenticated (the device supports Basic/Digest +
|
> real path** — lower latency, and it can be authenticated (the device supports Basic/Digest +
|
||||||
> HTTPS on the push), unlike the open UDP control direction.
|
> HTTPS on the push), unlike the open UDP control direction.
|
||||||
|
|
||||||
|
### What it pushes vs. doesn't (logging)
|
||||||
|
|
||||||
|
- **Inputs (buttons): YES, pushed.** Input changes are HTTP-pushed via `input_link_url` and now
|
||||||
|
land in the host's signed [[append-only-event-chain]] as `input_received` events (bus →
|
||||||
|
`EventLog`). That is the audit trail for "a button fired."
|
||||||
|
- **Relay / barrier opens: NO push, no log.** The device has **no event log of its own** and does
|
||||||
|
not report when a relay fires — relay control is one-way UDP that the *host* initiates. So
|
||||||
|
"the barrier opened" is not something to scrape from the device. The host records what it
|
||||||
|
*commanded* (a future `barrier_open_command` event); a relay open with **no matching signed
|
||||||
|
host event is itself the anomaly** to alarm on ([[threat-model]]). Do not treat the Dingtian as
|
||||||
|
a log source — it is a dumb relay+input board; the host is the source of truth.
|
||||||
|
|
||||||
## Hardening (`harden()`) — and why HTTP auth is not a boundary here
|
## Hardening (`harden()`) — and why HTTP auth is not a boundary here
|
||||||
|
|
||||||
On assign the driver runs `harden()` (the [[device-registry|HardenableDevice]] capability):
|
On assign the driver runs `harden()` (the [[device-registry|HardenableDevice]] capability):
|
||||||
1. **`relay_pw`** — set a random relay password so binary relay commands (UDP 60000) need it.
|
1. **`relay_pw`** — set a random relay password so binary relay commands (UDP 60000) need it.
|
||||||
2. **Disable unused channels** — set `p:255` on rs485/can/tcp×2/mqtt; keep only UDP1 binary
|
2. **Disable EVERY other channel** — set `p:255` on the string protocol (udp2), rs485, can,
|
||||||
(relay control) + UDP2 string (status read).
|
tcp×2, mqtt; keep **only** UDP1 binary, which carries `relay_pw` for both control AND status.
|
||||||
3. **Rotate the `admin`/`admin` web login** — `GET /userset.cgi?<old_u>&<old_p>&<new_u>&<new_p>&`
|
3. **Rotate the `admin`/`admin` web login** — `GET /userset.cgi?<old_u>&<old_p>&<new_u>&<new_p>&`
|
||||||
(response `&0&…&` = success, verified on hardware). The new password is stored back in
|
(response `&0&…&` = success, verified on hardware). The new password is stored back in
|
||||||
config (`webUser`/`webPassword`) so a re-run can rotate again (the device checks the *old*
|
config (`webUser`/`webPassword`) so a re-run can rotate again (the device checks the *old*
|
||||||
creds). This step is **best-effort** — a failure logs and does not fail the assign.
|
creds). This step is **best-effort** — a failure logs and does not fail the assign.
|
||||||
|
|
||||||
|
> ⚠️ **The string protocol (udp2) is a password-less relay-fire path — the original `harden()`
|
||||||
|
> left it ENABLED "for status reads", which was a real hole.** The Dingtian string protocol has
|
||||||
|
> NO password field and can fire relays (`"11"` = relay 1 on, `"21"` = off, `"11*"` = jog).
|
||||||
|
> **Proven on hardware**: sending `"11"` to UDP 60001 with no credentials opened relay 1,
|
||||||
|
> completely bypassing `relay_pw`. Fixes: (a) status reads moved to the **authenticated binary
|
||||||
|
> read** (relay command `0x00`) so the string protocol is no longer needed; (b) `harden()` now
|
||||||
|
> sets `udp2.p=255` to disable it. **Firmware caveat (V3.6J):** the CONFIG API silently refuses
|
||||||
|
> to disable udp2 — it accepts the write, reboots, and clamps it back — even though the device's
|
||||||
|
> **web UI can** disable it. So the udp2 disable is **best-effort + warns** (it is NOT part of the
|
||||||
|
> blocking verify); if it doesn't stick, `harden()` returns a warning telling the admin to flip
|
||||||
|
> UDP2 off in the device web UI. Verified: after the web-UI disable, the `"11"` attack gets no
|
||||||
|
> reply and the relay stays off, while authenticated binary control/status still work.
|
||||||
|
|
||||||
|
> 🔑 **Web-login model (bug fixed).** The login set has TWO distinct config keys:
|
||||||
|
> `webPassword` = the password the admin WANTS (blank → harden generates a random one), and
|
||||||
|
> `webPasswordCurrent` = the device's EXISTING password (the old cred `userset.cgi` checks;
|
||||||
|
> defaults to `admin`). The original code conflated them — an admin typing a *desired* password
|
||||||
|
> made harden send it as the *old* cred, the rotation failed, yet the DB still saved the typed
|
||||||
|
> value: **the DB claimed a password the device never accepted (login stayed admin/admin).**
|
||||||
|
> Fix: harden now rotates `current → desired`, **verifies** by re-authenticating with the new
|
||||||
|
> password, and only then returns `secrets.webPassword`; assign strips the typed inputs and
|
||||||
|
> persists only the verified value (else a warning, no save). Verified on hardware: device
|
||||||
|
> rejects `admin/admin` (`&2&`) and accepts the chosen password (`&0&`) after harden.
|
||||||
|
>
|
||||||
> ⚠️ **The device CGI API is UNAUTHENTICATED.** Verified on hardware: `GET /api/v2/config.cgi`,
|
> ⚠️ **The device CGI API is UNAUTHENTICATED.** Verified on hardware: `GET /api/v2/config.cgi`,
|
||||||
> `/`, and even `/userset.cgi` all return **200 with no credentials**. The `admin`/`admin` login
|
> `/`, and even `/userset.cgi` all return **200 with no credentials**. The `admin`/`admin` login
|
||||||
> gates only the interactive **browser UI** — the CGI control plane (read/write full config, fire
|
> gates only the interactive **browser UI** — the CGI control plane (read/write full config, fire
|
||||||
|
|||||||
+61
@@ -227,3 +227,64 @@ guarantee. Recorded in [[dingtian-relay]] (new Hardening section).
|
|||||||
- New page: [[printer-status-monitoring]]. Updated [[rongta-printer]], [[index]].
|
- New page: [[printer-status-monitoring]]. Updated [[rongta-printer]], [[index]].
|
||||||
- Open: capture the page's actual text for an ACTIVE fault (pull paper / open cover) to confirm
|
- Open: capture the page's actual text for an ACTIVE fault (pull paper / open cover) to confirm
|
||||||
the Yes flip; wire degraded/offline into failover + entry-flow all-down policy.
|
the Yes flip; wire degraded/offline into failover + entry-flow all-down policy.
|
||||||
|
|
||||||
|
## [2026-06-15] ingest | Multi-instance device setup (add/remove per category)
|
||||||
|
- Confirmed the data model was already multi-instance (lane_devices = one row per instance,
|
||||||
|
assign always inserts); the limitation was UI-only (one slot per category).
|
||||||
|
- Backend: added DELETE /api/setup/assign/:id (unassign); /state now redacts secrets
|
||||||
|
(pushPassword/webPassword/relayPassword) via a shared redactSecrets() also used by /assign.
|
||||||
|
- Web: SetupWizard reworked — each category lists assigned instances (with Remove) + "Add
|
||||||
|
another" form; select-type config fields now render as dropdowns (fixes printer role input).
|
||||||
|
- Verified via Fastify inject: 2 printers assigned to one lane -> both listed, no secret leak,
|
||||||
|
delete -> 204, delete unknown -> 404, count drops to 1. Full repo typechecks (8/8).
|
||||||
|
- Updated [[first-run-setup]].
|
||||||
|
|
||||||
|
## [2026-06-15] ingest | Append-only signed event log (Dingtian input pushes persist)
|
||||||
|
- Q: does the Dingtian push events? -> inputs YES (input_link_url), relay opens NO (device keeps
|
||||||
|
no log). Host is the source of truth; a relay open w/o matching signed event is the anomaly.
|
||||||
|
- Implemented EventLog (apps/server/event-log.ts): serialized append, monotonic index, prevHash
|
||||||
|
chain, signature; verifyChain() detects tamper/reorder/delete. Read: GET /api/events;
|
||||||
|
integrity: GET /api/events/verify (admin).
|
||||||
|
- Signer abstraction (packages/shared) over the ATECC608; SoftwareSigner (HMAC, EVENT_SIGNING_KEY)
|
||||||
|
shipped now since chip wiring is open-question #6. Caveat documented: software signer is
|
||||||
|
tamper-evident but NOT unforgeable-by-owner.
|
||||||
|
- Wired bus -> log: Dingtian input pushes become input_received events (lane mapping TODO).
|
||||||
|
- Added ParkingEventType 'input_received'.
|
||||||
|
- Verified via inject: push w/o digest -> 401; pushes -> 2 signed+chained events; verify -> ok;
|
||||||
|
direct DB tamper -> verifyChain catches at the right index; deleted row -> index gap. 5 concurrent
|
||||||
|
appends -> indices 1..5 intact. Full repo typechecks.
|
||||||
|
- Updated [[append-only-event-chain]], [[dingtian-relay]].
|
||||||
|
|
||||||
|
## [2026-06-15] ingest | Event log + Dingtian string-protocol security fix
|
||||||
|
- Append-only signed event log shipped (EventLog, Signer abstraction over ATECC608 w/ SoftwareSigner
|
||||||
|
HMAC; GET /api/events + /api/events/verify). Dingtian input pushes persist as input_received.
|
||||||
|
Verified on hardware: shorting I1-I4 -> 8 signed+chained events, verifyChain ok.
|
||||||
|
- SECURITY (verified on hardware): the password-less string protocol (udp2) can fire relays
|
||||||
|
("11" -> relay1 on) with NO auth, bypassing relay_pw. Fixes: status reads moved to authenticated
|
||||||
|
binary read (cmd 0x00); harden() disables udp2 BEST-EFFORT (firmware V3.6J config API refuses,
|
||||||
|
but web UI works) and returns a warning instead of throwing. After web-UI disable, the "11" attack
|
||||||
|
is dead and binary control/status still work.
|
||||||
|
- GAP (user-identified): event log captures host-originated actions only; out-of-band relay
|
||||||
|
actuation (sniffed relay_pw, string protocol, ip_watchdog) produces NO event — proven on hardware.
|
||||||
|
Real control is reconciliation vs. an independent witness; witness+reconciliation NOT yet built.
|
||||||
|
- Device web login (webUser/webPassword) now un-redacted in setup state (admin-only device area);
|
||||||
|
pushPassword/relayPassword stay machine-only.
|
||||||
|
- harden() warnings surfaced via the assign response.
|
||||||
|
- localAddress threaded through the Dingtian driver (device-facing-IP foundation; multi-homed hosts).
|
||||||
|
- INCIDENT: probing default.cgi factory-reset the bench device (now at 192.168.1.100, defaults).
|
||||||
|
Re-provisioning is the ADMIN's job via First-run setup (app must not hardcode site IPs).
|
||||||
|
- Updated [[append-only-event-chain]], [[dingtian-relay]].
|
||||||
|
|
||||||
|
## [2026-06-15] fix | Dingtian web-password: desired-vs-current split + verify + UI warnings
|
||||||
|
- BUG (found in real assign): admin typed a web password; harden used it as the OLD cred, rotation
|
||||||
|
failed silently, DB saved the typed value but device login stayed admin/admin. Also UDP2 warning
|
||||||
|
never reached the admin (frontend discarded the assign response).
|
||||||
|
- FIX: split config into webPassword (desired; blank→random) and webPasswordCurrent (existing old
|
||||||
|
cred, default admin). harden() rotates current→desired, VERIFIES by re-auth with the new pw, and
|
||||||
|
only returns secrets.webPassword on success (else warning, no save). assign strips typed
|
||||||
|
webPassword/webPasswordCurrent and persists only verified secrets.
|
||||||
|
- SetupWizard now shows assign-response warnings (amber banner, per category) — closes the
|
||||||
|
feedback loop for the UDP2-can't-disable case.
|
||||||
|
- Verified on hardware (192.168.1.100): harden set login to a chosen pw; device then rejects
|
||||||
|
admin/admin (&2&) and accepts the chosen pw (&0&). UDP2 warning surfaced as designed.
|
||||||
|
- Updated [[dingtian-relay]].
|
||||||
|
|||||||
Reference in New Issue
Block a user