feat: React control panel; pending-card review workflow; auth-method audit

Frontend rewrite (frontend/, replacing backend/static/):
- Vite + TypeScript + React 19, React Router 7, zustand, TanStack Query 5
- dev: vite proxy /api -> :9000; prod: npm run build -> dist/, served by
  the backend with SPA fallback
- pages: Control (gun bays w/ scope+readiness-gated start/stop, relays),
  History (who/via/gun/when/duration/kWh audit), Cards (pending review,
  enrolled, rejected), Users (permission checkbox matrix)
- self-contained: fonts bundled, no CDN; light/dark; reduced-motion safe

Backend:
- learn mode removed: unknown cards are always refused and queued in
  pending_cards; admin approves (name + owner + gun restrictions in one
  step) or rejects (denied_cards, silent, un-rejectable); pending count
  rides /api/status as the notification signal
- sessions record the auth method (card tap vs in-app button) for audit
- GET /api/permissions: grantable-permission catalog driving the UI matrix
- SPA static serving with path-traversal guard; 503 hint when not built

Smoke test: 54 checks incl. approve/reject round-trips over a fake charge
point and method audit assertions.
This commit is contained in:
2026-07-11 20:52:20 +02:00
parent 56c9020d9f
commit 75869364b0
41 changed files with 4057 additions and 610 deletions
+10 -4
View File
@@ -10,12 +10,13 @@ The three planned ways to authorize a charging session. Architecturally they all
## 1. RFID cards — ✅ verified live (2026-07-09)
First card tapped on the real charger: idTag `1000000000000393` → Authorize → StartTransaction on gun 2 → **actual charging session started** (tx 1, meter_start 3,513.857 kWh). Enrolled as "RFID card A". Second card captured the same session: `1000000000000395` → "RFID card B". The ids are sequential — the cards ship as a numbered batch. Remaining: tap any further cards, then set `learn_mode=false` to enforce.
First card tapped on the real charger: idTag `1000000000000393` → Authorize → StartTransaction on gun 2 → **actual charging session started** (tx 1, meter_start 3,513.857 kWh). Enrolled as "RFID card A". Second card captured the same session: `1000000000000395` → "RFID card B". The ids are sequential — the cards ship as a numbered batch.
> [!warning] Session restarted after remote stop (❓ verify mechanism)
> ~65 s after a RemoteStop on gun 2 (cable left plugged), a **new** transaction began with the same card id. Either the owner re-tapped, or the charger auto-restarts from its authorization cache (`AuthorizationCacheEnabled=true`). Matters for app UX: "stop" may not stick while the cable stays in. Test: remote-stop and touch nothing for 5 min.
Flow for each new card: tap once in learn mode → harvest its idTag from `seen_tags.json` / `GET /api/allowlist` → add to `authorized` with a name (`kind: "card"`).
> [!warning] Superseded (2026-07-11): learn mode removed — replaced by the **pending-card review workflow**
> An unknown card is now ALWAYS refused, but lands in `pending_cards`. The admin gets a notification (banner + badge in the [[frontend|panel]]) and decides: **approve** (name it, link it to a user, optionally restrict guns — one step) or **reject** (goes to `denied_cards`, silently refused, never re-pends; un-rejectable). New-card flow: tap once on the charger → review in the panel’s Cards page. ✅ smoke-verified: unknown tap → Invalid + pending; approved card authorizes on next tap; rejected card stays silent.
Since 2026-07-11 a card can be **linked to a user and restricted per gun**:
@@ -64,13 +65,18 @@ The [[backend]] now has real multi-user authorization on top of the three method
| `charger:eu092025:1` | start/stop/unlock gun 1 |
| `charger:eu092025:2` | same for gun 2 |
| `relay:<name>` / `relay:*` | switch those relays (others are invisible to the user) |
| `admin` | everything, incl. allowlist/user CRUD, learn-mode flip, setconfig, events |
| `admin` | everything, incl. cards (pending review, allowlist), user CRUD, relay/charger registry, setconfig, events |
- **Bootstrap**: zero users = open API (startup warns loudly). First user: `venv\Scripts\python -m backend.users add <name> --scopes admin`.
- ✅ Verified by the 45-check smoke test (login, wrong password, cookie + bearer, per-scope 403s, relay visibility filtering, user CRUD, session invalidation on delete). ⚠️ Not yet exercised from a real phone browser.
- Admins grant permissions in the panel’s Users page as a **checkbox matrix** (per gun, per relay, admin) rendered from `GET /api/permissions` — nobody types raw scope strings.
- ✅ Verified by the 54-check smoke test (login, wrong password, cookie + bearer, per-scope 403s, relay visibility filtering, user CRUD, session invalidation on delete). ⚠️ Not yet exercised from a real phone browser.
This resolves the ❓ "web app auth" open decision in [[overview]]: username+password with per-resource scopes, chosen over plain tokens by the owner.
## Audit: who charged, and how
Every session row records the **method**: `card` (physical RFID tap) or `app` (in-app button press), derived from the allowlist entry’s kind at StartTransaction, plus the resolved **who** (card owner / username). The panel’s History tab shows Who · Via · Gun · When · Duration · kWh. (2026-07-11, owner requirement.)
## Facts from the live probe that shape this design
Per [[2026-07-09-discovery-eu092025]]: `AuthorizeRemoteTxRequests=false`, so remote starts don't trigger a separate Authorize — the `decide()` gate fires when the charger sends `StartTransaction`. The on-charger offline allowlist (`LocalAuthList`) holds max **6 idTags** and is currently disabled; enough for a household if we ever want tap-to-charge to survive CSMS downtime.
+11 -9
View File
@@ -17,8 +17,7 @@ backend/ (run: venv\Scripts\python -m backend.main, from the repo root)
├── users.py passwords (PBKDF2), sessions (HMAC), scope matcher, user CLI
├── store.py SQLite session store: who charged, when, how many kWh + meter samples
├── config.py app-state sections (users/allowlist/relays/chargers), db-backed
├── journal.py events.jsonl + seen_tags.json (raw ground truth)
├── static/ the web panel PWA (index.html, manifest, service worker, icon)
├── journal.py events.jsonl (raw ground truth)
└── backend.db THE one store (SQLite, gitignored): sessions + samples +
settings (users, allowlist, relays, chargers, session secret)
```
@@ -26,32 +25,35 @@ backend/ (run: venv\Scripts\python -m backend.main, from the repo root)
## Surfaces (all on :9000 — the touchscreen URL never changes)
- `ws://<host>:9000/<ChargerID>` — OCPP WebSocket (catch-all path, the JC-6620 dials in)
- `GET /` — **the web panel** (mobile-first PWA, vanilla JS, self-contained; login → tabs Control / History / Admin, buttons filtered by the user's scopes; polls `/api/status` every 5 s)
- `GET /` — **the [[frontend|React panel]]** served from `../frontend/dist/` with SPA fallback (deep links land on index.html; `/api/*` + `/docs` excluded; 503 with instructions if not built)
- `POST /api/login|logout`, `GET /api/me` — username/password → 30-day session (cookie + bearer)
- `GET /api/sessions?limit&cp&connector` — **charging history: who / when / kWh** (visibility: own sessions + guns within scope; admin sees all); `GET /api/sessions/{tx}/samples` — per-minute energy/power/SoC for charts
- `GET /api/status` — mode, connected chargers, gun states, active transactions, auth events, relays (filtered to what the caller may control)
- `GET /api/status` — connected chargers, gun states, active transactions, auth events + pending-card count (admin), relays (filtered to what the caller may control)
- `GET /api/events?limit&event=` — tail the journal (admin)
- `POST /api/charger/start|stop[/{tx}]|unlock/{n}` — gun-scoped; `trigger/{...}|setconfig|probe` — admin
- `GET/PUT/DELETE /api/allowlist[/{idTag}]` + `POST /api/mode?learn=` — admin; **learn mode flips at runtime, no restart**
- `GET/PUT/DELETE /api/allowlist[/{idTag}]` — enrolled cards/tokens (admin)
- `GET /api/cards/pending` + `POST /api/cards/pending/{id}/approve|reject`, `GET/DELETE /api/cards/denied[/{id}]` — the **unknown-card review workflow** (admin); pending count rides `/api/status` as the notification signal
- `GET /api/permissions` — the grantable-permission catalog (chargers/guns/relays) that drives the panel's checkbox matrix (admin)
- `GET/PUT/DELETE /api/users[/{name}]` — user CRUD (admin), enables a PWA admin page later
- `GET /api/relays[?live=true]`, `GET /api/relays/{name}`, `POST /api/relays/{name}/on|off|toggle` — relay-scoped
- `/docs` — interactive OpenAPI docs
## Design facts
- Carried over from the proven discovery code: the `decide()` gate ([[authorization]]) — now with card→user linking (`"user"`) and charger-qualified gun restriction (`"guns": ["eu092025:2"]`, fnmatch) — the `_WSAdapter` WebSocket bridge, learn mode, the JSONL event journal. `DataTransfer` frames are journaled too (the VIN long-shot lead in [[authorization]]).
- Carried over from the proven discovery code: the `decide()` gate ([[authorization]]) — now with card→user linking (`"user"`) and charger-qualified gun restriction (`"guns": ["eu092025:2"]`, fnmatch) — the `_WSAdapter` WebSocket bridge, and the JSONL event journal. `DataTransfer` frames are journaled too (the VIN long-shot lead in [[authorization]]).
- **Multi-charger by design**: a second charger only needs the same URL with a unique ChargerID; scopes, sessions, card restrictions, and the panel are all keyed by charger id. Gun display names come from the `"chargers"` config section (not hardcoded).
- **Multi-user auth** (2026-07-11, replaced the interim `api_token`): username/password users with permission scopes — `charger:<cp>:<gun>`, `relay:<name>`, `admin` — full model in [[authorization]]. Stdlib crypto only (PBKDF2 + HMAC sessions). Zero users = open API (startup warns); bootstrap via `python -m backend.users add <name> --scopes admin`.
- Remote starts run under the calling user's own idTag (`app-<name>`, auto-enrolled) → per-person session attribution.
- **Consumption tracking** (`store.py`, 2026-07-11): every `StartTransaction` opens a row in `backend.db` with a resolved "who" (allowlist name or username); `StopTransaction` closes it and computes Wh from the meter diff; `MeterValues` rows land in a `samples` table (energy/power/SoC, kW→W normalized). Transaction ids continue from `MAX(tx)` across restarts, and stop-by-tx falls back to the store so sessions running through a backend restart stay stoppable.
- Relay calls are blocking tinytuya I/O, run via `asyncio.to_thread` so the OCPP socket never stalls.
- Venv at repo root (`../venv/`, Python 3.13); deps pinned in `backend/requirements.txt` (fastapi, uvicorn, websockets, ocpp, tinytuya) — the auth system added none.
- ✅ Smoke-tested 2026-07-11 (45 checks, isolated temp db via the `BACKEND_DB` env override): REST surface, allowlist CRUD incl. gun-restricted cards, login/sessions/scopes, user/relay/charger CRUD, the full consumption pipeline (start → meter sample → stop → kWh → visibility filtering), static panel serving, and a fake charge point over the real WS route.
- Sessions record the **auth method** (`card` vs `app`) for the audit trail; unknown cards NEVER charge — they queue in `pending_cards` for admin approve/reject (learn mode is gone).
- ✅ Smoke-tested 2026-07-11 (54 checks, isolated temp db via the `BACKEND_DB` env override): REST surface, allowlist CRUD incl. gun-restricted cards, login/sessions/scopes, user/relay/charger CRUD, the full consumption pipeline (start → meter sample → stop → kWh → visibility filtering), static panel serving, and a fake charge point over the real WS route.
- ✅ **Live charger connected** (2026-07-11 evening): `eu092025` dials the backend (events.jsonl). ⚠️ Panel not yet exercised from a real phone; relays unconfigured until the [[wifi-relays|key extraction]] is done.
## Web panel notes
## Web panel
Vanilla JS on purpose (no framework, no CDN — the panel must work with NetBird-only reachability). Start button enables only when the gun reports `Preparing`/`Available` **and** the user holds that gun's scope. Gun cards show who is charging and since when; History tab lists who/when/kWh; Admin tab (admin scope only) manages allowlist (incl. per-gun cards + "seen but not enrolled" quick-enroll), users, and the learn/enforce toggle. Trivial service worker = installable ("add to home screen") without cache-staleness risk.
See [[frontend]] — React/Vite app, built to `frontend/dist/` and served by this process.
## Deliberately deferred
+30
View File
@@ -0,0 +1,30 @@
---
type: entity
updated: 2026-07-11
tags: [software, frontend, react]
---
# Frontend (`../frontend/`)
The React control panel (built 2026-07-11, replacing the single-file vanilla-JS panel at the owner's request). Stack per the owner's spec: **Vite + TypeScript + React 19, React Router 7 (routing), zustand (auth/UI state), TanStack Query 5 (server state, polling)**.
## Dev / prod workflow
- **Dev**: `npm run dev` in `frontend/` → Vite on `:5173`, **proxies `/api` to the backend on `:9000`** (`vite.config.ts`), so the session cookie flows normally.
- **Prod**: `npm run build` → `frontend/dist/`; the [[backend]] serves it statically with an SPA fallback (exact files win, everything else gets `index.html`, `/api/*` and `/docs` excluded). No separate web server.
- Fully self-contained: fonts (Archivo + IBM Plex Mono via Fontsource) are bundled into `dist/` — nothing loads from a CDN, so it works over [[netbird|NetBird]] without internet. ~94 kB gzipped JS.
## Pages
| Route | Who | What |
|---|---|---|
| `/` (Control) | all | one "bay" card per gun (labels from the chargers registry): status lamp, Start/Stop gated by scope **and** gun readiness; live session shows who/via/duration; relay toggles with on-demand live read |
| `/history` | all (filtered by scope) | the audit table: **who charged, via Card or In-app, which gun, when, duration, kWh**; total kWh; live sessions flagged |
| `/cards` | admin | **pending cards awaiting review** (approve → name + owner + gun restrictions in one step; reject → silenced), enrolled cards with owner/guns editing, rejected list with un-reject |
| `/users` | admin | user CRUD with the **permission matrix** — admin toggle, per-gun and per-relay checkboxes rendered from `GET /api/permissions` (no raw scope strings in the UI) |
An amber **notification banner + nav badge** appears for admins whenever unknown cards are pending (count polled via `/api/status` every 5 s).
## Design
Instrument-panel direction grounded in the hardware: porcelain/graphite surfaces (light + dark via `prefers-color-scheme`), **copper-busbar accent**, IBM Plex Mono for telemetry/identifiers, Archivo for UI. Signature element: the **indicator lamp** (radial LED with glow) encoding state everywhere — green=available, pulsing green=charging, amber=preparing/pending, red=fault/denied. Reduced motion respected; keyboard focus visible.
+2 -1
View File
@@ -16,7 +16,8 @@ Catalog of every wiki page. Updated on every ingest. (Schema/conventions live in
- [[anfu-charger]] — the charging pile: its three internal devices + working touchscreen config
- [[jc-6620]] — the OCPP communication controller / client; its IPs and shipped-gateway gotcha
- [[backend]] — the production backend in `../backend/`: CSMS + REST API + relay control + user auth + consumption store + web panel, all on :9000
- [[backend]] — the production backend in `../backend/`: CSMS + REST API + relay control + user auth + consumption store, all on :9000
- [[frontend]] — the React control panel in `../frontend/`: Vite/TS, React Router, zustand, TanStack Query; served by the backend
- [[csms-toolkit]] — the Python CSMS scripts in `../discovering/`; discovery/diagnostic tooling (production role superseded by [[backend]])
- [[wifi-relays]] — the Tuya/SmartLife WiFi relays; local tinytuya control path + key-extraction steps
- [[netbird]] — the private overlay network; security boundary for the future web panel
+4
View File
@@ -79,3 +79,7 @@ Owner requirements: cards must belong to a person (not float around as "RFID car
## [2026-07-11] meta | config.json eliminated — one SQLite store (backend.db)
Owner pushback: two persistence stores (sessions.db + a config.json that doubled as a mutable datastore) was one too many, with confusing hand-edit-needs-restart semantics. Now everything lives in backend.db (renamed from sessions.db): sessions + samples tables plus a settings table holding the app-state sections (users, allowlist, relays, chargers, learn_mode, session_secret) as JSON blobs. All changes go through the API/panel and apply immediately; nothing to hand-edit. Legacy config.json auto-imports on first start (kept as config.json.migrated) — julian + cards + charger labels migrated. New admin endpoints PUT/DELETE /api/relays/{name} and PUT /api/chargers/{id} replace file editing (tinytuya wizard results now enter via /docs). Smoke test isolated via BACKEND_DB env override; 45 checks. Also: live cutover confirmed — eu092025 connected to the backend this evening. Updated [[backend]], [[authorization]], [[wifi-relays]], [[overview]].
## [2026-07-11] meta | React frontend; pending-card review workflow; auth-method audit
Owner: full frontend revision (React + routing + zustand + TanStack Query, Vite proxy in dev, static build served by backend, professional look) and backend fixes: permissions must be understandable, cards must connect to users, unknown card taps must notify the admin for approve/reject, and sessions must audit HOW authorization happened. Backend: learn mode REMOVED -> pending_cards/denied_cards workflow (unknown taps always refused, queued for review; pending count on /api/status as notification); sessions.method column (card|app); GET /api/permissions catalog. Frontend: new ../frontend/ (React 19, instrument-panel design, copper accent, indicator-lamp signature, bundled fonts); pages Control/History/Cards/Users; permission checkbox matrix; approve-with-owner-link in one step. Old backend/static vanilla panel deleted; seen_tags.json gone. Smoke: 54 checks. Created [[frontend]]; updated [[backend]], [[authorization]], [[overview]], [[architecture-plan]], [[index]], root CLAUDE.md.
+3 -1
View File
@@ -30,6 +30,8 @@ FastAPI app (uvicorn, :9000, on the always-on host)
**Web frontend: mobile-first PWA, no build pipeline — decided.**
Plain HTML/JS (Alpine.js or htmx + SSE), served by FastAPI. Features: status card, start/stop, allowlist management, session history. PWA manifest → "add to home screen". Reached only over [[netbird|NetBird]].
> [!warning] Superseded (2026-07-11): owner opted for a real build pipeline after seeing v1 — React/Vite stack, see [[frontend]]. "Served by FastAPI on :9000" and "NetBird-only" still hold.
**Flutter mobile app: phase 2, optional.**
The PWA covers ~95% of the value. Flutter earns its keep only for push notifications ("charging complete") or as a learning project. It would consume the same REST API (FastAPI's OpenAPI spec → typed Dart client codegen), so nothing built now is wasted. Phone needs the NetBird client either way.
@@ -39,7 +41,7 @@ The PWA covers ~95% of the value. Flutter earns its keep only for push notificat
1. **Productionize the CSMS** — ✅ done 2026-07-11 as the [[backend]] package (`../backend/`); SQLite session store added same day (JSONL journal stays as raw ground truth).
2. **REST API** — ✅ done 2026-07-11: status, remote start/stop, allowlist CRUD, runtime learn-mode flip, **relay on/off/toggle**, multi-user login with permission scopes, **session history (who/when/kWh)**. ⚠️ Relay half awaits the [[wifi-relays|local-key extraction]].
3. **Web panel (PWA)** — ✅ built 2026-07-11 (`backend/static/`, vanilla JS instead of Alpine — zero dependencies): login, per-gun status + start/stop gated by scopes and gun readiness, relay toggles, consumption history, admin tab. ⚠️ Untested on a real phone.
3. **Web panel** — ✅ built 2026-07-11, then **rebuilt the same day as a React app at the owner's request** ([[frontend]]: Vite + TS + React Router + zustand + TanStack Query; dev proxy to :9000, prod build served by the backend). The interim vanilla-JS panel is gone. ⚠️ Untested on a real phone.
4. **Deploy** — pick the always-on host (❓ open, [[overview]]), run as a service (systemd or NSSM on Windows), static IP / DHCP reservation, firewall rule for :9000, joined to NetBird.
5. **Hardware tasks** — RFID enrollment via learn mode; the Autocharge plug-in test ([[authorization]]) to settle "by vehicle".
6. **(Optional) Flutter app** — consumes the same API; adds push notifications.
+3 -3
View File
@@ -12,7 +12,7 @@ tags: [synthesis]
**Connectivity: ✅ solved.** The [[jc-6620|JC-6620]] controller inside the [[anfu-charger|charging pile]] reliably dials out to the CSMS — verified both on the charger's own LAN (`192.168.2.114:9000`) and across the NAT boundary on the WAN subnet (`10.0.10.203:9000`). Getting here required the fixes catalogued in [[troubleshooting]]; the network layout is in [[network-topology]].
**Software: production [[backend]] built (2026-07-11), including the web panel.** `station.py` was ported into the `../backend/` package: one FastAPI process on port 9000 = CSMS WebSocket + `/api/*` (charger control, allowlist CRUD, runtime learn-mode flip) + [[wifi-relays|Tuya relay]] on/off/toggle + **multi-user auth** (username/password, per-resource scopes: gun 1 / gun 2 / per-relay / admin, per-gun-restrictable RFID cards — [[authorization]]) + **consumption tracking** (SQLite: who charged, when, how many kWh, per-minute meter samples) + the **PWA control panel** at `/` (login, scope-filtered start/stop buttons, relay toggles, history, admin). Smoke-tested (45 checks incl. a fake charge point over the real WS route); ✅ live charger connects to it since 2026-07-11 evening; ⚠️ panel untested from a real phone. All state lives in one SQLite file (`backend.db`) — no config file, every change via API/panel takes effect immediately. The [[csms-toolkit]] (`../discovering/`) remains as diagnostic tooling.
**Software: production [[backend]] built (2026-07-11), including the web panel.** `station.py` was ported into the `../backend/` package: one FastAPI process on port 9000 = CSMS WebSocket + `/api/*` (charger control, allowlist CRUD, runtime learn-mode flip) + [[wifi-relays|Tuya relay]] on/off/toggle + **multi-user auth** (username/password, per-resource scopes: gun 1 / gun 2 / per-relay / admin, per-gun-restrictable RFID cards — [[authorization]]) + **consumption tracking** (SQLite: who charged, when, how many kWh, per-minute meter samples) + the **PWA control panel** at `/` (login, scope-filtered start/stop buttons, relay toggles, history, admin). Smoke-tested (54 checks incl. a fake charge point over the real WS route); ✅ live charger connects to it since 2026-07-11 evening; ⚠️ panel untested from a real phone. All state lives in one SQLite file (`backend.db`) — no config file, every change via API/panel takes effect immediately. **Late 2026-07-11:** learn mode replaced by the **pending-card review workflow** (unknown taps refused + queued for admin approve/reject), sessions audit the **auth method** (card vs in-app), and the panel was rebuilt as a **React app** ([[frontend]]). The [[csms-toolkit]] (`../discovering/`) remains as diagnostic tooling.
**Capabilities: ✅ known.** The live probe ([[2026-07-09-discovery-eu092025]]) identified the pile as SimpleCharge "MultiSocketCharger" (fw 1.24.0620.1, OCPP ID `eu092025`) with **two guns**, RemoteTrigger (verified), SmartCharging, Reservation, a 6-entry local auth list, and per-minute meter data including SoC. Only Autocharge remains unknown (physical test pending; `MacEnabled` is a lead — [[authorization]]).
@@ -28,8 +28,8 @@ Hardware surprise: this is a **DC-capable multi-standard charger** (gun 1 EU, gu
1. ~~Cut the live charger over to the backend~~ — ✅ done 2026-07-11 evening: `eu092025` connects to `python -m backend.main` (verified in events.jsonl). Remaining: a card tap + a panel button-push on the live charger.
2. **Create the real users** — `python -m backend.users add <name> --scopes ...` for each household member (the API stays open until the first user exists).
3. **Extract the Tuya local keys** (`tinytuya wizard` — steps in [[wifi-relays]]) and register them via `PUT /api/relays/<name>` → relays become controllable.
4. **Flip learn mode off** — both cards + the app token are enrolled; switchable from the panel's Admin tab or `POST /api/mode?learn=false`, no restart. (Only wait if more cards need tapping.)
5. **Test the panel from a phone** — it's built and serving at `http://<host>:9000/`; verify login, a real button-push start on a ready gun, and add-to-home-screen over [[netbird|NetBird]].
4. **Restart the backend once** to pick up the React panel + pending-card workflow (state changes never need restarts; code updates do).
5. **Test the panel from a phone** — `http://<host>:9000/`; verify login, a real button-push start on a ready gun, the pending-card banner (tap an unenrolled card), and add-to-home-screen over [[netbird|NetBird]].
6. **Resolve the ❓ remote-stop restart question** — did the gun-2 session auto-restart from auth cache after RemoteStop, or was the card re-tapped? Affects the app's Stop button UX ([[authorization]]).
## Open decisions ❓