Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d0536da3d7 | |||
| ae736a9e3e | |||
| 1b54775b4d |
@@ -11,6 +11,8 @@ dist/
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
# Committed (non-secret): the desktop/prod build's backend origin — see apps/web/.env.production
|
||||
!.env.production
|
||||
|
||||
# Editor/OS
|
||||
.DS_Store
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# Desktop (Tauri) build — the @parking/web SPA needs to know where Fastify is.
|
||||
#
|
||||
# In a BROWSER (dev via the Vite proxy, or prod where Fastify serves the SPA),
|
||||
# leave VITE_API_BASE UNSET — requests stay relative/same-origin.
|
||||
#
|
||||
# For the DESKTOP build, the bundled SPA loads from tauri://localhost and has no
|
||||
# proxy, so point it at the appliance's Fastify origin. This is read at WEB build
|
||||
# time, so export it before `pnpm --filter @parking/desktop build` (or put it in
|
||||
# apps/web/.env.production).
|
||||
VITE_API_BASE=http://127.0.0.1:3000
|
||||
@@ -0,0 +1,3 @@
|
||||
# Rust / Tauri build artifacts
|
||||
src-tauri/target/
|
||||
src-tauri/gen/
|
||||
@@ -0,0 +1,42 @@
|
||||
# @parking/desktop — Tauri v2 kiosk shell
|
||||
|
||||
A **thin native desktop window** over the `@parking/web` SPA. It contains **no UI and no business
|
||||
logic** of its own: the window renders the *same* web app the browser does, so the desktop and the
|
||||
browser stay identical and never drift. Device/auth/ledger logic stays in `@parking/server`. See
|
||||
`wiki/decisions/desktop-shell-tauri.md`.
|
||||
|
||||
## How the "same look & functionality" guarantee works
|
||||
|
||||
| | Source of the UI |
|
||||
| --- | --- |
|
||||
| **Dev** (`tauri dev`) | the window loads `http://localhost:5173` — the **`@parking/web` Vite dev server**. Edit a component in `apps/web` → HMR updates the desktop window live. |
|
||||
| **Prod** (`tauri build`) | the window bundles `apps/web`'s built `dist/`. `beforeBuildCommand` rebuilds the SPA first. |
|
||||
|
||||
There is only one UI codebase (`apps/web`); this package just wraps it.
|
||||
|
||||
## Backend connection
|
||||
|
||||
The SPA talks to Fastify over HTTP/WS. In a browser that's same-origin (relative `/api`). In the
|
||||
desktop build the bundled assets load from `tauri://localhost`, so set **`VITE_API_BASE`** (read at
|
||||
web build time — see `.env.example`) to the appliance's Fastify origin, e.g.
|
||||
`http://127.0.0.1:3000`. The CSP `connect-src` in `tauri.conf.json` is already allowed for that
|
||||
origin, and the backend must include the Tauri origin in `WS_ALLOWED_ORIGINS` for the live feed.
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
pnpm --filter @parking/desktop dev # native window over the web dev server (HMR)
|
||||
pnpm --filter @parking/desktop bundle # build the SPA + bundle the desktop app (.deb/.rpm/.AppImage)
|
||||
```
|
||||
|
||||
> `build` is a **no-op** in this package so `turbo run build` stays fast — the real desktop bundle
|
||||
> (compiles Rust, minutes long) is the explicit `bundle` script above.
|
||||
|
||||
Requires the Rust toolchain and (on Linux) WebKitGTK 4.1 + libsoup-3 dev libraries. Under WSL2 the
|
||||
window needs a display (WSLg or an X server).
|
||||
|
||||
## Not here (deliberately)
|
||||
|
||||
Kiosk lockdown (fullscreen/no-decorations), auto-update, code signing, and launching Fastify from
|
||||
the shell are out of scope for the scaffold — on the appliance Fastify runs as its own service and
|
||||
this shell connects to it.
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"name": "@parking/desktop",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"//": "Tauri v2 desktop shell — a THIN native window over the @parking/web SPA. No business logic lives here (device/auth/ledger stay in @parking/server); see wiki/decisions/desktop-shell-tauri.md. Dev loads the web dev server (HMR); build bundles the web app's dist/, so the desktop UI and the browser UI are the SAME codebase and never drift.",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "tauri dev",
|
||||
"build": "echo 'no-op in the Turbo graph — the real desktop bundle is a deliberate `pnpm --filter @parking/desktop bundle` (compiles Rust + packages installers, minutes long)'",
|
||||
"bundle": "tauri build",
|
||||
"tauri": "tauri",
|
||||
"lint": "echo 'no JS lint (Tauri shell; Rust checked via cargo)'"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tauri-apps/cli": "^2.9.1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tauri-apps/plugin-process": "^2.3.1",
|
||||
"@tauri-apps/plugin-updater": "^2.10.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
[package]
|
||||
name = "parking-desktop"
|
||||
version = "0.0.0"
|
||||
description = "Parking System — desktop kiosk shell"
|
||||
edition = "2021"
|
||||
rust-version = "1.77"
|
||||
|
||||
# Thin Tauri v2 shell. Deliberately holds NO business logic — it loads the
|
||||
# @parking/web SPA and lets it talk to the local Fastify server. Device/auth/
|
||||
# ledger stay server-side. See wiki/decisions/desktop-shell-tauri.md.
|
||||
|
||||
[lib]
|
||||
name = "parking_desktop_lib"
|
||||
crate-type = ["staticlib", "cdylib", "rlib"]
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "2", features = [] }
|
||||
|
||||
[dependencies]
|
||||
tauri = { version = "2", features = [] }
|
||||
serde_json = "1"
|
||||
# Auto-update: prompt the operator, download a signed update, relaunch.
|
||||
tauri-plugin-updater = "2"
|
||||
tauri-plugin-process = "2"
|
||||
|
||||
[features]
|
||||
# Used by `tauri dev`/CLI for hot-reload of the Rust side.
|
||||
custom-protocol = ["tauri/custom-protocol"]
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() {
|
||||
tauri_build::build()
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "default",
|
||||
"description": "Minimal capability set for the kiosk shell. The window only needs to render the SPA; it is granted NOTHING that touches the filesystem, shell, or devices — those stay server-side. Add a named permission here only when a concrete need arises (deny-by-default). See wiki/decisions/desktop-shell-tauri.md.",
|
||||
"windows": ["main"],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"updater:default",
|
||||
"process:default"
|
||||
]
|
||||
}
|
||||
|
After Width: | Height: | Size: 953 B |
|
After Width: | Height: | Size: 1.2 KiB |
|
After Width: | Height: | Size: 552 B |
|
After Width: | Height: | Size: 745 B |
|
After Width: | Height: | Size: 891 B |
|
After Width: | Height: | Size: 1016 B |
|
After Width: | Height: | Size: 997 B |
|
After Width: | Height: | Size: 1.5 KiB |
|
After Width: | Height: | Size: 562 B |
|
After Width: | Height: | Size: 1.5 KiB |
|
After Width: | Height: | Size: 643 B |
|
After Width: | Height: | Size: 748 B |
|
After Width: | Height: | Size: 838 B |
|
After Width: | Height: | Size: 706 B |
|
After Width: | Height: | Size: 4.4 KiB |
|
After Width: | Height: | Size: 1.8 KiB |
@@ -0,0 +1,21 @@
|
||||
// Parking System desktop shell — entry point.
|
||||
//
|
||||
// Intentionally minimal: build the default Tauri app and run it. The window
|
||||
// config (kiosk, fullscreen, which URL/assets to load) lives in tauri.conf.json.
|
||||
// No custom commands are registered — the renderer (the @parking/web SPA) reaches
|
||||
// the backend over HTTP to the local Fastify server, NOT through Tauri IPC. This
|
||||
// keeps the shell a thin presentation wrapper with a deny-by-default native
|
||||
// surface (see wiki/decisions/desktop-shell-tauri.md).
|
||||
|
||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||
pub fn run() {
|
||||
tauri::Builder::default()
|
||||
// Auto-update: the JS side (apps/web) checks on launch, prompts the
|
||||
// operator, and installs + relaunches on confirm. These plugins expose
|
||||
// the update check/install and the relaunch to that flow. The updater
|
||||
// endpoint + signing pubkey live in tauri.conf.json.
|
||||
.plugin(tauri_plugin_updater::Builder::new().build())
|
||||
.plugin(tauri_plugin_process::init())
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running the Parking System desktop shell");
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
// Prevents an extra console window on Windows in release.
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
fn main() {
|
||||
parking_desktop_lib::run()
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "Parking System",
|
||||
"version": "0.0.0",
|
||||
"identifier": "com.parking.desktop",
|
||||
"build": {
|
||||
"devUrl": "http://localhost:5173",
|
||||
"frontendDist": "../../web/dist",
|
||||
"beforeDevCommand": "pnpm --filter @parking/web dev",
|
||||
"beforeBuildCommand": "pnpm --filter @parking/web build"
|
||||
},
|
||||
"app": {
|
||||
"windows": [
|
||||
{
|
||||
"label": "main",
|
||||
"title": "Parking System",
|
||||
"width": 1280,
|
||||
"height": 800,
|
||||
"minWidth": 1024,
|
||||
"minHeight": 640,
|
||||
"resizable": true,
|
||||
"maximized": true,
|
||||
"fullscreen": false
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": "default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; connect-src 'self' http://127.0.0.1:3000 http://localhost:3000 ws://127.0.0.1:3000 ws://localhost:3000"
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"targets": "all",
|
||||
"createUpdaterArtifacts": true,
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
"icons/128x128@2x.png",
|
||||
"icons/icon.icns",
|
||||
"icons/icon.ico"
|
||||
]
|
||||
},
|
||||
"plugins": {
|
||||
"updater": {
|
||||
"endpoints": [
|
||||
"https://UPDATES.EXAMPLE.invalid/parking/{{target}}/{{arch}}/{{current_version}}"
|
||||
],
|
||||
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDgxNzg5RUQ1QkM0Q0FDRjYKUldUMnJFeTgxWjU0Z1RlNmhneDVZQlVVTVZZdGhJTkUxTGdDeGYwQSttZmNKVVp5WEdVMWlBb1YK"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"$schema": "https://turbo.build/schema.json",
|
||||
"extends": ["//"],
|
||||
"//": "Tauri shell as a first-class Turbo node. build outputs [] so `turbo run build` doesn't try to cache/compile the Rust bundle on every pass (a real desktop bundle is a deliberate `pnpm --filter @parking/desktop build`).",
|
||||
"tasks": {
|
||||
"build": {
|
||||
"outputs": []
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { desc, gte, ledgerEvents, type Db } from "@parking/db";
|
||||
import { and, desc, gte, lte, ledgerEvents, type Db } from "@parking/db";
|
||||
import type { LedgerEvent } from "@parking/shared";
|
||||
import { requirePermission } from "../auth.js";
|
||||
import { enrichEvents } from "../event-enrich.js";
|
||||
@@ -19,19 +19,26 @@ export async function eventRoutes(
|
||||
const guard = requirePermission("event:read");
|
||||
|
||||
// Recent events, newest first. `limit` caps the page (default 100, max 1000).
|
||||
// Optional `since` (ISO) scopes the page to events at/after that instant — the
|
||||
// booth passes the current shift's start so the live feed shows ONLY this shift's
|
||||
// activity (logs are per-shift, not all history). See wiki/concepts/shift.md.
|
||||
app.get<{ Querystring: { limit?: string; since?: string } }>(
|
||||
// Optional `since` (ISO) scopes to events at/after that instant — the booth passes
|
||||
// the current shift's start so the live feed shows ONLY this shift's activity. An
|
||||
// optional `until` (ISO) closes the upper bound — the shift-history screen passes a
|
||||
// selected shift's [start, end] to show just that shift's signed activity log.
|
||||
// (logs are per-shift, not all history). See wiki/concepts/shift.md.
|
||||
app.get<{ Querystring: { limit?: string; since?: string; until?: string } }>(
|
||||
"/api/events",
|
||||
{ preHandler: guard },
|
||||
async (req) => {
|
||||
const limit = Math.min(Math.max(Number(req.query.limit) || 100, 1), 1000);
|
||||
const since = (req.query.since ?? "").trim();
|
||||
const until = (req.query.until ?? "").trim();
|
||||
const bounds = [
|
||||
since ? gte(ledgerEvents.occurredAt, since) : undefined,
|
||||
until ? lte(ledgerEvents.occurredAt, until) : undefined,
|
||||
].filter(Boolean);
|
||||
const rows = db
|
||||
.select()
|
||||
.from(ledgerEvents)
|
||||
.where(since ? gte(ledgerEvents.occurredAt, since) : undefined)
|
||||
.where(bounds.length ? and(...bounds) : undefined)
|
||||
.orderBy(desc(ledgerEvents.index))
|
||||
.limit(limit)
|
||||
.all();
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# Production build env for the SPA (auto-loaded by `vite build`, which the Tauri
|
||||
# desktop bundle runs via beforeBuildCommand). NOT loaded by `vite` dev.
|
||||
#
|
||||
# The desktop shell serves the bundled SPA from tauri://localhost (no proxy, not
|
||||
# same-origin), so the SPA must reach Fastify by absolute origin. This is the
|
||||
# appliance's local Fastify address. Not a secret — committed for reproducible
|
||||
# desktop builds. Override per-deployment if Fastify binds elsewhere.
|
||||
#
|
||||
# NOTE: a plain browser prod build (Fastify serving dist/ same-origin) does NOT
|
||||
# want this set. If you build the SPA for that, override VITE_API_BASE="" .
|
||||
VITE_API_BASE=http://127.0.0.1:3000
|
||||
@@ -17,6 +17,8 @@
|
||||
"@radix-ui/react-tabs": "^1.1.15",
|
||||
"@tanstack/react-query": "^5.101.0",
|
||||
"@tanstack/react-router": "^1.170.16",
|
||||
"@tauri-apps/plugin-process": "^2.3.1",
|
||||
"@tauri-apps/plugin-updater": "^2.10.1",
|
||||
"i18next": "^26.3.1",
|
||||
"react": "19.2.7",
|
||||
"react-dom": "19.2.7",
|
||||
|
||||
@@ -94,7 +94,7 @@ export function LogsViewer() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-5xl">
|
||||
<div className="">
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<h1 className="text-sm font-bold uppercase tracking-widest text-term-amber">{t("logs.title")}</h1>
|
||||
<button type="button" className="btn btn-ghost btn-sm" onClick={() => q.refetch()}>
|
||||
|
||||
@@ -53,7 +53,7 @@ export function RolesManager({ user }: { user: SessionUser | null }) {
|
||||
const onError = (e: unknown) => setError(e instanceof ApiError ? e.message : (e as Error).message);
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-4xl">
|
||||
<div className="">
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<h1 className="text-sm font-bold uppercase tracking-widest text-term-amber">{t("roles.title")}</h1>
|
||||
{canCreate && (
|
||||
|
||||
@@ -75,7 +75,7 @@ export function SetupWizard() {
|
||||
const controllers = assignments.filter((a) => a.category === "access");
|
||||
|
||||
return (
|
||||
<section className="mx-auto max-w-3xl px-4 py-6">
|
||||
<section className="px-4 py-6">
|
||||
<h2 className="mb-1 text-h4 font-semibold text-term-text">{t("setup.title")}</h2>
|
||||
<p className="hint mb-4 max-w-prose">{t("setup.intro")}</p>
|
||||
|
||||
|
||||
@@ -1,252 +0,0 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
closeShift,
|
||||
fetchShift,
|
||||
fetchShiftReport,
|
||||
openShift,
|
||||
recordCashVoucher,
|
||||
type ShiftReport,
|
||||
type XReport,
|
||||
} from "./api.js";
|
||||
|
||||
// Manned-mode shift control. Start/End are explicit (not time-based — see
|
||||
// wiki/concepts/shift.md). End Shift signs + prints a Z-report and shows the
|
||||
// totals + the DRAWER picture (opening float carried from the prior shift, cash
|
||||
// taken/added/removed, expected drawer). Operators RAISE a drawer cash voucher
|
||||
// (Mandat Arkëtimi / Mandat Pagese); an admin AUTHORIZES it with their password.
|
||||
// Available to cashier/operator/admin (readonly has no shift).
|
||||
|
||||
const money = (m: number, cur: string | null) => `${(m / 100).toFixed(2)} ${cur ?? ""}`.trim();
|
||||
|
||||
export function ShiftControl({ canVoucher = false }: { canVoucher?: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
const [startedAt, setStartedAt] = useState<string | null>(null);
|
||||
const [drawerMinor, setDrawerMinor] = useState<number | null>(null);
|
||||
const [currency, setCurrency] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [report, setReport] = useState<ShiftReport | null>(null);
|
||||
const [xReport, setXReport] = useState<XReport | null>(null);
|
||||
const [err, setErr] = useState<string | null>(null);
|
||||
|
||||
// Drawer-voucher form. Operator raises; an admin authorizes (name + password).
|
||||
const [moveAmount, setMoveAmount] = useState("");
|
||||
const [moveReason, setMoveReason] = useState("");
|
||||
const [authName, setAuthName] = useState("");
|
||||
const [authPassword, setAuthPassword] = useState("");
|
||||
const [moveMsg, setMoveMsg] = useState<string | null>(null);
|
||||
|
||||
function refresh() {
|
||||
fetchShift()
|
||||
.then((s) => {
|
||||
setStartedAt(s.open?.startedAt ?? null);
|
||||
setDrawerMinor(s.drawerMinor);
|
||||
setCurrency(s.currency);
|
||||
})
|
||||
.catch(() => {
|
||||
/* readonly / not permitted — hide control */
|
||||
});
|
||||
}
|
||||
useEffect(refresh, []);
|
||||
|
||||
async function start() {
|
||||
setBusy(true);
|
||||
setErr(null);
|
||||
setReport(null);
|
||||
setXReport(null);
|
||||
try {
|
||||
const { startedAt } = await openShift();
|
||||
setStartedAt(startedAt);
|
||||
refresh();
|
||||
} catch (e) {
|
||||
setErr((e as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
async function end() {
|
||||
setBusy(true);
|
||||
setErr(null);
|
||||
setXReport(null);
|
||||
try {
|
||||
const z = await closeShift();
|
||||
setReport(z);
|
||||
setStartedAt(null);
|
||||
refresh();
|
||||
} catch (e) {
|
||||
setErr((e as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
// Mid-shift X-report: read-only "takings so far" (appends nothing). Re-fetched on
|
||||
// each click so it's always current.
|
||||
async function viewReport() {
|
||||
setErr(null);
|
||||
try {
|
||||
setXReport(await fetchShiftReport());
|
||||
} catch (e) {
|
||||
setErr((e as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
async function voucher(type: "cash_in" | "cash_out") {
|
||||
setMoveMsg(null);
|
||||
const major = Number(moveAmount);
|
||||
if (!Number.isFinite(major) || major <= 0) {
|
||||
setMoveMsg(t("shift.enterPositive"));
|
||||
return;
|
||||
}
|
||||
if (!authName.trim() || !authPassword) {
|
||||
setMoveMsg(t("shift.authRequired"));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const r = await recordCashVoucher({
|
||||
type,
|
||||
amountMinor: Math.round(major * 100),
|
||||
reason: moveReason.trim(),
|
||||
authorizedBy: authName.trim(),
|
||||
authorizerPassword: authPassword,
|
||||
});
|
||||
setMoveAmount("");
|
||||
setMoveReason("");
|
||||
setAuthPassword("");
|
||||
setMoveMsg(
|
||||
t("shift.voucherRecorded", { no: r.voucherNo, amount: money(r.balanceMinor, currency) }),
|
||||
);
|
||||
refresh();
|
||||
} catch (e) {
|
||||
setMoveMsg((e as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="card mt-6 max-w-md p-4">
|
||||
<div className="flex flex-wrap items-center gap-2 text-[13px]">
|
||||
<strong className="uppercase tracking-wider text-term-muted">{t("shift.label")}</strong>
|
||||
{startedAt ? (
|
||||
<>
|
||||
<span className="font-semibold text-term-green">{t("shift.open")}</span>
|
||||
<span className="text-term-muted">{t("shift.since")} {new Date(startedAt).toLocaleString()}</span>
|
||||
<button type="button" className="btn btn-sm" onClick={viewReport} disabled={busy}>
|
||||
{t("shift.viewTakings")}
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm btn-danger" onClick={end} disabled={busy}>
|
||||
{busy ? t("shift.ending") : t("shift.endShift")}
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className="text-term-muted">{t("shift.notStarted")}</span>
|
||||
<button type="button" className="btn btn-go btn-sm" onClick={start} disabled={busy}>
|
||||
{busy ? t("shift.starting") : t("shift.startShift")}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{/* Live drawer balance (what's in the till right now / inherited). */}
|
||||
{drawerMinor != null && (
|
||||
<div className="mt-2 text-[12px] text-term-text">
|
||||
{t("shift.drawer")} <strong className="tabular-nums">{money(drawerMinor, currency)}</strong>
|
||||
{startedAt && <span className="text-term-muted"> {t("shift.openingFloatInherited")}</span>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{err && <p className="mt-2 text-[12px] text-term-red">{err}</p>}
|
||||
|
||||
{/* Drawer cash voucher: operator RAISES, an admin AUTHORIZES (name + password).
|
||||
cash_in = Mandat Arkëtimi (pay-IN), cash_out = Mandat Pagese (pay-OUT). */}
|
||||
{canVoucher && (
|
||||
<div className="mt-4 border-t border-term-border pt-3">
|
||||
<div className="mb-1.5 text-[11px] uppercase tracking-wider text-term-muted">
|
||||
{t("shift.drawerVoucher")}
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<input
|
||||
className="input w-28"
|
||||
value={moveAmount}
|
||||
onChange={(e) => setMoveAmount(e.target.value)}
|
||||
placeholder={t("shift.amount")}
|
||||
inputMode="decimal"
|
||||
/>
|
||||
<input
|
||||
className="input min-w-36 flex-1"
|
||||
value={moveReason}
|
||||
onChange={(e) => setMoveReason(e.target.value)}
|
||||
placeholder={t("shift.reasonPlaceholder")}
|
||||
/>
|
||||
</div>
|
||||
{/* Admin sign-off — the float can only move with an admin's authorization. */}
|
||||
<div className="mt-2 flex flex-wrap items-center gap-2">
|
||||
<input
|
||||
className="input w-36"
|
||||
value={authName}
|
||||
onChange={(e) => setAuthName(e.target.value)}
|
||||
placeholder={t("shift.authName")}
|
||||
autoComplete="off"
|
||||
/>
|
||||
<input
|
||||
className="input w-36"
|
||||
type="password"
|
||||
value={authPassword}
|
||||
onChange={(e) => setAuthPassword(e.target.value)}
|
||||
placeholder={t("shift.authPassword")}
|
||||
autoComplete="off"
|
||||
/>
|
||||
<button type="button" className="btn btn-go btn-sm" onClick={() => voucher("cash_in")}>
|
||||
{t("shift.mandatArketimi")}
|
||||
</button>
|
||||
<button type="button" className="btn btn-danger btn-sm" onClick={() => voucher("cash_out")}>
|
||||
{t("shift.mandatPagese")}
|
||||
</button>
|
||||
</div>
|
||||
<div className="mt-1 text-[11px] text-term-muted">{t("shift.voucherHint")}</div>
|
||||
{moveMsg && <div className="mt-1.5 text-[12px] text-term-muted">{moveMsg}</div>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Mid-shift X-report — read-only "takings so far" (no event appended). */}
|
||||
{xReport && (
|
||||
<div className="mt-4 rounded-term border border-term-cyan/40 bg-term-bg p-3 text-[12px] tabular-nums">
|
||||
<div className="font-semibold text-term-cyan">{t("shift.xReport")} — {xReport.operator}</div>
|
||||
<div className="text-term-muted">
|
||||
{t("shift.asOf")} {new Date(xReport.asOf).toLocaleString()}
|
||||
</div>
|
||||
<div className="text-term-text">{t("shift.payments")} {xReport.paymentCount}</div>
|
||||
<div className="text-term-text">{t("shift.cash")} {money(xReport.cashTotalMinor, xReport.currency)}</div>
|
||||
<div className="text-term-text">{t("shift.card")} {money(xReport.cardTotalMinor, xReport.currency)}</div>
|
||||
<div className="mt-2 text-[11px] uppercase tracking-wider text-term-muted">{t("shift.drawerSection")}</div>
|
||||
<div className="text-term-text">{t("shift.openingFloat")} {money(xReport.openingFloatMinor, xReport.currency)}</div>
|
||||
<div className="text-term-text">{t("shift.cashTaken")} {money(xReport.cashTotalMinor, xReport.currency)}</div>
|
||||
<div className="text-term-text">{t("shift.cashAdded")} {money(xReport.cashAddedMinor, xReport.currency)}</div>
|
||||
<div className="text-term-text">{t("shift.cashRemoved")} {money(xReport.cashRemovedMinor, xReport.currency)}</div>
|
||||
<div className="font-semibold text-term-text">
|
||||
{t("shift.expectedDrawer")} {money(xReport.expectedDrawerMinor, xReport.currency)}
|
||||
</div>
|
||||
<div className="mt-1 text-[11px] text-term-muted">{t("shift.xReportHint")}</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{report && (
|
||||
<div className="mt-4 rounded-term border border-term-border bg-term-bg p-3 text-[12px] tabular-nums">
|
||||
<div className="font-semibold text-term-text">{t("shift.zReport")} — {report.operator}</div>
|
||||
<div className="text-term-text">{t("shift.payments")} {report.paymentCount}</div>
|
||||
<div className="text-term-text">{t("shift.cash")} {money(report.cashTotalMinor, report.currency)}</div>
|
||||
<div className="text-term-text">{t("shift.card")} {money(report.cardTotalMinor, report.currency)}</div>
|
||||
<div className="mt-2 text-[11px] uppercase tracking-wider text-term-muted">{t("shift.drawerSection")}</div>
|
||||
<div className="text-term-text">{t("shift.openingFloat")} {money(report.openingFloatMinor, report.currency)}</div>
|
||||
<div className="text-term-text">{t("shift.cashTaken")} {money(report.cashTotalMinor, report.currency)}</div>
|
||||
<div className="text-term-text">{t("shift.cashAdded")} {money(report.cashAddedMinor, report.currency)}</div>
|
||||
<div className="text-term-text">{t("shift.cashRemoved")} {money(report.cashRemovedMinor, report.currency)}</div>
|
||||
<div className="font-semibold text-term-text">
|
||||
{t("shift.expectedDrawer")} {money(report.expectedDrawerMinor, report.currency)}
|
||||
</div>
|
||||
<div className={report.printed ? "mt-1 text-term-green" : "mt-1 text-term-amber"}>
|
||||
{report.printed ? t("shift.printedToReceipt") : t("shift.recordedNoPrinter")}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,171 +1,515 @@
|
||||
import { useState } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { fetchShifts, type ShiftSummary, type SessionUser } from "./api.js";
|
||||
import {
|
||||
closeShift,
|
||||
fetchEvents,
|
||||
fetchShift,
|
||||
fetchShiftReport,
|
||||
fetchShifts,
|
||||
openShift,
|
||||
recordCashVoucher,
|
||||
type ShiftReport,
|
||||
type ShiftSummary,
|
||||
type SessionUser,
|
||||
} from "./api.js";
|
||||
import { formatMoney, formatDuration, formatRelativeDateTime } from "./lib/format.js";
|
||||
import { Modal } from "./ui/Modal.js";
|
||||
import type { LedgerEvent } from "@parking/shared";
|
||||
|
||||
// Completed shift history. Scope is enforced SERVER-SIDE by permission: an operator
|
||||
// gets only their own shifts; an admin (shift:cash) gets all + a date/operator
|
||||
// filter. The screen mirrors that — it shows the filter only when the server
|
||||
// reports scope:"all". Each row is one signed shift_z_report; expanding it shows the
|
||||
// drawer reconciliation. See wiki/concepts/shift.md.
|
||||
// Shift hub — a two-pane master/detail. LEFT: the open/CURRENT shift (when any) plus
|
||||
// completed shifts, filterable by a timeframe preset and (admin) by operator. RIGHT: the
|
||||
// selected shift's signed activity log (every ledger event in its window). The current
|
||||
// shift's pane carries the shift ACTIONS (End shift / drawer voucher / takings-so-far),
|
||||
// each opening a modal. Scope is enforced SERVER-SIDE: an operator sees only their own;
|
||||
// an admin (shift:cash) sees all. See wiki/concepts/shift.md.
|
||||
|
||||
function money(minor: number, currency: string | null): string {
|
||||
return currency ? formatMoney(minor, currency) : (minor / 100).toFixed(2);
|
||||
}
|
||||
|
||||
export function ShiftsHistory({ user }: { user: SessionUser | null }) {
|
||||
const { t } = useTranslation();
|
||||
// Admin filter inputs (only sent when the server grants the "all" scope; for an
|
||||
// operator the server ignores them anyway).
|
||||
const [operator, setOperator] = useState("");
|
||||
const [from, setFrom] = useState("");
|
||||
const [to, setTo] = useState("");
|
||||
// The applied filter (separate from the inputs, so typing doesn't refetch).
|
||||
const [applied, setApplied] = useState<{ operator?: string; from?: string; to?: string }>({});
|
||||
// Event styling for the activity log (mirrors the booth live feed).
|
||||
const EVENT_STYLE: Record<string, { labelKey: string; color: string }> = {
|
||||
vehicle_entry: { labelKey: "booth.evtEntry", color: "text-term-green" },
|
||||
vehicle_exit: { labelKey: "booth.evtExit", color: "text-term-red" },
|
||||
payment: { labelKey: "booth.evtPay", color: "text-term-cyan" },
|
||||
void: { labelKey: "booth.evtVoid", color: "text-term-amber" },
|
||||
barrier_open_command: { labelKey: "booth.evtOpenCmd", color: "text-term-muted" },
|
||||
barrier_open_observed: { labelKey: "booth.evtOpenObserved", color: "text-term-muted" },
|
||||
shift_open: { labelKey: "booth.evtShiftOpen", color: "text-term-amber" },
|
||||
shift_z_report: { labelKey: "booth.evtShiftZ", color: "text-term-amber" },
|
||||
cash_movement: { labelKey: "booth.evtCashMovement", color: "text-term-cyan" },
|
||||
cash_in: { labelKey: "booth.evtCashIn", color: "text-term-green" },
|
||||
cash_out: { labelKey: "booth.evtCashOut", color: "text-term-amber" },
|
||||
anomaly: { labelKey: "booth.evtAnomaly", color: "text-term-red" },
|
||||
};
|
||||
|
||||
const q = useQuery({
|
||||
queryKey: ["shifts", applied],
|
||||
queryFn: () => fetchShifts(applied),
|
||||
type Preset = "yesterday" | "week" | "month" | "custom" | "all";
|
||||
|
||||
/** A preset → an inclusive [from, to] date window (yyyy-mm-dd) over the shift START. */
|
||||
function presetRange(p: Preset): { from: string; to: string } | null {
|
||||
if (p === "all" || p === "custom") return null;
|
||||
const now = new Date();
|
||||
const iso = (d: Date) => d.toISOString().slice(0, 10);
|
||||
if (p === "yesterday") {
|
||||
const y = new Date(now);
|
||||
y.setDate(y.getDate() - 1);
|
||||
return { from: iso(y), to: iso(y) };
|
||||
}
|
||||
const from = new Date(now);
|
||||
from.setDate(from.getDate() - (p === "week" ? 7 : 30));
|
||||
return { from: iso(from), to: iso(now) };
|
||||
}
|
||||
|
||||
/** The CURRENT (open) shift, synthesized from the X-report so it lists alongside closed
|
||||
* shifts. `id` is a sentinel; `open` marks it for the badge + the action pane. null when
|
||||
* no shift is open (or not visible to the requester). */
|
||||
function useCurrentShift(): { current: (ShiftSummary & { open: true }) | null; isMine: boolean; refetch: () => void } {
|
||||
const status = useQuery({ queryKey: ["shift", "current"], queryFn: fetchShift });
|
||||
const report = useQuery({
|
||||
queryKey: ["shift", "xreport"],
|
||||
queryFn: fetchShiftReport,
|
||||
enabled: status.data?.open != null,
|
||||
});
|
||||
const refetch = () => {
|
||||
void status.refetch();
|
||||
void report.refetch();
|
||||
};
|
||||
if (!status.data?.open || !report.data) return { current: null, isMine: status.data?.isMine ?? false, refetch };
|
||||
const x = report.data;
|
||||
return {
|
||||
isMine: status.data.isMine,
|
||||
refetch,
|
||||
current: {
|
||||
id: "__current__",
|
||||
index: Number.MAX_SAFE_INTEGER,
|
||||
operator: x.operator,
|
||||
startedAt: x.startedAt,
|
||||
endedAt: x.asOf,
|
||||
cashTotalMinor: x.cashTotalMinor,
|
||||
cardTotalMinor: x.cardTotalMinor,
|
||||
currency: x.currency,
|
||||
paymentCount: x.paymentCount,
|
||||
openingFloatMinor: x.openingFloatMinor,
|
||||
cashAddedMinor: x.cashAddedMinor,
|
||||
cashRemovedMinor: x.cashRemovedMinor,
|
||||
expectedDrawerMinor: x.expectedDrawerMinor,
|
||||
open: true,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function ShiftsHistory({ user, canManage = false, canVoucher = false }: { user: SessionUser | null; canManage?: boolean; canVoucher?: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
const [preset, setPreset] = useState<Preset>("week");
|
||||
const [operator, setOperator] = useState("");
|
||||
const [customFrom, setCustomFrom] = useState("");
|
||||
const [customTo, setCustomTo] = useState("");
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||
|
||||
const { current, isMine, refetch: refetchCurrent } = useCurrentShift();
|
||||
|
||||
const range = preset === "custom" ? { from: customFrom, to: customTo } : presetRange(preset);
|
||||
const applied = {
|
||||
operator: operator.trim() || undefined,
|
||||
from: range?.from ? new Date(`${range.from}T00:00:00`).toISOString() : undefined,
|
||||
to: range?.to ? new Date(`${range.to}T23:59:59`).toISOString() : undefined,
|
||||
};
|
||||
|
||||
const q = useQuery({ queryKey: ["shifts", applied], queryFn: () => fetchShifts(applied) });
|
||||
const isAdmin = q.data?.scope === "all";
|
||||
const shifts = q.data?.shifts ?? [];
|
||||
const closed = q.data?.shifts ?? [];
|
||||
|
||||
function apply() {
|
||||
setApplied({
|
||||
operator: operator.trim() || undefined,
|
||||
// A date input gives yyyy-mm-dd; widen `to` to the end of that day.
|
||||
from: from ? new Date(`${from}T00:00:00`).toISOString() : undefined,
|
||||
to: to ? new Date(`${to}T23:59:59`).toISOString() : undefined,
|
||||
});
|
||||
}
|
||||
function clear() {
|
||||
setOperator("");
|
||||
setFrom("");
|
||||
setTo("");
|
||||
setApplied({});
|
||||
// The current/open shift sits at the TOP of the list (when present + visible to me).
|
||||
const list: (ShiftSummary & { open?: boolean })[] = current && (isMine || isAdmin) ? [current, ...closed] : closed;
|
||||
const selected = list.find((s) => s.id === selectedId) ?? list[0] ?? null;
|
||||
|
||||
// Default the selection to the current shift (if any), else the newest closed one.
|
||||
useEffect(() => {
|
||||
if (list.length === 0) setSelectedId(null);
|
||||
else if (!list.some((s) => s.id === selectedId)) setSelectedId(list[0]!.id);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [q.data, current?.id]);
|
||||
|
||||
function refreshAll() {
|
||||
void q.refetch();
|
||||
refetchCurrent();
|
||||
}
|
||||
|
||||
const PRESETS: Preset[] = ["yesterday", "week", "month", "all", "custom"];
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-4xl">
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<div>
|
||||
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
|
||||
<h1 className="text-sm font-bold uppercase tracking-widest text-term-amber">
|
||||
{isAdmin ? t("shifts.title") : t("shifts.myTitle")}
|
||||
</h1>
|
||||
{/* No shift open → the only action is to start one (gated on shift:create). */}
|
||||
{canManage && !current && (
|
||||
<StartShiftButton onDone={refreshAll} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Admin-only filter: by operator + a date window over the shift start. */}
|
||||
{isAdmin && (
|
||||
<div className="card mb-3 flex flex-wrap items-end gap-3 p-3">
|
||||
{/* Filters: timeframe presets (everyone) + operator (admin only). */}
|
||||
<div className="card mb-3 flex flex-wrap items-end gap-3 p-3">
|
||||
<div className="field">
|
||||
<span className="label">{t("shifts.timeframe")}</span>
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{PRESETS.map((p) => (
|
||||
<button key={p} type="button" className={`btn btn-sm ${preset === p ? "btn-primary" : ""}`} onClick={() => setPreset(p)}>
|
||||
{t(`shifts.preset_${p}`)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
{preset === "custom" && (
|
||||
<>
|
||||
<div className="field">
|
||||
<span className="label">{t("shifts.filterFrom")}</span>
|
||||
<input type="date" className="input w-40" value={customFrom} onChange={(e) => setCustomFrom(e.target.value)} />
|
||||
</div>
|
||||
<div className="field">
|
||||
<span className="label">{t("shifts.filterTo")}</span>
|
||||
<input type="date" className="input w-40" value={customTo} onChange={(e) => setCustomTo(e.target.value)} />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{isAdmin && (
|
||||
<div className="field">
|
||||
<span className="label">{t("shifts.operator")}</span>
|
||||
<input
|
||||
className="input w-44"
|
||||
value={operator}
|
||||
onChange={(e) => setOperator(e.target.value)}
|
||||
placeholder={t("shifts.allOperators")}
|
||||
/>
|
||||
<input className="input w-44" value={operator} onChange={(e) => setOperator(e.target.value)} placeholder={t("shifts.allOperators")} />
|
||||
</div>
|
||||
<div className="field">
|
||||
<span className="label">{t("shifts.filterFrom")}</span>
|
||||
<input type="date" className="input w-44" value={from} onChange={(e) => setFrom(e.target.value)} />
|
||||
</div>
|
||||
<div className="field">
|
||||
<span className="label">{t("shifts.filterTo")}</span>
|
||||
<input type="date" className="input w-44" value={to} onChange={(e) => setTo(e.target.value)} />
|
||||
</div>
|
||||
<button type="button" className="btn btn-primary btn-sm" onClick={apply}>
|
||||
{t("shifts.apply")}
|
||||
</button>
|
||||
<button type="button" className="btn btn-sm" onClick={clear}>
|
||||
{t("shifts.clear")}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
)}
|
||||
</div>
|
||||
|
||||
{q.isError && (
|
||||
<div className="mb-2 rounded-term border border-term-red px-3 py-2 text-[12px] text-term-red">
|
||||
{t("shifts.loadFailed")}
|
||||
</div>
|
||||
<div className="mb-2 rounded-term border border-term-red px-3 py-2 text-[12px] text-term-red">{t("shifts.loadFailed")}</div>
|
||||
)}
|
||||
|
||||
<div className="overflow-hidden rounded-term border border-term-border">
|
||||
<table className="w-full text-[12px] tabular-nums">
|
||||
<thead className="bg-term-panel-2 text-[11px] uppercase tracking-wider text-term-muted">
|
||||
<tr>
|
||||
{isAdmin && <th className="px-3 py-1.5 text-left">{t("shifts.operator")}</th>}
|
||||
<th className="px-3 py-1.5 text-left">{t("shifts.started")}</th>
|
||||
<th className="px-3 py-1.5 text-left">{t("shifts.ended")}</th>
|
||||
<th className="px-3 py-1.5 text-right">{t("shifts.payments")}</th>
|
||||
<th className="px-3 py-1.5 text-right">{t("shifts.cash")}</th>
|
||||
<th className="px-3 py-1.5 text-right">{t("shifts.card")}</th>
|
||||
<th className="px-3 py-1.5 text-right">{t("shifts.expectedDrawer")}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{shifts.map((s) => (
|
||||
<ShiftRow key={s.id} s={s} showOperator={isAdmin} colSpan={isAdmin ? 7 : 6} />
|
||||
))}
|
||||
{!q.isLoading && shifts.length === 0 && (
|
||||
<tr>
|
||||
<td colSpan={isAdmin ? 7 : 6} className="px-3 py-3 text-term-muted">
|
||||
{t("shifts.none")}
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
{/* Two-pane: shift list (left) + selected shift's activity log (right). */}
|
||||
<div className="grid gap-3 md:grid-cols-[minmax(0,1fr)_minmax(0,1.6fr)]">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
{!q.isLoading && list.length === 0 && (
|
||||
<p className="rounded-term border border-term-border px-3 py-3 text-[12px] text-term-muted">{t("shifts.none")}</p>
|
||||
)}
|
||||
{list.map((s) => (
|
||||
<ShiftCard key={s.id} s={s} showOperator={isAdmin} open={!!s.open} selected={selected?.id === s.id} onClick={() => setSelectedId(s.id)} />
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="rounded-term border border-term-border">
|
||||
{selected ? (
|
||||
<ShiftActivityLog
|
||||
shift={selected}
|
||||
isCurrent={!!selected.open}
|
||||
isMine={isMine}
|
||||
showOperator={isAdmin}
|
||||
canManage={canManage}
|
||||
canVoucher={canVoucher}
|
||||
onChanged={refreshAll}
|
||||
/>
|
||||
) : (
|
||||
<p className="px-3 py-6 text-center text-[12px] text-term-muted">{t("shifts.selectAShift")}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ShiftRow({ s, showOperator, colSpan }: { s: ShiftSummary; showOperator: boolean; colSpan: number }) {
|
||||
function StartShiftButton({ onDone }: { onDone: () => void }) {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
const cur = s.currency;
|
||||
const when = (iso: string) => formatRelativeDateTime(iso, t);
|
||||
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [err, setErr] = useState<string | null>(null);
|
||||
async function start() {
|
||||
setBusy(true);
|
||||
setErr(null);
|
||||
try {
|
||||
await openShift();
|
||||
onDone();
|
||||
} catch (e) {
|
||||
setErr((e as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<tr
|
||||
className="cursor-pointer border-t border-term-border hover:bg-term-panel-2"
|
||||
onClick={() => setOpen((o) => !o)}
|
||||
>
|
||||
{showOperator && <td className="px-3 py-1.5 text-term-text">{s.operator}</td>}
|
||||
<td className="px-3 py-1.5">{when(s.startedAt)}</td>
|
||||
<td className="px-3 py-1.5">
|
||||
{when(s.endedAt)}
|
||||
<span className="ml-2 text-term-muted">{formatDuration(s.startedAt, s.endedAt)}</span>
|
||||
</td>
|
||||
<td className="px-3 py-1.5 text-right">{s.paymentCount}</td>
|
||||
<td className="px-3 py-1.5 text-right text-term-green">{money(s.cashTotalMinor, cur)}</td>
|
||||
<td className="px-3 py-1.5 text-right text-term-cyan">{money(s.cardTotalMinor, cur)}</td>
|
||||
<td className="px-3 py-1.5 text-right font-semibold">{money(s.expectedDrawerMinor, cur)}</td>
|
||||
</tr>
|
||||
{open && (
|
||||
<tr className="border-t border-term-border/50 bg-term-bg">
|
||||
<td colSpan={colSpan} className="px-3 py-2">
|
||||
<div className="text-[11px] uppercase tracking-wider text-term-muted">{t("shifts.drawerSection")}</div>
|
||||
<div className="mt-1 grid grid-cols-2 gap-x-8 gap-y-0.5 sm:grid-cols-4">
|
||||
<Figure label={t("shifts.openingFloat")} value={money(s.openingFloatMinor, cur)} />
|
||||
<Figure label={t("shifts.cashTaken")} value={money(s.cashTotalMinor, cur)} />
|
||||
<Figure label={t("shifts.cashAdded")} value={money(s.cashAddedMinor, cur)} />
|
||||
<Figure label={t("shifts.cashRemoved")} value={money(s.cashRemovedMinor, cur)} />
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</>
|
||||
<span className="flex items-center gap-2">
|
||||
{err && <span className="text-[12px] text-term-red">{err}</span>}
|
||||
<button type="button" className="btn btn-go btn-sm" onClick={start} disabled={busy}>
|
||||
{busy ? t("shift.starting") : t("shift.startShift")}
|
||||
</button>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function Figure({ label, value }: { label: string; value: string }) {
|
||||
function ShiftCard({ s, showOperator, open, selected, onClick }: { s: ShiftSummary; showOperator: boolean; open: boolean; selected: boolean; onClick: () => void }) {
|
||||
const { t } = useTranslation();
|
||||
const cur = s.currency;
|
||||
const when = (iso: string) => formatRelativeDateTime(iso, t);
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
className={`card w-full p-2.5 text-left text-[12px] transition-colors ${selected ? "border-term-amber bg-term-panel-2" : "hover:bg-term-panel-2"}`}
|
||||
>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="flex items-center gap-2 font-semibold text-term-text">
|
||||
{open && <span className="rounded border border-term-green px-1 text-[10px] text-term-green">{t("shifts.current")}</span>}
|
||||
{showOperator ? s.operator : when(s.startedAt)}
|
||||
</span>
|
||||
<span className="text-term-muted">{formatDuration(s.startedAt, s.endedAt)}</span>
|
||||
</div>
|
||||
{showOperator && <div className="text-term-muted">{when(s.startedAt)}</div>}
|
||||
<div className="mt-1 flex flex-wrap gap-x-3 tabular-nums">
|
||||
<span className="text-term-muted">{t("shifts.payments")} {s.paymentCount}</span>
|
||||
<span className="text-term-green">{money(s.cashTotalMinor, cur)}</span>
|
||||
<span className="text-term-cyan">{money(s.cardTotalMinor, cur)}</span>
|
||||
<span className="ml-auto font-semibold text-term-text" title={t("shifts.expectedDrawer")}>{money(s.expectedDrawerMinor, cur)}</span>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function ShiftActivityLog({
|
||||
shift,
|
||||
isCurrent,
|
||||
isMine,
|
||||
showOperator,
|
||||
canManage,
|
||||
canVoucher,
|
||||
onChanged,
|
||||
}: {
|
||||
shift: ShiftSummary;
|
||||
isCurrent: boolean;
|
||||
isMine: boolean;
|
||||
showOperator: boolean;
|
||||
canManage: boolean;
|
||||
canVoucher: boolean;
|
||||
onChanged: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [modal, setModal] = useState<null | "end" | "voucher" | "takings">(null);
|
||||
|
||||
// The current shift's log runs entry→now (no upper bound); a closed shift is bounded.
|
||||
const q = useQuery({
|
||||
queryKey: ["shift-events", shift.id, shift.endedAt],
|
||||
queryFn: () => fetchEvents(1000, shift.startedAt, isCurrent ? undefined : shift.endedAt),
|
||||
refetchInterval: isCurrent ? 5000 : false,
|
||||
});
|
||||
const events = q.data?.events ?? [];
|
||||
const cur = shift.currency;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="border-b border-term-border bg-term-panel-2 px-3 py-2">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 text-[12px]">
|
||||
<span className="flex items-center gap-2 font-semibold text-term-text">
|
||||
{isCurrent && <span className="rounded border border-term-green px-1 text-[10px] text-term-green">{t("shifts.current")}</span>}
|
||||
{showOperator && `${shift.operator} · `}
|
||||
{formatRelativeDateTime(shift.startedAt, t)}
|
||||
{!isCurrent && ` → ${formatRelativeDateTime(shift.endedAt, t)}`}
|
||||
</span>
|
||||
{/* Actions live on the CURRENT shift's pane (when it's mine), each → a modal. */}
|
||||
{isCurrent && isMine && canManage && (
|
||||
<span className="flex flex-wrap gap-1.5">
|
||||
<button type="button" className="btn btn-sm" onClick={() => setModal("takings")}>{t("shift.viewTakings")}</button>
|
||||
{canVoucher && <button type="button" className="btn btn-sm" onClick={() => setModal("voucher")}>{t("shift.drawerVoucher")}</button>}
|
||||
<button type="button" className="btn btn-sm btn-danger" onClick={() => setModal("end")}>{t("shift.endShift")}</button>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-1 grid grid-cols-2 gap-x-6 gap-y-0.5 text-[11px] tabular-nums sm:grid-cols-4">
|
||||
<Figure label={t("shifts.openingFloat")} value={money(shift.openingFloatMinor, cur)} />
|
||||
<Figure label={t("shifts.cashTaken")} value={money(shift.cashTotalMinor, cur)} />
|
||||
<Figure label={t("shifts.cashAdded")} value={money(shift.cashAddedMinor, cur)} />
|
||||
<Figure label={t("shifts.cashRemoved")} value={money(shift.cashRemovedMinor, cur)} />
|
||||
<Figure label={t("shifts.card")} value={money(shift.cardTotalMinor, cur)} />
|
||||
<Figure label={t("shifts.expectedDrawer")} value={money(shift.expectedDrawerMinor, cur)} bold />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="max-h-[62vh] overflow-y-auto">
|
||||
{q.isLoading && <p className="px-3 py-3 text-[12px] text-term-muted">{t("common.loading")}</p>}
|
||||
{!q.isLoading && events.length === 0 && <p className="px-3 py-3 text-[12px] text-term-muted">{t("shifts.noActivity")}</p>}
|
||||
{events.map((e) => (
|
||||
<ActivityRow key={e.id} e={e} />
|
||||
))}
|
||||
</div>
|
||||
|
||||
{modal === "end" && <EndShiftModal shift={shift} onClose={() => setModal(null)} onDone={onChanged} />}
|
||||
{modal === "voucher" && <VoucherModal currency={cur} onClose={() => setModal(null)} onDone={onChanged} />}
|
||||
{modal === "takings" && <TakingsModal onClose={() => setModal(null)} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// --- Action modals ---------------------------------------------------------
|
||||
|
||||
function EndShiftModal({ shift, onClose, onDone }: { shift: ShiftSummary; onClose: () => void; onDone: () => void }) {
|
||||
const { t } = useTranslation();
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [report, setReport] = useState<ShiftReport | null>(null);
|
||||
const [err, setErr] = useState<string | null>(null);
|
||||
const cur = shift.currency;
|
||||
|
||||
async function confirm() {
|
||||
setBusy(true);
|
||||
setErr(null);
|
||||
try {
|
||||
setReport(await closeShift());
|
||||
onDone();
|
||||
} catch (e) {
|
||||
setErr((e as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal open onClose={onClose} title={t("shift.endShift")} width="max-w-md">
|
||||
{report ? (
|
||||
// Result — the signed Z-report.
|
||||
<div className="text-[13px] tabular-nums">
|
||||
<div className="font-semibold text-term-text">{t("shift.zReport")} — {report.operator}</div>
|
||||
<div className="mt-1 grid grid-cols-2 gap-x-6 gap-y-0.5">
|
||||
<Figure label={t("shift.payments")} value={String(report.paymentCount)} />
|
||||
<Figure label={t("shift.cash")} value={money(report.cashTotalMinor, report.currency)} />
|
||||
<Figure label={t("shift.card")} value={money(report.cardTotalMinor, report.currency)} />
|
||||
<Figure label={t("shift.openingFloat")} value={money(report.openingFloatMinor, report.currency)} />
|
||||
<Figure label={t("shift.cashAdded")} value={money(report.cashAddedMinor, report.currency)} />
|
||||
<Figure label={t("shift.cashRemoved")} value={money(report.cashRemovedMinor, report.currency)} />
|
||||
<Figure label={t("shift.expectedDrawer")} value={money(report.expectedDrawerMinor, report.currency)} bold />
|
||||
</div>
|
||||
<div className={report.printed ? "mt-2 text-term-green" : "mt-2 text-term-amber"}>
|
||||
{report.printed ? t("shift.printedToReceipt") : t("shift.recordedNoPrinter")}
|
||||
</div>
|
||||
<div className="mt-3 flex justify-end">
|
||||
<button type="button" className="btn btn-sm" onClick={onClose}>{t("common.close")}</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
// Confirm — show the live takings/drawer before closing.
|
||||
<div className="text-[13px] tabular-nums">
|
||||
<p className="text-term-muted">{t("shift.endConfirm")}</p>
|
||||
<div className="mt-2 grid grid-cols-2 gap-x-6 gap-y-0.5">
|
||||
<Figure label={t("shift.cash")} value={money(shift.cashTotalMinor, cur)} />
|
||||
<Figure label={t("shift.card")} value={money(shift.cardTotalMinor, cur)} />
|
||||
<Figure label={t("shift.expectedDrawer")} value={money(shift.expectedDrawerMinor, cur)} bold />
|
||||
</div>
|
||||
{err && <p className="mt-2 text-[12px] text-term-red">{err}</p>}
|
||||
<div className="mt-3 flex justify-end gap-2">
|
||||
<button type="button" className="btn btn-sm" onClick={onClose}>{t("subs.cancel")}</button>
|
||||
<button type="button" className="btn btn-sm btn-danger" onClick={confirm} disabled={busy}>
|
||||
{busy ? t("shift.ending") : t("shift.endShift")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
function VoucherModal({ currency, onClose, onDone }: { currency: string | null; onClose: () => void; onDone: () => void }) {
|
||||
const { t } = useTranslation();
|
||||
const [amount, setAmount] = useState("");
|
||||
const [reason, setReason] = useState("");
|
||||
const [authName, setAuthName] = useState("");
|
||||
const [authPassword, setAuthPassword] = useState("");
|
||||
const [msg, setMsg] = useState<string | null>(null);
|
||||
|
||||
async function submit(type: "cash_in" | "cash_out") {
|
||||
setMsg(null);
|
||||
const major = Number(amount);
|
||||
if (!Number.isFinite(major) || major <= 0) return setMsg(t("shift.enterPositive"));
|
||||
if (!authName.trim() || !authPassword) return setMsg(t("shift.authRequired"));
|
||||
try {
|
||||
const r = await recordCashVoucher({ type, amountMinor: Math.round(major * 100), reason: reason.trim(), authorizedBy: authName.trim(), authorizerPassword: authPassword });
|
||||
setMsg(t("shift.voucherRecorded", { no: r.voucherNo, amount: money(r.balanceMinor, currency) }));
|
||||
setAmount("");
|
||||
setReason("");
|
||||
setAuthPassword("");
|
||||
onDone();
|
||||
} catch (e) {
|
||||
setMsg((e as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal open onClose={onClose} title={t("shift.drawerVoucher")} width="max-w-md">
|
||||
<div className="flex flex-col gap-2 text-[13px]">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<input className="input w-28" value={amount} onChange={(e) => setAmount(e.target.value)} placeholder={t("shift.amount")} inputMode="decimal" />
|
||||
<input className="input min-w-36 flex-1" value={reason} onChange={(e) => setReason(e.target.value)} placeholder={t("shift.reasonPlaceholder")} />
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<input className="input w-36" value={authName} onChange={(e) => setAuthName(e.target.value)} placeholder={t("shift.authName")} autoComplete="off" />
|
||||
<input className="input w-36" type="password" value={authPassword} onChange={(e) => setAuthPassword(e.target.value)} placeholder={t("shift.authPassword")} autoComplete="off" />
|
||||
</div>
|
||||
<div className="text-[11px] text-term-muted">{t("shift.voucherHint")}</div>
|
||||
{msg && <div className="text-[12px] text-term-muted">{msg}</div>}
|
||||
<div className="mt-1 flex justify-end gap-2">
|
||||
<button type="button" className="btn btn-sm" onClick={onClose}>{t("common.close")}</button>
|
||||
<button type="button" className="btn btn-go btn-sm" onClick={() => submit("cash_in")}>{t("shift.mandatArketimi")}</button>
|
||||
<button type="button" className="btn btn-danger btn-sm" onClick={() => submit("cash_out")}>{t("shift.mandatPagese")}</button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
function TakingsModal({ onClose }: { onClose: () => void }) {
|
||||
const { t } = useTranslation();
|
||||
const q = useQuery({ queryKey: ["shift", "xreport", "modal"], queryFn: fetchShiftReport });
|
||||
const x = q.data;
|
||||
return (
|
||||
<Modal open onClose={onClose} title={t("shift.xReport")} width="max-w-md">
|
||||
{!x ? (
|
||||
<p className="text-[12px] text-term-muted">{t("common.loading")}</p>
|
||||
) : (
|
||||
<div className="text-[13px] tabular-nums">
|
||||
<div className="text-term-muted">{t("shift.asOf")} {new Date(x.asOf).toLocaleString()}</div>
|
||||
<div className="mt-1 grid grid-cols-2 gap-x-6 gap-y-0.5">
|
||||
<Figure label={t("shift.payments")} value={String(x.paymentCount)} />
|
||||
<Figure label={t("shift.cash")} value={money(x.cashTotalMinor, x.currency)} />
|
||||
<Figure label={t("shift.card")} value={money(x.cardTotalMinor, x.currency)} />
|
||||
<Figure label={t("shift.openingFloat")} value={money(x.openingFloatMinor, x.currency)} />
|
||||
<Figure label={t("shift.cashAdded")} value={money(x.cashAddedMinor, x.currency)} />
|
||||
<Figure label={t("shift.cashRemoved")} value={money(x.cashRemovedMinor, x.currency)} />
|
||||
<Figure label={t("shift.expectedDrawer")} value={money(x.expectedDrawerMinor, x.currency)} bold />
|
||||
</div>
|
||||
<div className="mt-2 text-[11px] text-term-muted">{t("shift.xReportHint")}</div>
|
||||
<div className="mt-3 flex justify-end">
|
||||
<button type="button" className="btn btn-sm" onClick={onClose}>{t("common.close")}</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
function ActivityRow({ e }: { e: LedgerEvent }) {
|
||||
const { t } = useTranslation();
|
||||
const style = EVENT_STYLE[e.type] ?? { labelKey: "", color: "text-term-text" };
|
||||
const time = new Date(e.occurredAt).toLocaleTimeString();
|
||||
const p = e.payload ?? {};
|
||||
const amount = typeof p.amountMinor === "number" && p.amountMinor !== 0 ? money(p.amountMinor, (p.currency as string) ?? null) : null;
|
||||
const actor = (e.subscriberLabel as string | undefined) ?? e.identity ?? (p.sessionRef as string | undefined) ?? "";
|
||||
return (
|
||||
<div className="flex items-center gap-2 border-t border-term-border/60 px-3 py-1.5 text-[12px] first:border-t-0">
|
||||
<span className="w-16 shrink-0 tabular-nums text-term-muted">{time}</span>
|
||||
<span className={`w-20 shrink-0 font-semibold uppercase ${style.color}`}>{style.labelKey ? t(style.labelKey) : e.type}</span>
|
||||
<span className="min-w-0 flex-1 truncate text-term-text" title={actor}>{actor}</span>
|
||||
{amount && <span className="shrink-0 tabular-nums text-term-cyan">{amount}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Figure({ label, value, bold }: { label: string; value: string; bold?: boolean }) {
|
||||
return (
|
||||
<div className="flex justify-between gap-2">
|
||||
<span className="text-term-muted">{label}</span>
|
||||
<span className="text-term-text">{value}</span>
|
||||
<span className={bold ? "font-semibold text-term-text" : "text-term-text"}>{value}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -353,7 +353,7 @@ export function SubscriptionManager() {
|
||||
if (!subs) return null;
|
||||
|
||||
return (
|
||||
<section className="mx-auto max-w-3xl px-4 py-6">
|
||||
<section className="px-4 py-6">
|
||||
<h2 className="mb-3 text-h4 font-semibold text-term-text">{t("subs.title")}</h2>
|
||||
<ul className="mb-3 list-none p-0">
|
||||
{subs.map((s) => (
|
||||
|
||||
@@ -235,7 +235,7 @@ export function SubscriptionPlansManager() {
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="mx-auto max-w-2xl px-4 py-6">
|
||||
<section className="px-4 py-6">
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<h3 className="text-[13px] font-semibold uppercase tracking-wider text-term-muted">{t("plans.title")}</h3>
|
||||
<button type="button" className="btn btn-go btn-sm" onClick={() => setForm(emptyForm())}>
|
||||
|
||||
@@ -351,7 +351,7 @@ export function TariffComposer() {
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="mx-auto max-w-3xl px-4 py-6">
|
||||
<section className="px-4 py-6">
|
||||
<h2 className="mb-1 text-h4 font-semibold text-term-text">{t("tariff.title")}</h2>
|
||||
{!state?.active ? (
|
||||
<p className="mb-4 rounded-term border border-term-amber/50 bg-term-amber/10 px-3 py-2 text-[12px] text-term-amber">
|
||||
|
||||
@@ -113,7 +113,7 @@ export function TariffLab() {
|
||||
const currency = result?.currency ?? state?.active?.currency ?? "ALL";
|
||||
|
||||
return (
|
||||
<section className="mx-auto max-w-3xl px-4 py-6">
|
||||
<section className="px-4 py-6">
|
||||
<h2 className="mb-1 text-h4 font-semibold text-term-text">{t("lab.title")}</h2>
|
||||
<p className="hint mb-4">{t("lab.intro")}</p>
|
||||
|
||||
|
||||
@@ -41,7 +41,7 @@ export function UsersManager({ user }: { user: SessionUser | null }) {
|
||||
setError(e instanceof ApiError ? e.message : (e as Error).message);
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-3xl">
|
||||
<div className="">
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<h1 className="text-sm font-bold uppercase tracking-widest text-term-amber">{t("users.title")}</h1>
|
||||
{canCreate && roles.length > 0 && (
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
// wiki/entities/local-jwt-auth.md.
|
||||
|
||||
import { logFailedRequest } from "./lib/logger.js";
|
||||
import { apiUrl } from "./lib/origin.js";
|
||||
import type { AppLogRecord } from "@parking/shared";
|
||||
|
||||
const CSRF_COOKIE = "parking_csrf";
|
||||
@@ -27,7 +28,7 @@ export async function apiFetch<T>(path: string, init: RequestInit = {}): Promise
|
||||
const csrf = readCookie(CSRF_COOKIE);
|
||||
if (csrf) headers.set(CSRF_HEADER, csrf);
|
||||
}
|
||||
const res = await fetch(path, { ...init, headers, credentials: "include" });
|
||||
const res = await fetch(apiUrl(path), { ...init, headers, credentials: "include" });
|
||||
if (!res.ok) {
|
||||
const msg = (await res.json().catch(() => ({}))) as { error?: string; problems?: string[] };
|
||||
const error = msg.error ?? `${path}: ${res.status}`;
|
||||
@@ -862,9 +863,11 @@ export type { AppLogRecord };
|
||||
export function fetchEvents(
|
||||
limit = 100,
|
||||
since?: string,
|
||||
until?: string,
|
||||
): Promise<{ events: import("@parking/shared").LedgerEvent[] }> {
|
||||
const qs = new URLSearchParams({ limit: String(limit) });
|
||||
if (since) qs.set("since", since);
|
||||
if (until) qs.set("until", until);
|
||||
return apiFetch(`/api/events?${qs.toString()}`);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
// Desktop auto-update — prompt-on-update flow.
|
||||
//
|
||||
// Runs ONLY inside the Tauri desktop shell; a plain browser has no updater, so
|
||||
// this is a guarded no-op there. On launch it checks the configured update
|
||||
// endpoint (tauri.conf.json → plugins.updater); if a signed newer version is
|
||||
// available it asks the operator, then downloads + installs and relaunches.
|
||||
//
|
||||
// The plugins are imported dynamically so the browser build never bundles them
|
||||
// and never tries to resolve the Tauri APIs. Offline-first: a failed check (no
|
||||
// network — the appliance is usually offline) is swallowed; updates only happen
|
||||
// when someone has brought the box online (e.g. a phone hotspot) on purpose.
|
||||
|
||||
/** True when running inside the Tauri webview (not a normal browser). */
|
||||
function inTauri(): boolean {
|
||||
return typeof window !== "undefined" && "__TAURI_INTERNALS__" in window;
|
||||
}
|
||||
|
||||
export interface UpdatePrompt {
|
||||
/** Newer version string offered by the server. */
|
||||
version: string;
|
||||
/** Release notes, if the server provided them. */
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check for an update. If one is available, calls `confirm` (your UI) with the
|
||||
* version/notes; when it resolves true, downloads + installs and relaunches.
|
||||
* No-op (resolves silently) in the browser or when no update / offline.
|
||||
*/
|
||||
export async function checkForDesktopUpdate(
|
||||
confirm: (info: UpdatePrompt) => Promise<boolean>,
|
||||
): Promise<void> {
|
||||
if (!inTauri()) return;
|
||||
try {
|
||||
const { check } = await import("@tauri-apps/plugin-updater");
|
||||
const update = await check();
|
||||
if (!update) return; // up to date
|
||||
|
||||
const accepted = await confirm({ version: update.version, notes: update.body });
|
||||
if (!accepted) return;
|
||||
|
||||
// Download + install the signed update (signature verified against the
|
||||
// pubkey in tauri.conf.json), then relaunch into the new version.
|
||||
await update.downloadAndInstall();
|
||||
const { relaunch } = await import("@tauri-apps/plugin-process");
|
||||
await relaunch();
|
||||
} catch {
|
||||
// Offline / endpoint unreachable / no update server yet → ignore. The app
|
||||
// keeps running on the current version; checking again next launch.
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,10 @@ export const en: Catalog = {
|
||||
signIn: "Sign in",
|
||||
signingIn: "Signing in…",
|
||||
},
|
||||
update: {
|
||||
available: "Update available",
|
||||
prompt: "Version {{version}} is available. Install now and restart?",
|
||||
},
|
||||
nav: {
|
||||
booth: "Booth",
|
||||
shift: "Shift",
|
||||
@@ -568,6 +572,7 @@ export const en: Catalog = {
|
||||
starting: "Starting…",
|
||||
endShift: "End shift",
|
||||
ending: "Ending…",
|
||||
endConfirm: "End this shift? A signed Z-report is recorded and printed.",
|
||||
drawer: "Drawer:",
|
||||
openingFloatInherited: "(opening float inherited from the prior shift)",
|
||||
drawerCashAdmin: "Drawer cash (admin) — load or remove the float",
|
||||
@@ -632,6 +637,15 @@ export const en: Catalog = {
|
||||
allOperators: "All operators",
|
||||
apply: "Apply",
|
||||
clear: "Clear",
|
||||
timeframe: "Timeframe",
|
||||
preset_yesterday: "Yesterday",
|
||||
preset_week: "Last week",
|
||||
preset_month: "Last month",
|
||||
preset_all: "All",
|
||||
preset_custom: "Custom",
|
||||
selectAShift: "Select a shift to see its activity log.",
|
||||
noActivity: "No activity in this shift.",
|
||||
current: "current",
|
||||
drawerSection: "Drawer",
|
||||
openingFloat: "Opening float",
|
||||
cashTaken: "Cash taken",
|
||||
|
||||
@@ -40,6 +40,10 @@ export const sq = {
|
||||
signIn: "Hyr",
|
||||
signingIn: "Duke hyrë…",
|
||||
},
|
||||
update: {
|
||||
available: "Përditësim i disponueshëm",
|
||||
prompt: "Versioni {{version}} është i disponueshëm. Ta instaloj tani dhe ta rinis?",
|
||||
},
|
||||
nav: {
|
||||
booth: "Kabina",
|
||||
shift: "Turni",
|
||||
@@ -580,6 +584,7 @@ export const sq = {
|
||||
starting: "Duke filluar…",
|
||||
endShift: "Mbyll turnin",
|
||||
ending: "Duke mbyllur…",
|
||||
endConfirm: "Të mbyllet ky turn? Regjistrohet dhe printohet një Raport Z i nënshkruar.",
|
||||
drawer: "Arka:",
|
||||
openingFloatInherited: "(bilanci fillestar i trashëguar nga turni i mëparshëm)",
|
||||
drawerCashAdmin: "Para në arkë (admin) — shto ose hiq bilancin",
|
||||
@@ -645,6 +650,15 @@ export const sq = {
|
||||
allOperators: "Të gjithë operatorët",
|
||||
apply: "Apliko",
|
||||
clear: "Pastro",
|
||||
timeframe: "Periudha",
|
||||
preset_yesterday: "Dje",
|
||||
preset_week: "Javën e fundit",
|
||||
preset_month: "Muajin e fundit",
|
||||
preset_all: "Të gjitha",
|
||||
preset_custom: "E zgjedhur",
|
||||
selectAShift: "Zgjidh një turn për të parë aktivitetin e tij.",
|
||||
noActivity: "Asnjë aktivitet në këtë turn.",
|
||||
current: "aktual",
|
||||
// Expanded drawer detail.
|
||||
drawerSection: "Arka",
|
||||
openingFloat: "Bilanci fillestar",
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
// Kiosk affordances for the operator console.
|
||||
//
|
||||
// We do NOT lock the operator out of the OS (that's a deliberate decision —
|
||||
// the desktop window starts maximized, not fullscreen). The one restriction is
|
||||
// blocking the right-click context menu in PRODUCTION builds, so an operator
|
||||
// can't reach "Inspect"/"Reload"/"Save as" on the live appliance. In DEV the
|
||||
// context menu (and devtools) stay available for debugging.
|
||||
//
|
||||
// Applies to both the browser prod build and the Tauri desktop build, since both
|
||||
// load this same SPA. import.meta.env.PROD is true for `vite build`, false for
|
||||
// `vite` dev.
|
||||
|
||||
export function installKioskGuards(): void {
|
||||
if (!import.meta.env.PROD) return; // dev: keep right-click + devtools
|
||||
window.addEventListener("contextmenu", (e) => e.preventDefault());
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
// Where the SPA reaches the Fastify backend.
|
||||
//
|
||||
// In a browser (dev via the Vite proxy, or prod where Fastify serves the built
|
||||
// SPA) this is EMPTY — requests stay relative (`/api/...`) and same-origin, so
|
||||
// nothing changes. The Tauri desktop shell (apps/desktop) serves the bundled
|
||||
// SPA from `tauri://localhost`, which has no backend and no proxy; there we set
|
||||
// VITE_API_BASE to the appliance's Fastify origin (e.g. http://127.0.0.1:3000)
|
||||
// at build time so /api and the live WS feed resolve to the real server.
|
||||
//
|
||||
// Keep this the SINGLE source for the backend origin — api.ts and the live-feed
|
||||
// WebSocket both read it, so the web app and the desktop shell stay identical
|
||||
// except for this one build-time value.
|
||||
|
||||
/** Backend HTTP origin, no trailing slash. Empty string = same-origin/relative. */
|
||||
export const API_BASE: string = (import.meta.env.VITE_API_BASE ?? "").replace(/\/$/, "");
|
||||
|
||||
/** Resolve an API path to a full URL (or a relative path when API_BASE is empty). */
|
||||
export function apiUrl(path: string): string {
|
||||
return API_BASE ? `${API_BASE}${path}` : path;
|
||||
}
|
||||
|
||||
/** Build the ws:// or wss:// URL for the backend's live feed. Uses API_BASE when
|
||||
* set (Tauri), else the page origin (browser). */
|
||||
export function wsUrl(path: string): string {
|
||||
if (API_BASE) {
|
||||
return `${API_BASE.replace(/^http/, "ws")}${path}`;
|
||||
}
|
||||
const proto = window.location.protocol === "https:" ? "wss:" : "ws:";
|
||||
return `${proto}//${window.location.host}${path}`;
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { useQueryClient } from "@tanstack/react-query";
|
||||
import type { DeviceStatus, LedgerEvent, Occupancy } from "../api.js";
|
||||
import { qk } from "./query.js";
|
||||
import { useLiveStore } from "./live-store.js";
|
||||
import { wsUrl } from "./origin.js";
|
||||
|
||||
// Booth WebSocket client. Opens ONE socket to /api/ws and turns server pushes into
|
||||
// (a) live-store updates for the ticker/occupancy and (b) Query cache invalidations
|
||||
@@ -18,11 +19,6 @@ type WsMessage =
|
||||
| { kind: "printer-status"; event: unknown }
|
||||
| { kind: "device-status"; event: DeviceStatus };
|
||||
|
||||
/** Build the ws:// or wss:// URL for the same origin the SPA is served from. */
|
||||
function wsUrl(): string {
|
||||
const proto = window.location.protocol === "https:" ? "wss:" : "ws:";
|
||||
return `${proto}//${window.location.host}/api/ws`;
|
||||
}
|
||||
|
||||
export function useLiveFeed(): void {
|
||||
const qc = useQueryClient();
|
||||
@@ -39,7 +35,7 @@ export function useLiveFeed(): void {
|
||||
const connect = () => {
|
||||
if (closedRef.current) return;
|
||||
setStatus(retryRef.current === 0 ? "connecting" : "connecting");
|
||||
const sock = new WebSocket(wsUrl());
|
||||
const sock = new WebSocket(wsUrl("/api/ws"));
|
||||
sockRef.current = sock;
|
||||
|
||||
sock.onopen = () => {
|
||||
|
||||
@@ -5,11 +5,23 @@ import "./lib/i18n/index.js"; // initialize i18next before the app renders
|
||||
import { App } from "./App.js";
|
||||
import { ErrorBoundary } from "./lib/ErrorBoundary.js";
|
||||
import { installClientLogging } from "./lib/logger.js";
|
||||
import { installKioskGuards } from "./lib/kiosk.js";
|
||||
import { checkForDesktopUpdate } from "./lib/desktop-updater.js";
|
||||
import i18n from "./lib/i18n/index.js";
|
||||
|
||||
// Capture uncaught errors / rejections / console noise → backend log store, before
|
||||
// the app mounts so even an early crash is reported. See lib/logger.ts.
|
||||
installClientLogging();
|
||||
|
||||
// Block the right-click context menu in prod builds (dev keeps it + devtools).
|
||||
installKioskGuards();
|
||||
|
||||
// Desktop only: check for a signed update on launch and, if one exists, ask the
|
||||
// operator before installing + relaunching. No-op in the browser / when offline.
|
||||
void checkForDesktopUpdate(({ version }) =>
|
||||
Promise.resolve(window.confirm(i18n.t("update.prompt", { version }))),
|
||||
);
|
||||
|
||||
const rootEl = document.getElementById("root");
|
||||
if (!rootEl) throw new Error("root element not found");
|
||||
|
||||
|
||||
@@ -24,7 +24,6 @@ import { TariffComposer } from "./TariffComposer.js";
|
||||
import { TariffLab } from "./TariffLab.js";
|
||||
import { SubscriptionManager } from "./SubscriptionManager.js";
|
||||
import { SubscriptionPlansManager } from "./SubscriptionPlansManager.js";
|
||||
import { ShiftControl } from "./ShiftControl.js";
|
||||
import { SiteSettings } from "./SiteSettings.js";
|
||||
import { UsersManager } from "./UsersManager.js";
|
||||
import { RolesManager } from "./RolesManager.js";
|
||||
@@ -78,7 +77,7 @@ function SetupLayout() {
|
||||
const { t } = useTranslation();
|
||||
const show = (perm: Permission) => can(user, perm);
|
||||
return (
|
||||
<div className="mx-auto max-w-4xl">
|
||||
<div className="">
|
||||
<nav className="mb-4 flex flex-wrap items-center gap-1 border-b border-term-border">
|
||||
{show("site:update") && <SetupTab to="/setup" label={t("nav.devices")} exact />}
|
||||
{show("tariff:read") && <SetupTab to="/setup/tariff" label={t("nav.tariff")} />}
|
||||
@@ -344,9 +343,17 @@ const shiftRoute = createRoute({
|
||||
path: "/shift",
|
||||
component: function ShiftRoute() {
|
||||
const { user } = rootRoute.useRouteContext();
|
||||
// The drawer-voucher form is operator-RAISED (shift:create); an admin still has
|
||||
// to authorize each voucher with their password server-side.
|
||||
return <ShiftControl canVoucher={can(user, "shift:create")} />;
|
||||
// The shift hub: list (current/open shift on top + history) + per-shift activity log.
|
||||
// The CURRENT shift's pane carries the actions (open/close, drawer voucher, takings),
|
||||
// each opening a modal. `canManage` = shift:create (start/end + raise vouchers); a
|
||||
// voucher additionally needs an admin's password sign-off server-side.
|
||||
return (
|
||||
<ShiftsHistory
|
||||
user={user}
|
||||
canManage={can(user, "shift:create")}
|
||||
canVoucher={can(user, "shift:create")}
|
||||
/>
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -18,6 +18,19 @@ importers:
|
||||
specifier: 6.0.3
|
||||
version: 6.0.3
|
||||
|
||||
apps/desktop:
|
||||
dependencies:
|
||||
'@tauri-apps/plugin-process':
|
||||
specifier: ^2.3.1
|
||||
version: 2.3.1
|
||||
'@tauri-apps/plugin-updater':
|
||||
specifier: ^2.10.1
|
||||
version: 2.10.1
|
||||
devDependencies:
|
||||
'@tauri-apps/cli':
|
||||
specifier: ^2.9.1
|
||||
version: 2.11.3
|
||||
|
||||
apps/server:
|
||||
dependencies:
|
||||
'@fastify/cookie':
|
||||
@@ -89,6 +102,12 @@ importers:
|
||||
'@tanstack/react-router':
|
||||
specifier: ^1.170.16
|
||||
version: 1.170.16(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
|
||||
'@tauri-apps/plugin-process':
|
||||
specifier: ^2.3.1
|
||||
version: 2.3.1
|
||||
'@tauri-apps/plugin-updater':
|
||||
specifier: ^2.10.1
|
||||
version: 2.10.1
|
||||
i18next:
|
||||
specifier: ^26.3.1
|
||||
version: 26.3.1(typescript@6.0.3)
|
||||
@@ -1261,6 +1280,86 @@ packages:
|
||||
'@tanstack/store@0.9.3':
|
||||
resolution: {integrity: sha512-8reSzl/qGWGGVKhBoxXPMWzATSbZLZFWhwBAFO9NAyp0TxzfBP0mIrGb8CP8KrQTmvzXlR/vFPPUrHTLBGyFyw==}
|
||||
|
||||
'@tauri-apps/api@2.11.1':
|
||||
resolution: {integrity: sha512-M2FPuYND2m+wh5hfW9ZpSdxMPdEJovPBWwoHJmwUpysTYNHaOkVFN419m/K0LIgjb/7KU2vBgsUepJWugQCvAA==}
|
||||
|
||||
'@tauri-apps/cli-darwin-arm64@2.11.3':
|
||||
resolution: {integrity: sha512-BxpaM8bsCoXs3wd4WKYhas/G1gs7+r7B+e4WnyRk2GEoVOouJB1hoL6E6YLXZDXbYci6VFdrNnobQwd2uVL4ew==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [darwin]
|
||||
|
||||
'@tauri-apps/cli-darwin-x64@2.11.3':
|
||||
resolution: {integrity: sha512-DbZYuPB1ZEzcAHYeyCvo3ltzM27+aXwPloCrtexPnmgPgulYJm3TOq6aC4S+wPhSXteddg8zImtNkvx/gQzmwg==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [darwin]
|
||||
|
||||
'@tauri-apps/cli-linux-arm-gnueabihf@2.11.3':
|
||||
resolution: {integrity: sha512-741NduqBmz1XkdU8yz3OI/kBZtqHbvxo9F9ytIeWYU69/Ba9dcZEbqOU++Dp0G/XU8vAI0TfTywEl+p+BbLvaA==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm]
|
||||
os: [linux]
|
||||
|
||||
'@tauri-apps/cli-linux-arm64-gnu@2.11.3':
|
||||
resolution: {integrity: sha512-RWAXT8pTqIczXcoic+LXlo6uEbAXGB0cgh6Pg7Y9xVnEbzryQ1JHtRGj9SxzrKSemBIDBH6Qc24kK2G69i8ofA==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
|
||||
'@tauri-apps/cli-linux-arm64-musl@2.11.3':
|
||||
resolution: {integrity: sha512-qomqYS+yAkd0gXMRmhguWXc7RfVN+XKKXaEwbf5QmKURwydLFOTldd6F8/WoZDSsBMrV8dpNxz0YneGLmobiSA==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
|
||||
'@tauri-apps/cli-linux-riscv64-gnu@2.11.3':
|
||||
resolution: {integrity: sha512-jOCXbDqeDj5XcclsOBAaXjtTgwZCVg8zEZ+dbPUCoADOgljFgL0rOkYTc96vUYgOrYEfuHYihWMxIDGaD6GwJw==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [riscv64]
|
||||
os: [linux]
|
||||
|
||||
'@tauri-apps/cli-linux-x64-gnu@2.11.3':
|
||||
resolution: {integrity: sha512-+u3HO/F3gHwL48t9gWN/urqZvpaEJzBFmTaq5eSIhvy8TOvnhb+LgJr3Q3BG+5JxuBrCUjqtOEz6gMttdJFSBA==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
|
||||
'@tauri-apps/cli-linux-x64-musl@2.11.3':
|
||||
resolution: {integrity: sha512-spr5Jpr6KF/vehkLwJ0YmdGv8QwpWU+uw7J8bgijO0sox6ZCYsSNMbcsQjTqPi4xl+p0woIYpWXgChgHYpAc8g==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
|
||||
'@tauri-apps/cli-win32-arm64-msvc@2.11.3':
|
||||
resolution: {integrity: sha512-abkoRQih5xBa3vz2spWaex0kP/MzVzVPQHom2f8jnCq46R/luOD6Uy85EMU9/bfzf6ZzdorWJsgO+OMX90Fx2w==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [win32]
|
||||
|
||||
'@tauri-apps/cli-win32-ia32-msvc@2.11.3':
|
||||
resolution: {integrity: sha512-Vy6AvzFm1G40hg3r+OYDB3jkuu7R4wnMzbQBKuun9v6Cgg8IierpLL7toMzrZKs/8NlG8Sg4x1iLFR52oknyHg==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [ia32]
|
||||
os: [win32]
|
||||
|
||||
'@tauri-apps/cli-win32-x64-msvc@2.11.3':
|
||||
resolution: {integrity: sha512-GlciF75GdbseajOyib2aCHwE3BXIqZ1liGKWLFRvCdN5wm8h8hFssEVKQ/6E+2jsMLg9v7LCTb983YFnn0QSww==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [win32]
|
||||
|
||||
'@tauri-apps/cli@2.11.3':
|
||||
resolution: {integrity: sha512-EElQe8z8uD7Pi5++tJ/UfEwWuK08rd3oCDYdeIbJAb6pZRrxlqmoF5gh5H5YvzmUPhS4IRCaLSsQhvWkrfK+GQ==}
|
||||
engines: {node: '>= 10'}
|
||||
hasBin: true
|
||||
|
||||
'@tauri-apps/plugin-process@2.3.1':
|
||||
resolution: {integrity: sha512-nCa4fGVaDL/B9ai03VyPOjfAHRHSBz5v6F/ObsB73r/dA3MHHhZtldaDMIc0V/pnUw9ehzr2iEG+XkSEyC0JJA==}
|
||||
|
||||
'@tauri-apps/plugin-updater@2.10.1':
|
||||
resolution: {integrity: sha512-NFYMg+tWOZPJdzE/PpFj2qfqwAWwNS3kXrb1tm1gnBJ9mYzZ4WDRrwy8udzWoAnfGCHLuePNLY1WVCNHnh3eRA==}
|
||||
|
||||
'@turbo/darwin-64@2.9.18':
|
||||
resolution: {integrity: sha512-9f27peFu16ur8c0v9nUFUEyBnbKuuFsUTjHFWfmwGfzySBXbHwzU44QhZon6Mznz0cHsIr3984NQj/bVrnGSRw==}
|
||||
cpu: [x64]
|
||||
@@ -3167,6 +3266,63 @@ snapshots:
|
||||
|
||||
'@tanstack/store@0.9.3': {}
|
||||
|
||||
'@tauri-apps/api@2.11.1': {}
|
||||
|
||||
'@tauri-apps/cli-darwin-arm64@2.11.3':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-darwin-x64@2.11.3':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-linux-arm-gnueabihf@2.11.3':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-linux-arm64-gnu@2.11.3':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-linux-arm64-musl@2.11.3':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-linux-riscv64-gnu@2.11.3':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-linux-x64-gnu@2.11.3':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-linux-x64-musl@2.11.3':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-win32-arm64-msvc@2.11.3':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-win32-ia32-msvc@2.11.3':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli-win32-x64-msvc@2.11.3':
|
||||
optional: true
|
||||
|
||||
'@tauri-apps/cli@2.11.3':
|
||||
optionalDependencies:
|
||||
'@tauri-apps/cli-darwin-arm64': 2.11.3
|
||||
'@tauri-apps/cli-darwin-x64': 2.11.3
|
||||
'@tauri-apps/cli-linux-arm-gnueabihf': 2.11.3
|
||||
'@tauri-apps/cli-linux-arm64-gnu': 2.11.3
|
||||
'@tauri-apps/cli-linux-arm64-musl': 2.11.3
|
||||
'@tauri-apps/cli-linux-riscv64-gnu': 2.11.3
|
||||
'@tauri-apps/cli-linux-x64-gnu': 2.11.3
|
||||
'@tauri-apps/cli-linux-x64-musl': 2.11.3
|
||||
'@tauri-apps/cli-win32-arm64-msvc': 2.11.3
|
||||
'@tauri-apps/cli-win32-ia32-msvc': 2.11.3
|
||||
'@tauri-apps/cli-win32-x64-msvc': 2.11.3
|
||||
|
||||
'@tauri-apps/plugin-process@2.3.1':
|
||||
dependencies:
|
||||
'@tauri-apps/api': 2.11.1
|
||||
|
||||
'@tauri-apps/plugin-updater@2.10.1':
|
||||
dependencies:
|
||||
'@tauri-apps/api': 2.11.1
|
||||
|
||||
'@turbo/darwin-64@2.9.18':
|
||||
optional: true
|
||||
|
||||
|
||||
@@ -69,10 +69,21 @@ secure element is a new `Signer` impl with no `EventLog` change; each event stor
|
||||
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.
|
||||
> unforgeable by someone who owns the host** — only a non-extractable key in a secure element
|
||||
> ([[atecc608]] on embedded, or the host **[[tpm|TPM]]** on a PC appliance) gives property (3) above.
|
||||
> Until that is wired, the chain detects tampering by *outsiders* and *accidental* corruption, but an
|
||||
> operator (or anyone who pulls the SSD and reads the `.env`) has the HMAC key and could **edit a row
|
||||
> and re-sign the whole chain undetectably**. This is the central reason #6 matters.
|
||||
|
||||
> **Pull-the-disk attack (traced 2026-06-21).** Removing the SSD, editing `parking.sqlite` on
|
||||
> another machine, and rebooting: any blind edit/delete/reorder **breaks the chain** and
|
||||
> `verifyChain()` pinpoints it (bad signature / index gap / prevHash mismatch / unknown keyId). **But
|
||||
> two gaps:** (a) **nothing runs `verifyChain()` at startup today** — the tamper is *detectable but
|
||||
> undetected* until something invokes verification (wire a boot-time self-check that at least logs/flags
|
||||
> a signed alarm — fail-open on exit still governs; this is [[open-questions]] #13); and (b) with the
|
||||
> *software* signer the key is on the same disk, so the attacker can re-sign and pass verification —
|
||||
> only a secure-element key ([[tpm]]/[[atecc608]]) closes that. [[tpm|TPM-sealed]] LUKS additionally
|
||||
> stops the disk **mounting** off-host at all.
|
||||
|
||||
### Business-layer event types (the ledger)
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
type: concept
|
||||
tags: [parking, security, platform]
|
||||
sources: [parking-system-architecture]
|
||||
updated: 2026-06-14
|
||||
updated: 2026-06-21
|
||||
---
|
||||
|
||||
# Disk / OS Hardening
|
||||
@@ -18,6 +18,12 @@ Physical-access attacks on Windows are trivial (boot media + password-reset tool
|
||||
- **GRUB password + Secure Boot** — prevents boot-parameter tampering / unsigned loaders.
|
||||
- **No desktop environment** — single-purpose appliance.
|
||||
- **Key-based SSH only.**
|
||||
- **[[tpm|TPM 2.0]]** _(recommended, 2026-06-21)_ — seals the LUKS key to the boot chain so the disk
|
||||
**auto-unlocks only on an untampered boot**, making encryption-at-rest compatible with **unattended
|
||||
reboot** (a booth must come back up after a power cut without a human typing a passphrase). Also a
|
||||
candidate home for the non-extractable host event-signing key. Caveats (live-root limit, bus-sniff,
|
||||
PCR brittleness, mandatory recovery passphrase + re-seal runbook) on [[tpm]]; implementation is
|
||||
[[open-questions]] #12.
|
||||
|
||||
With LUKS in place, **SQLCipher becomes optional** defence-in-depth rather than the critical
|
||||
layer. (The custom controller adds its own: ESP32 flash encryption + secure boot — see
|
||||
|
||||
@@ -13,8 +13,8 @@ The **second foundational force** (with [[offline-first]]). The central insight
|
||||
## The key reframing
|
||||
|
||||
Early thinking focused on protecting the database **at rest** — SQLCipher, LUKS, BitLocker,
|
||||
TPM-sealed keys. All of that defends against **an outsider who steals the machine or boots from
|
||||
external media**.
|
||||
[[tpm|TPM-sealed keys]]. All of that defends against **an outsider who steals the machine or boots
|
||||
from external media**.
|
||||
|
||||
That is the **wrong primary threat**. The most likely adversary is the **legitimate operator at
|
||||
the booth**. While the app runs, the database is decrypted in memory and the operator has full
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
---
|
||||
type: concept
|
||||
tags: [parking, security, platform, hardware]
|
||||
sources: []
|
||||
updated: 2026-06-21
|
||||
---
|
||||
|
||||
# TPM 2.0 (Trusted Platform Module)
|
||||
|
||||
A small crypto chip on the host that provides two host-hardening primitives. Useful **defence-in-
|
||||
depth** for the appliance, but — like all secure elements — it defends the **secondary**
|
||||
([[threat-model|outsider-with-the-box]]) threat, **never** the operator-at-the-booth, and is **not**
|
||||
a substitute for the system's real anti-fraud control ([[reconciliation]] over the
|
||||
[[append-only-event-chain|signed chain]]). _(Analysis recorded 2026-06-21; implementation pending —
|
||||
see [[open-questions]] #12.)_
|
||||
|
||||
> ⚠ **Naming:** it's **TPM** (Trusted Platform Module), often miswritten "TMP".
|
||||
|
||||
## How it works — two primitives
|
||||
|
||||
1. **Non-extractable keys.** A key generated *inside* the TPM never leaves it. No command at any
|
||||
privilege level reads out the private key; you can only ask the TPM to *use* it (sign/decrypt).
|
||||
So the key isn't a file an attacker can copy — the same property the [[atecc608]] gives, but with
|
||||
hardware most PCs already have.
|
||||
2. **Boot measurement + sealing (PCRs).** Each boot stage hashes the next (firmware → bootloader →
|
||||
kernel) into tamper-evident registers (**PCRs**). A secret can be **sealed** so the TPM only
|
||||
releases/uses it when the PCRs match a known-good boot state — tamper the boot chain → PCRs change
|
||||
→ the TPM refuses.
|
||||
|
||||
## What it buys this appliance
|
||||
|
||||
- **Sealed-LUKS auto-unlock for unattended reboot.** The headline win. LUKS ([[disk-os-hardening]])
|
||||
normally needs a human to type a passphrase at boot; a parking booth must reboot itself after a
|
||||
power cut. `systemd-cryptenroll --tpm2-device` seals the LUKS key to the TPM + boot-chain PCRs, so
|
||||
the disk auto-unlocks **only** on an untampered boot. This is what makes "encrypted disk" and
|
||||
"unattended appliance" compatible.
|
||||
- **Defeats the offline disk-tamper / re-sign attack.** If the host event-signing key lives in the
|
||||
TPM (non-extractable), then pulling the SSD yields the *data* but **not** the signing key — so an
|
||||
attacker cannot edit a row and re-sign the chain. `verifyChain()` then catches every edit. (With a
|
||||
*software* signer the key sits in `.env` on the disk, so disk theft = key theft = forgeable; see
|
||||
[[append-only-event-chain]] "Signer abstraction".) Sealed-LUKS goes further: the disk won't even
|
||||
**mount** off-host, blocking the read step entirely.
|
||||
- **Boot tamper-evidence** complementing the already-decided Secure Boot + GRUB password
|
||||
([[disk-os-hardening]]).
|
||||
|
||||
## What it does NOT protect against (be honest about the limits)
|
||||
|
||||
- **A rooted *running* host.** The TPM stops key *theft*, not key *use*. An attacker with admin/root
|
||||
on the live appliance can still ask the TPM to sign — the chip signs for whoever the running OS
|
||||
authorizes. So a TPM does **not** make a compromised host trustworthy. (A per-op TPM auth PIN/policy
|
||||
raises this bar but a determined root can often capture it.) This is exactly why the load-bearing
|
||||
control stays [[reconciliation]] against an **external** authority that assumes the box may lie.
|
||||
- **Determined physical + BIOS access with tools.** Documented attacks exist:
|
||||
- **Bus sniffing** — a *discrete* TPM talks to the CPU over an external LPC/SPI bus; researchers
|
||||
have physically tapped it and captured secrets *as they're released* (e.g. the LUKS/BitLocker key
|
||||
in transit) on PCR-only-sealed systems. A **firmware TPM (fTPM)** inside the CPU has no external
|
||||
bus to sniff (but has had its own firmware bugs).
|
||||
- **TPM 1.2 is broken** (SHA-1) — require **2.0** only.
|
||||
- Vendor-specific firmware/reset/replay vulns have surfaced over the years.
|
||||
- **The operator (primary threat).** While the app runs, the DB is decrypted in memory and the
|
||||
operator acts *through* the authenticated app — encryption/sealing is irrelevant to "take the cash,
|
||||
void the record" ([[threat-model]]).
|
||||
- **Windows caveat.** On Windows the TPM serves BitLocker/Hello, not our Linux app; a Windows-admin
|
||||
attacker inherits Windows' long history of BitLocker-TPM bypasses. Another reason the Windows + WSL
|
||||
fallback ([[desktop-shell-tauri]]) is the weak deployment.
|
||||
|
||||
## Verdict & guidance
|
||||
|
||||
- **Recommended (not required)** on the **Ubuntu 26.04 LTS appliance** ([[desktop-shell-tauri|best
|
||||
case]]): use it for **sealed-LUKS auto-unlock + a non-extractable host event-signing key**. It is a
|
||||
**cost-raiser and theft-defeater, not an absolute vault.**
|
||||
- **Prefer a firmware TPM (fTPM)** (Intel PTT / AMD fTPM — no external bus to sniff) and add a
|
||||
**PIN/auth policy**, rather than PCR-only sealing.
|
||||
- **Operational hazard:** sealing to boot-chain PCRs means a *legitimate* kernel / GRUB / BIOS update
|
||||
also changes the PCRs and **locks you out** until re-sealed. Keep a **LUKS recovery passphrase** and
|
||||
a **re-seal-on-update runbook** — mandatory, and a reason this stays "enhancement," not "baseline".
|
||||
- **It complements, never replaces,** the [[append-only-event-chain|signed chain]] +
|
||||
[[reconciliation]].
|
||||
|
||||
## TPM vs. ATECC608 — which secure element for the signing key
|
||||
|
||||
Both can hold the non-extractable host event-signing key. Pick by platform:
|
||||
|
||||
| | **TPM 2.0** | **[[atecc608]]** |
|
||||
| --- | --- | --- |
|
||||
| In a typical PC? | **Often yes** (discrete or fTPM) | **No** — an external I²C part you add/solder |
|
||||
| Standard / integration | TCG standard, OS-integrated | Microchip part, app-integrated over I²C |
|
||||
| Best fit here | **PC-based host appliance** (use what's there) | **Embedded / [[esp32-custom-controller|ESP32]]** controller |
|
||||
| Tangled with the whole OS attack surface? | Yes (general-purpose) | Less so (single-purpose chip) |
|
||||
|
||||
**Implication (refines the prior framing):** the wiki/[[bom]] treated the ATECC608 as *the* host
|
||||
signing root, but for the **Ubuntu-PC appliance the TPM is the realistic host secure-element** (no
|
||||
extra part to source), with the **ATECC608 reserved for the embedded controller** where there's no
|
||||
TPM. Either delivers the tamper-*proof* property; see [[open-questions]] #6 (host secure-element by
|
||||
platform) and #12 (TPM hardening implementation).
|
||||
@@ -0,0 +1,164 @@
|
||||
---
|
||||
type: decision
|
||||
tags: [parking, decisions, desktop, frontend]
|
||||
sources: []
|
||||
updated: 2026-06-21
|
||||
status: settled
|
||||
---
|
||||
|
||||
# Desktop shell — Tauri v2 (chosen over Electron)
|
||||
|
||||
The operator UI ([[react-vite-spa]]) needs to ship as a **desktop application** on the
|
||||
appliance (kiosk-style), with a **mobile app possible later** but out of scope now. The choice
|
||||
was **Tauri v2 vs. Electron**. **Decision: Tauri v2.** _(Settled with the user, 2026-06-21.)_
|
||||
|
||||
## The thin-shell architecture (why this choice is low-risk)
|
||||
|
||||
The desktop shell is a **thin kiosk wrapper around the existing SPA**, nothing more. All
|
||||
privileged logic — device drivers ([[device-adapter-pattern]]: reader/printer/relay/serial),
|
||||
[[local-jwt-auth|auth]], the [[append-only-event-chain|signed ledger]], [[tariff]]/[[subscription]]
|
||||
pricing — **stays in the [[fastify]] server** (settled with the user, 2026-06-21). The shell only
|
||||
loads the SPA, which talks to the local Fastify server over localhost. Consequences:
|
||||
|
||||
- **No device/serial logic is ported into the shell** (no Rust device code for Tauri; no Node
|
||||
main-process drivers for Electron). The "logic lives in the server" invariant holds.
|
||||
- If a WebView quirk ever bites, the **blast radius is presentation only** — the server and its
|
||||
signed ledger are untouched.
|
||||
|
||||
This is what neutralizes Tauri's main weakness (host-WebView fragmentation, below): the shell's
|
||||
job is fullscreen chrome, autostart, and kiosk lockdown — not correctness-critical rendering of
|
||||
financial truth.
|
||||
|
||||
## Why Tauri v2 fits *this* project specifically
|
||||
|
||||
- **Threat-model alignment ([[threat-model]]).** The primary adversary is the operator at the
|
||||
booth. Tauri's **deny-by-default capability/permission model** means the renderer literally
|
||||
cannot reach the filesystem, shell, or any native command unless we hand it a named, allowlisted
|
||||
command. That is defense-in-depth that matches "don't trust the booth." Electron's equivalent
|
||||
hardening (`contextIsolation`, `nodeIntegration:false`, `sandbox:true`, strict CSP) is **opt-in
|
||||
and easy to misconfigure** into giving the renderer Node access — exactly what this threat model
|
||||
can't afford.
|
||||
- **Small footprint / smaller CVE surface.** Tauri uses the **OS WebView** (WebKitGTK on Linux) —
|
||||
~3–10 MB bundles, tens of MB RAM, and **no bundled Chromium** to patch. Electron ships and pins
|
||||
its own Chromium (100+ MB, hundreds of MB RAM) and makes us **own Chromium's CVE treadmill** on a
|
||||
long-lived appliance. On a [[disk-os-hardening|hardened]] single-purpose box maintained for
|
||||
years, less to patch is a real operational win.
|
||||
- **License.** Tauri is **MIT / Apache-2.0** — clears the hard MIT/Apache/BSD constraint
|
||||
([[technology-stack]]). (Electron is also MIT; not a differentiator.)
|
||||
- **Rust core** is available if device access ever *did* move shell-side — but per the decision
|
||||
above it does not, so this is latent upside, not a current cost.
|
||||
|
||||
## What Electron would have bought (the rejected upside)
|
||||
|
||||
- **Version-pinned bundled Chromium** → identical rendering everywhere regardless of host. The most
|
||||
predictable option on a locked-down appliance image, and the reason this isn't a slam-dunk.
|
||||
- Largest, most battle-tested kiosk/appliance ecosystem.
|
||||
- Node in the main process → trivial code-sharing with the Fastify/Node device drivers — but we
|
||||
explicitly **keep drivers in the server**, so this advantage doesn't apply here.
|
||||
|
||||
Rejected because the heavy footprint, the Chromium CVE-patching obligation, and the opt-in (easy
|
||||
to get wrong) security posture all cut against the appliance + threat-model constraints, while its
|
||||
one real advantage (bundled Chromium) is only conditionally needed — see the open question.
|
||||
|
||||
## Target deployment — best case vs. worst case
|
||||
|
||||
The decision's risk collapses to **which OS the appliance actually runs** (user, 2026-06-21):
|
||||
|
||||
- **Best case — Ubuntu 26.04 LTS desktop (the intended appliance).** Ships a **current,
|
||||
distro-maintained WebKitGTK** (`webkit2gtk-4.1` / GTK4), patched by Canonical for the LTS
|
||||
lifetime. This **closes** the WebView risk below — no ancient-WebView problem, no CVE-patching
|
||||
burden on us. A native, hardened, single-purpose box that matches the [[disk-os-hardening]]
|
||||
platform decision. **Tauri belongs here; the decision is unconditional in this world.**
|
||||
- **Worst case — Windows 11 + WSL + Docker.** This is **not** a "use Electron instead" fallback —
|
||||
it **contradicts the [[standing-decisions|standing platform decision]]** (explicitly *"a
|
||||
dedicated, hardened Linux appliance, **not Windows/WSL**"*) and undermines
|
||||
[[disk-os-hardening|Secure Boot / LUKS / tamper resistance]] against the booth operator
|
||||
([[threat-model]]). Moreover a **desktop GUI shell does not naturally live inside WSL/Docker**
|
||||
(both are headless Linux). The realistic shape there is **no native shell at all**: run
|
||||
[[fastify]] + the SPA in the WSL/Docker backend, and open the SPA in a **kiosk browser** on
|
||||
Windows (`msedge`/`chrome --kiosk --app=http://localhost:PORT`). Electron is warranted **only**
|
||||
if a self-contained installable Windows `.exe` (no system browser) is a hard requirement.
|
||||
|
||||
The **thin-shell architecture makes the worst-case fallback cheap**: because all logic lives in
|
||||
[[fastify]], dropping the shell for a kiosk browser costs only the native window wrapper, not any
|
||||
functionality.
|
||||
|
||||
| Deployment | Desktop shell |
|
||||
| --- | --- |
|
||||
| **Ubuntu 26.04 LTS** (best, intended) | **Tauri v2** — current WebKitGTK, native, hardened. Decision stands unconditionally. |
|
||||
| **Windows 11 + WSL + Docker** (worst, conflicts with platform decision) | **No native shell — kiosk browser** at the local Fastify-served SPA. Electron only if a standalone Windows installer is required. |
|
||||
|
||||
## The one thing to verify (procurement / image gate)
|
||||
|
||||
Tauri's rendering correctness depends on the **WebKitGTK version that ships on the target
|
||||
appliance OS image**. On a hardened/pinned image this can be old and cause rendering quirks — pin
|
||||
it and test the built SPA against that **exact** WebView. **On the intended Ubuntu 26.04 LTS this
|
||||
is effectively resolved** (current distro-maintained WebKitGTK); the concern only bites on an
|
||||
unexpected image with an ancient/unavailable WebView, which would point to the kiosk-browser path
|
||||
(or Electron) above. Tracked as an [[open-questions|open question]].
|
||||
|
||||
## Invariants this decision must preserve
|
||||
|
||||
1. **Server owns all privileged logic.** The shell is presentation only; device/auth/ledger/pricing
|
||||
stay in [[fastify]]. Don't let "convenient native access" pull driver logic into the shell.
|
||||
2. **Deny-by-default native surface.** Expose Tauri commands one at a time, allowlisted; never open
|
||||
a broad filesystem/shell capability to the renderer ([[threat-model]]).
|
||||
3. **[[offline-first]].** The shell, its updater, and any WebView must work air-gapped; no decision
|
||||
here may introduce a network dependency in core operation.
|
||||
4. **Mobile later, not now.** A future mobile app is a separate target; don't pre-build for it.
|
||||
|
||||
## As-built (scaffolded 2026-06-21)
|
||||
|
||||
`apps/desktop` — a Tauri v2 shell, its own pnpm/Turbo package, wrapping the **same** `apps/web`
|
||||
SPA so the desktop and browser UIs **cannot drift** (one UI codebase; requirement from the user):
|
||||
|
||||
- **Dev:** `tauri dev` loads `http://localhost:5173` (the `@parking/web` Vite dev server) →
|
||||
editing a component in `apps/web` updates the desktop window via HMR live. `beforeDevCommand`
|
||||
starts the web dev server.
|
||||
- **Prod:** `frontendDist: ../../web/dist` bundles the built SPA into the binary;
|
||||
`beforeBuildCommand` rebuilds it first.
|
||||
- **Backend origin:** the SPA used relative `/api` + a `window.location.host` WS URL — fine in a
|
||||
browser, broken from `tauri://localhost`. Centralized into `apps/web/src/lib/origin.ts`
|
||||
(`API_BASE`/`apiUrl`/`wsUrl`), read from **`VITE_API_BASE`** (empty in the browser = unchanged;
|
||||
set to the Fastify origin for the desktop build). The `tauri.conf.json` CSP `connect-src`
|
||||
whitelists `127.0.0.1:3000`/`localhost:3000` http+ws; the backend's `WS_ALLOWED_ORIGINS` must
|
||||
include the Tauri origin.
|
||||
- **Thin shell, enforced:** the Rust crate (`parking_desktop_lib::run`) registers **no commands**;
|
||||
the capability set is `core:default` only — no fs/shell/device access to the renderer
|
||||
(invariants 1–2). All logic stays in [[fastify]].
|
||||
- **Turbo:** `build` is a **no-op** (so `turbo run build` stays fast); the real bundle is a
|
||||
deliberate `pnpm --filter @parking/desktop bundle` (the vision-shim pattern).
|
||||
- **Verified:** `cargo check` + a full `tauri build` compiled the Rust/WebKitGTK/wry stack and
|
||||
produced working `.deb`/`.rpm`/`.AppImage` bundles; `pnpm turbo run build lint` → 14/14 green
|
||||
(was 12). All Linux prereqs present (Rust 1.93, WebKitGTK 4.1, libsoup-3, WSLg display).
|
||||
### Window / kiosk, auto-update, env (added 2026-06-21)
|
||||
|
||||
Per the user's choices — the operator **keeps OS access** (no fullscreen lockdown):
|
||||
|
||||
- **Window:** starts **maximized** (`maximized: true`), not fullscreen, resizable. No OS-key
|
||||
blocking, no always-on-top — the booth PC stays usable as a PC.
|
||||
- **Right-click:** the context menu is blocked in **prod only** (`apps/web/src/lib/kiosk.ts`,
|
||||
guarded on `import.meta.env.PROD`); dev keeps right-click + devtools. Applies to both the browser
|
||||
prod build and the desktop build (same SPA).
|
||||
- **`VITE_API_BASE` wired to the environment:** `apps/web/.env.production` (committed, non-secret,
|
||||
allow-listed in `.gitignore`) sets `VITE_API_BASE=http://127.0.0.1:3000`, auto-loaded by
|
||||
`vite build` (which the desktop bundle runs). So the desktop build targets Fastify with no manual
|
||||
export; the browser-served-by-Fastify build should override to `""`.
|
||||
- **Auto-update (prompt-on-update, self-hosted):** `tauri-plugin-updater` + `tauri-plugin-process`.
|
||||
On launch the SPA checks the endpoint (`apps/web/src/lib/desktop-updater.ts`, no-op in browser /
|
||||
offline), prompts the operator (i18n `update.prompt`), then `downloadAndInstall()` + `relaunch()`.
|
||||
Accepts that the appliance may be **offline** day-to-day and brought online (phone hotspot) only
|
||||
when an update is wanted — consistent with [[offline-first]] (no network dependency in *core*
|
||||
operation; updates are out-of-band). Endpoint in `tauri.conf.json` is a **placeholder**
|
||||
(`https://UPDATES.EXAMPLE.invalid/...`) to fill in once the self-hosted update URL exists; the
|
||||
server must serve `latest.json` + the signed installer + its `.sig`.
|
||||
- **Code-signing (updater):** an Ed25519 **updater keypair** was generated. The **public key is
|
||||
embedded** in `tauri.conf.json` (`plugins.updater.pubkey`); the **private key + password live
|
||||
OUTSIDE the repo** at `~/.parking-updater-keys/` (0600) and as the build-time secrets
|
||||
`TAURI_SIGNING_PRIVATE_KEY` / `TAURI_SIGNING_PRIVATE_KEY_PASSWORD`. Losing them means no future
|
||||
signed updates — back them up. **Verified:** a signed `pnpm --filter @parking/desktop bundle`
|
||||
produced `.deb`/`.rpm`/`.AppImage` **plus their `.sig` updater signatures**; full `turbo run build
|
||||
lint` 14/14 green. *(This is the **updater** signing — distinct from OS-installer signing for
|
||||
Windows/macOS "unknown publisher", and from the [[atecc608]]/[[tpm]] **event** signing.)*
|
||||
- **Still deferred:** the actual update-hosting URL, OS-level installer signing
|
||||
(Windows/macOS publisher trust), and the Windows kiosk-browser fallback path.
|
||||
@@ -2,14 +2,14 @@
|
||||
type: decision
|
||||
tags: [parking, decisions, open]
|
||||
sources: [parking-system-architecture]
|
||||
updated: 2026-06-15
|
||||
updated: 2026-06-21
|
||||
status: open
|
||||
---
|
||||
|
||||
# Open Questions / Next Steps
|
||||
|
||||
**Not yet decided**, and they drive everything else — settle before procurement. (See
|
||||
[[parking-system-architecture]] §10.)
|
||||
**Not yet decided** (or decided-but-not-yet-built), and they drive everything else — settle before
|
||||
procurement. (See [[parking-system-architecture]] §10.)
|
||||
|
||||
1. **Lane topology.** One host per lane, or one central host driving networked devices in each
|
||||
lane? Decides how many controllers, printers, UPSs, and [[sqlite]] instances exist, and the
|
||||
@@ -62,3 +62,36 @@ status: open
|
||||
reclaim deleted-blob pages without `VACUUM`. **Undecided:** pruning policy (age-based vs.
|
||||
total-size cap), VACUUM cadence, and how this interacts with the #5 backup strategy (blobs
|
||||
bloat every backup). Until decided, snapshots accumulate unbounded. See [[entry-exit-points]].
|
||||
11. **Appliance OS image → WebKitGTK version (Tauri dependency).** _(Raised by
|
||||
[[desktop-shell-tauri]], 2026-06-21; narrowed same day.)_ The chosen
|
||||
[[desktop-shell-tauri|Tauri v2 desktop shell]] renders through the **host's WebKitGTK**, not a
|
||||
bundled browser. The risk reduces to which OS the appliance runs:
|
||||
- **Best case — Ubuntu 26.04 LTS desktop (intended):** ships a current, distro-maintained
|
||||
WebKitGTK → this question is **effectively resolved**; just confirm the built SPA renders on
|
||||
the actual image and pin it.
|
||||
- **Worst case — Windows 11 + WSL + Docker:** this **conflicts with the standing platform
|
||||
decision** (Linux appliance, *not* Windows/WSL — see [[standing-decisions]],
|
||||
[[disk-os-hardening]]) and a GUI shell doesn't live inside headless WSL/Docker. Fallback is
|
||||
**no native shell — a kiosk browser** at the local [[fastify]]-served SPA (Electron only if a
|
||||
standalone Windows installer is mandated). See [[desktop-shell-tauri]] for the decision table.
|
||||
Close this once the appliance OS image is fixed and the SPA is verified against its WebView.
|
||||
(Ties to #1 lane topology / image standardization.)
|
||||
12. **TPM 2.0 hardening — implementation (to build).** _(Recorded 2026-06-21; analysis in [[tpm]].)_
|
||||
On the Ubuntu 26.04 LTS appliance, harden using the host **TPM**: (a) **sealed-LUKS auto-unlock**
|
||||
(`systemd-cryptenroll --tpm2-device`) so the encrypted disk auto-unlocks only on an untampered
|
||||
boot → unattended reboot after power loss; (b) optionally hold the **non-extractable host
|
||||
event-signing key** in the TPM (a new `Signer` impl — no `EventLog` change; mirrors the
|
||||
[[atecc608]] swap), defeating the offline pull-the-disk-and-re-sign attack. **Must include:**
|
||||
require **TPM 2.0** (reject 1.2), **prefer fTPM** + a per-op **PIN/auth policy** (not PCR-only —
|
||||
bus-sniff), a **LUKS recovery passphrase**, and a **re-seal-on-update runbook** (kernel/GRUB/BIOS
|
||||
updates change the PCRs and lock the disk). TPM **complements, never replaces**, [[reconciliation]];
|
||||
it does nothing against a rooted live host or the operator. Moot in the Windows + WSL fallback. See
|
||||
[[tpm]], [[disk-os-hardening]]; relates to #6 (host secure-element by platform) and #13.
|
||||
13. **Startup chain-integrity self-check (to build).** _(Raised by the pull-the-disk trace,
|
||||
2026-06-21.)_ `verifyChain()` exists and pinpoints any tamper, but **nothing invokes it on
|
||||
boot** — a tampered DB loads and serves normally (detectable but undetected). Wire a **startup
|
||||
self-check** that runs `verifyChain()` and, on a break, **flags degraded state / writes a signed
|
||||
`anomaly` + alarms** (surfaced to the booth footer / next reconciliation). Open: refuse-to-serve
|
||||
vs. serve-degraded — lean **serve-degraded + loud alarm** (fail-open on exit still governs;
|
||||
refusing to boot could strand a lane). Software-only, independent of the TPM/[[atecc608]] hardware.
|
||||
See [[append-only-event-chain]].
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
type: decision
|
||||
tags: [parking, decisions]
|
||||
sources: [parking-system-architecture]
|
||||
updated: 2026-06-14
|
||||
updated: 2026-06-21
|
||||
status: settled
|
||||
---
|
||||
|
||||
@@ -20,6 +20,11 @@ The decisions treated as settled in the design notes. (See [[parking-system-arch
|
||||
[[vision-service]].
|
||||
- **Platform:** a **dedicated, hardened Linux appliance** (LUKS + GRUB password + Secure Boot),
|
||||
**not Windows/WSL** — see [[disk-os-hardening]].
|
||||
- **Desktop shell:** the operator UI ships as a **[[desktop-shell-tauri|Tauri v2]]** kiosk wrapper
|
||||
(chosen over Electron, 2026-06-21) — small footprint, no bundled Chromium to patch, and a
|
||||
deny-by-default native surface that fits [[threat-model|the booth-operator threat model]]. The
|
||||
shell stays **thin**: all privileged logic remains in [[fastify]]. One open dependency — the
|
||||
appliance's WebKitGTK version (see [[open-questions]] #11).
|
||||
- **Integrity:** append-only, hash-chained, [[atecc608]]-signed event log
|
||||
([[append-only-event-chain]]); **[[reconciliation]] is the anti-fraud control**; encryption
|
||||
protects only at-rest (see [[threat-model]]).
|
||||
|
||||
@@ -22,3 +22,11 @@ Two distinct uses:
|
||||
|
||||
Confirming ATECC608 wiring/usage on both ends is [[open-questions]] #6. Listed in the [[bom]]
|
||||
on the host machine.
|
||||
|
||||
> **Platform caveat (2026-06-21):** the ATECC608 is **not a PC component** — it's an external I²C
|
||||
> secure element you add/solder, native to embedded boards (the [[esp32-custom-controller]]), not to
|
||||
> an off-the-shelf host PC. For a **PC-based appliance** the realistic host secure-element for the
|
||||
> non-extractable event-signing key is the **[[tpm|TPM 2.0]]** the machine likely already has; reserve
|
||||
> the ATECC608 for the embedded controller. Both give the same non-extractable property — see [[tpm]]
|
||||
> "TPM vs. ATECC608". So use #1 (host event signing) is **TPM on a PC, ATECC608 on embedded**; use #2
|
||||
> (controller command auth) stays ATECC608.
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
---
|
||||
type: overview
|
||||
tags: [parking, index]
|
||||
updated: 2026-06-19
|
||||
updated: 2026-06-21
|
||||
---
|
||||
|
||||
# Index
|
||||
|
||||
Content catalog for the wiki. Start at [[overview]]. Maintained on every ingest.
|
||||
Counts: 4 sources · 19 entities · 44 concepts · 6 decision records.
|
||||
Counts: 4 sources · 19 entities · 45 concepts · 7 decision records.
|
||||
|
||||
## Overview & navigation
|
||||
- [[overview]] — the top-level synthesis and entry point.
|
||||
@@ -49,6 +49,7 @@ Counts: 4 sources · 19 entities · 44 concepts · 6 decision records.
|
||||
## Concepts — foundational forces
|
||||
- [[offline-first]] — no network dependency in core operation; what it forces (and doesn't).
|
||||
- [[threat-model]] — the operator-at-the-booth reframing; why encryption defends the wrong threat.
|
||||
- [[tpm]] — TPM 2.0 hardening: how it works, sealed-LUKS auto-unlock + non-extractable signing key; limits (live-root, bus-sniff) + TPM-vs-ATECC608 by platform; complements, not replaces, reconciliation.
|
||||
|
||||
## Concepts — integrity & anti-fraud
|
||||
- [[append-only-event-chain]] — append-only + hash chain + ATECC608 signing = unforgeable log.
|
||||
@@ -117,3 +118,4 @@ Counts: 4 sources · 19 entities · 44 concepts · 6 decision records.
|
||||
- [[vision-service]] — build a host-side ANPR + vehicle-verification service; replaces edge-LPR; scoped AGPL exception.
|
||||
- [[vision-service-packaging]] — the vision service lives in this monorepo (apps/vision/), separate process, wired into Turbo via a package.json shim; uv-managed Python.
|
||||
- [[event-streams-split]] — split the signed business ledger (ledger_events) from unsigned device telemetry (device_events).
|
||||
- [[desktop-shell-tauri]] — ✅ Tauri v2 chosen over Electron for the desktop kiosk shell; thin wrapper, server keeps all logic. Best case Ubuntu 26.04 LTS (resolves WebKitGTK); worst case Windows+WSL → kiosk browser, no native shell.
|
||||
|
||||
@@ -1173,3 +1173,59 @@ reserve checkbox (SiteSettings); booth pay modal shows an "OUT-OF-WINDOW" charge
|
||||
Verified on a copy of the live DB: qty 2 = 2× price; night-plan 19:30 entry → 30min/15,000 ALL owed,
|
||||
stamped + paid → gate clears, chain verifies; reserve toggle holds a qty-2 sub's 2 spots. Build+lint
|
||||
12/12; 80 shared tests. Updated [[subscription]], [[capacity-occupancy]], [[tariff]].
|
||||
|
||||
## [2026-06-21] query | Desktop shell: Tauri v2 vs. Electron
|
||||
Compared Tauri v2 and Electron for shipping the operator UI as a desktop app (mobile deferred).
|
||||
Decision (with user): **Tauri v2** — small footprint, no bundled Chromium to patch, deny-by-default
|
||||
native surface fitting the booth-operator threat model; MIT/Apache. Shell stays thin (device/auth/
|
||||
ledger/pricing remain in Fastify, per user). Filed [[desktop-shell-tauri]]; cross-linked from
|
||||
[[standing-decisions]], [[overview]], [[index]]. Open dependency: appliance WebKitGTK version
|
||||
([[open-questions]] #11) — flips to Electron if ancient/unavailable.
|
||||
|
||||
## [2026-06-21] query | Desktop shell — target OS (best/worst case)
|
||||
User specified deployment span: best = Ubuntu 26.04 LTS desktop, worst = Windows 11 + WSL + Docker.
|
||||
Refined [[desktop-shell-tauri]] + [[open-questions]] #11: Ubuntu 26.04 LTS ships a current
|
||||
distro-maintained WebKitGTK → effectively closes the WebView risk; Tauri unconditional there. The
|
||||
Windows+WSL case is NOT an "Electron instead" fallback — it conflicts with the standing Linux-
|
||||
appliance platform decision and can't host a GUI shell in headless WSL/Docker; fallback is a kiosk
|
||||
browser at the local Fastify-served SPA (Electron only if a standalone Windows installer is
|
||||
mandated). Thin-shell architecture makes that fallback cheap.
|
||||
|
||||
## [2026-06-21] query | TPM 2.0 hardening — analysis + pull-the-disk attack trace
|
||||
How a TPM works (non-extractable keys + PCR sealing) and its limits, recorded after tracing the
|
||||
"pull the SSD, tamper parking.sqlite offline, reboot" attack against event-log.ts/signer.ts.
|
||||
Findings: verifyChain() catches every blind tamper (bad sig / index gap / prevHash / unknown keyId)
|
||||
but (a) nothing runs it at boot, and (b) the software HMAC key lives in .env on the same disk →
|
||||
attacker can re-sign undetectably. Only a secure-element key (TPM on a PC, ATECC608 on embedded)
|
||||
makes it tamper-PROOF; TPM-sealed LUKS additionally blocks off-host mount. TPM verdict: recommended
|
||||
not required on the Ubuntu appliance (sealed-LUKS auto-unlock + non-extractable signing key); does
|
||||
NOT defend a rooted live host or the operator; bus-sniff/PCR-brittleness caveats → prefer fTPM + PIN,
|
||||
keep recovery passphrase + re-seal runbook; complements not replaces reconciliation. Also corrected:
|
||||
ATECC608 is NOT in a PC (external I²C part) → on a PC appliance the TPM is the host secure-element,
|
||||
ATECC608 reserved for the ESP32 controller. New page [[tpm]]; cross-linked [[disk-os-hardening]],
|
||||
[[threat-model]], [[atecc608]], [[append-only-event-chain]]; open-questions #12 (TPM impl, to build),
|
||||
#13 (startup verifyChain self-check, to build); index + counts updated.
|
||||
|
||||
## [2026-06-21] build | apps/desktop — Tauri v2 kiosk shell scaffolded
|
||||
Built the thin Tauri v2 shell per [[desktop-shell-tauri]]: new apps/desktop package wrapping the
|
||||
SAME apps/web SPA (dev → localhost:5173 with HMR; prod → bundled web dist/), so desktop and browser
|
||||
UIs can't drift (user requirement). Rust core holds no business logic; capabilities core:default
|
||||
only (deny-by-default). One apps/web change: centralized the backend origin into lib/origin.ts
|
||||
(API_BASE/apiUrl/wsUrl from VITE_API_BASE) — no-op in the browser, lets the Tauri build target the
|
||||
Fastify origin. Turbo build is a no-op; real bundle = `pnpm --filter @parking/desktop bundle`.
|
||||
VERIFIED: cargo check + full tauri build → working .deb/.rpm/.AppImage; turbo run build lint 14/14
|
||||
green; prereqs present (Rust 1.93, WebKitGTK 4.1, libsoup-3, WSLg). Filled the As-built section of
|
||||
[[desktop-shell-tauri]]. Deferred: kiosk lockdown, auto-update, signing, Windows kiosk-browser path.
|
||||
|
||||
## [2026-06-21] build | apps/desktop — window/right-click, auto-update, code-signing, env wiring
|
||||
Per user choices on the Tauri shell: window starts MAXIMIZED (not fullscreen — operator keeps OS
|
||||
access); right-click context menu blocked in PROD only (lib/kiosk.ts, dev keeps devtools).
|
||||
VITE_API_BASE wired via apps/web/.env.production (committed non-secret, allow-listed in .gitignore;
|
||||
auto-loaded by vite build → desktop bundle targets Fastify, no manual export). Auto-update built:
|
||||
tauri-plugin-updater + -process, prompt-on-update flow (lib/desktop-updater.ts, no-op in browser/
|
||||
offline) → downloadAndInstall + relaunch; endpoint is a self-hosted PLACEHOLDER to fill in. Updater
|
||||
keypair generated: pubkey embedded in tauri.conf.json; private key + password kept OUTSIDE the repo
|
||||
(~/.parking-updater-keys, 0600) + as TAURI_SIGNING_* build secrets. VERIFIED: signed bundle →
|
||||
.deb/.rpm/.AppImage + .sig updater signatures; turbo run build lint 14/14 green; no key material in
|
||||
the repo. Updated As-built in [[desktop-shell-tauri]]. Deferred: real update URL, OS installer
|
||||
signing, Windows kiosk-browser fallback.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
type: overview
|
||||
tags: [parking, overview, synthesis]
|
||||
sources: [parking-system-architecture]
|
||||
updated: 2026-06-14
|
||||
updated: 2026-06-21
|
||||
---
|
||||
|
||||
# Parking System — Overview
|
||||
@@ -23,7 +23,8 @@ deployed on-site at a parking facility. Two forces shape nearly every decision:
|
||||
|
||||
- **Stack** ([[technology-stack]] / [[standing-decisions]]): [[turborepo]] · [[fastify]] ·
|
||||
[[react-vite-spa]] · [[sqlite]] + [[drizzle-orm]] · [[local-jwt-auth]] — all open-licensed to
|
||||
avoid lock-in (cf. rejected [[payload-cms]], [[refine]], [[logto-zitadel-oidc]]).
|
||||
avoid lock-in (cf. rejected [[payload-cms]], [[refine]], [[logto-zitadel-oidc]]). The operator UI
|
||||
ships as a thin **[[desktop-shell-tauri|Tauri v2]]** kiosk shell (chosen over Electron).
|
||||
- **Integrity** is the heart of it: an [[append-only-event-chain]] (hash-chained, [[atecc608]]-
|
||||
signed) plus external [[reconciliation]] — *that's* what remote sync really is. Encryption at
|
||||
rest ([[disk-os-hardening]]) defends a secondary threat.
|
||||
|
||||