feat(backend): link cards to users; charger-qualified gun restrictions; config-driven gun labels

- Allowlist entries take "user": <username> — sessions started with that
  card attribute to the person, and the owner sees their card's history
  even without gun-wide permissions (ownership looked up live)
- "guns": ["eu092025:2"] (fnmatch) replaces the charger-blind
  "connectors": [2] restriction — safe with multiple chargers
- New "chargers" config section provides per-charger/per-gun display
  names; the panel no longer hardcodes the Anfu gun labels
- Panel admin tab: owner dropdown + guns field on card entries
- Smoke test: 42 checks, incl. retroactive history visibility after
  linking a card and rejection of links to unknown users
This commit is contained in:
2026-07-11 20:03:36 +02:00
parent 3326c8d16c
commit 70c2fe1210
8 changed files with 85 additions and 39 deletions
+15 -4
View File
@@ -19,14 +19,25 @@
} }
}, },
"authorized": { "authorized": {
"1000000000000000": { "name": "Example RFID card, works on both guns", "kind": "card" }, "1000000000000000": {
"1000000000000001": { "name": "Card linked to a user, works everywhere",
"name": "Example RFID card restricted to gun 2",
"kind": "card", "kind": "card",
"connectors": [2] "user": "admin-user"
},
"1000000000000001": {
"name": "Card restricted to gun 2 of one charger",
"kind": "card",
"user": "gun1-only-user",
"guns": ["eu092025:2"]
}, },
"app-remote": { "name": "Web/app remote start token", "kind": "app" } "app-remote": { "name": "Web/app remote start token", "kind": "app" }
}, },
"chargers": {
"eu092025": {
"label": "Anfu 60kW",
"guns": { "1": "Gun 1 · EU (CCS)", "2": "Gun 2 · GB/T" }
}
},
"relays": { "relays": {
"example-relay": { "example-relay": {
"id": "<tuya device id from tinytuya wizard>", "id": "<tuya device id from tinytuya wizard>",
+3 -1
View File
@@ -17,8 +17,10 @@ CONFIG_PATH = HERE / "config.json"
DEFAULTS = { DEFAULTS = {
"learn_mode": True, "learn_mode": True,
"users": {}, # name -> {"password": pbkdf2 hash, "scopes": [...], "id_tag": ...} "users": {}, # name -> {"password": pbkdf2 hash, "scopes": [...], "id_tag": ...}
"authorized": {}, # idTag -> {"name", "kind": "card|app|car", optional "connectors": [1]} "authorized": {}, # idTag -> {"name", "kind": "card|app|car",
# optional "user": owner, "guns": ["eu092025:2"]}
"relays": {}, # name -> {"id", "key", "ip", "version", "switch", "label"} "relays": {}, # name -> {"id", "key", "ip", "version", "switch", "label"}
"chargers": {}, # cp_id -> {"label", "guns": {"1": "display name", ...}} (UI only)
} }
+21 -13
View File
@@ -10,6 +10,7 @@ import asyncio
import json import json
import logging import logging
from collections import deque from collections import deque
from fnmatch import fnmatch
from typing import Optional from typing import Optional
from fastapi import WebSocket, WebSocketDisconnect from fastapi import WebSocket, WebSocketDisconnect
@@ -46,21 +47,24 @@ TRIGGERABLE = {
} }
def decide(id_tag: str, context: str, connector: Optional[int] = None) -> AuthorizationStatus: def decide(id_tag: str, context: str, connector: Optional[int] = None,
cp: Optional[str] = None) -> AuthorizationStatus:
"""The one gate every auth method flows through: is this idTag allowed? """The one gate every auth method flows through: is this idTag allowed?
An allowlist entry may carry "connectors": [1] to restrict a card to An allowlist entry may carry "guns": ["eu092025:2"] to restrict a card to
specific guns. Only StartTransaction knows the connector, so the per-gun specific guns of specific chargers (fnmatch patterns, so "eu092025:*"
check fires there; a plain Authorize (card tap) still accepts a known card works). Only StartTransaction knows the connector, so the per-gun check
— which matches this charger, since AuthorizeRemoteTxRequests=false means fires there; a plain Authorize (card tap) still accepts a known card —
which matches this charger, since AuthorizeRemoteTxRequests=false means
StartTransaction is the decisive call anyway. StartTransaction is the decisive call anyway.
""" """
entry = CONFIG["authorized"].get(id_tag) entry = CONFIG["authorized"].get(id_tag)
known = entry is not None known = entry is not None
if known and connector is not None and entry.get("connectors") \ gun = f"{cp}:{connector}" if cp and connector is not None else None
and connector not in entry["connectors"]: if known and gun and entry.get("guns") \
log.warning("[NO] REJECTED idTag=%r (%s) not allowed on connector %s (allowed: %s)", and not any(fnmatch(gun, pat) for pat in entry["guns"]):
id_tag, entry.get("name", "?"), connector, entry["connectors"]) log.warning("[NO] REJECTED idTag=%r (%s) not allowed on %s (allowed: %s)",
id_tag, entry.get("name", "?"), gun, entry["guns"])
status = AuthorizationStatus.invalid status = AuthorizationStatus.invalid
elif known: elif known:
name = entry.get("name", "?") name = entry.get("name", "?")
@@ -82,10 +86,14 @@ def decide(id_tag: str, context: str, connector: Optional[int] = None) -> Author
def resolve_who(id_tag: str) -> str: def resolve_who(id_tag: str) -> str:
"""Human label for a session: allowlist entry name, username, or the raw tag.""" """Human label for a session: the card's owning user, the allowlist entry
name, the username behind an app idTag, or the raw tag — in that order."""
entry = CONFIG["authorized"].get(id_tag) entry = CONFIG["authorized"].get(id_tag)
if entry and entry.get("name"): if entry:
return entry["name"] if entry.get("user"):
return entry["user"]
if entry.get("name"):
return entry["name"]
for username, user in CONFIG["users"].items(): for username, user in CONFIG["users"].items():
if user.get("id_tag") == id_tag: if user.get("id_tag") == id_tag:
return username return username
@@ -125,7 +133,7 @@ class ChargePoint(OcppChargePoint):
@on(Action.start_transaction) @on(Action.start_transaction)
async def on_start_transaction(self, connector_id, id_tag, meter_start, timestamp, **kwargs): async def on_start_transaction(self, connector_id, id_tag, meter_start, timestamp, **kwargs):
status = decide(id_tag, f"StartTransaction (connector {connector_id})", status = decide(id_tag, f"StartTransaction (connector {connector_id})",
connector=connector_id) connector=connector_id, cp=self.id)
if status == AuthorizationStatus.accepted: if status == AuthorizationStatus.accepted:
_tx_counter["n"] += 1 _tx_counter["n"] += 1
tx = _tx_counter["n"] tx = _tx_counter["n"]
+15 -7
View File
@@ -119,6 +119,7 @@ async def api_status(user: dict = Depends(current_user)):
"active_transactions": csms.ACTIVE_TX, "active_transactions": csms.ACTIVE_TX,
"recent_auth_events": list(csms.AUTH_EVENTS), "recent_auth_events": list(csms.AUTH_EVENTS),
"relays": _visible_relays(user), "relays": _visible_relays(user),
"chargers": CONFIG["chargers"], # display labels for the panel
} }
@@ -197,11 +198,15 @@ async def charger_probe(cp: Optional[str] = None, user: dict = Depends(current_u
# ---- session history: who charged when and how many kWh ---- # ---- session history: who charged when and how many kWh ----
def _may_see_session(user: dict, s: dict) -> bool: def _may_see_session(user: dict, s: dict) -> bool:
"""Own sessions, sessions on guns you control, or everything for admin.""" """Own sessions (own app starts or own cards), sessions on guns you
return ( control, or everything for admin. Card ownership is looked up live, so
s["id_tag"] == user.get("id_tag") linking a card to a user retroactively shows them its history."""
or users.allowed(user["scopes"], f"charger:{s['cp']}:{s['connector']}") if users.allowed(user["scopes"], f"charger:{s['cp']}:{s['connector']}"):
) return True
if s["id_tag"] == user.get("id_tag"):
return True
entry = CONFIG["authorized"].get(s["id_tag"])
return bool(entry and entry.get("user") == user["name"])
@router.get("/sessions") @router.get("/sessions")
@@ -225,8 +230,9 @@ async def session_samples(tx: int, user: dict = Depends(current_user)):
# ---- allowlist management (admin) ---- # ---- allowlist management (admin) ----
class AllowlistEntry(BaseModel): class AllowlistEntry(BaseModel):
name: str name: str
kind: str = "card" # card | app | car kind: str = "card" # card | app | car
connectors: Optional[list[int]] = None # e.g. [2] = this card only works on gun 2 user: Optional[str] = None # owning username -> sessions attribute to them
guns: Optional[list[str]] = None # e.g. ["eu092025:2"]; fnmatch, empty = all guns
@router.get("/allowlist") @router.get("/allowlist")
@@ -243,6 +249,8 @@ async def allowlist_get(user: dict = Depends(current_user)):
async def allowlist_put(id_tag: str, entry: AllowlistEntry, async def allowlist_put(id_tag: str, entry: AllowlistEntry,
user: dict = Depends(current_user)): user: dict = Depends(current_user)):
need(user, "admin") need(user, "admin")
if entry.user is not None and entry.user not in CONFIG["users"]:
raise HTTPException(400, f"cannot link card to unknown user {entry.user!r}")
CONFIG["authorized"][id_tag] = entry.model_dump(exclude_none=True) CONFIG["authorized"][id_tag] = entry.model_dump(exclude_none=True)
save() save()
log.info("allowlist: added/updated %r (%s)", id_tag, entry.name) log.info("allowlist: added/updated %r (%s)", id_tag, entry.name)
+19 -12
View File
@@ -143,22 +143,23 @@
</div> </div>
</div> </div>
<div class="card"> <div class="card">
<h2>Allowlist</h2> <h2>Cards &amp; tags</h2>
<div class="scroll"><table> <div class="scroll"><table>
<thead><tr><th>idTag</th><th>Name</th><th>Guns</th><th></th></tr></thead> <thead><tr><th>idTag</th><th>Name</th><th>User</th><th>Guns</th><th></th></tr></thead>
<tbody id="allowlist"></tbody> <tbody id="allowlist"></tbody>
</table></div> </table></div>
<div id="seen-tags"></div> <div id="seen-tags"></div>
<form onsubmit="return addAllowlist(event)" style="margin-top:10px"> <form onsubmit="return addAllowlist(event)" style="margin-top:10px">
<div class="row"><input id="a-tag" placeholder="idTag" required></div> <div class="row"><input id="a-tag" placeholder="idTag" required></div>
<div class="row"> <div class="row">
<input id="a-name" placeholder="Name (e.g. RFID card C)" required> <input id="a-name" placeholder="Name (e.g. Card blue)" required>
<select id="a-kind" style="width:110px"><option>card</option><option>app</option><option>car</option></select> <select id="a-kind" style="width:110px"><option>card</option><option>app</option><option>car</option></select>
</div> </div>
<div class="row"> <div class="row">
<input id="a-conn" placeholder="Guns, e.g. 1,2 — empty = all"> <select id="a-user"><option value="">No user linked</option></select>
<button class="small">Add</button> <input id="a-guns" placeholder="Guns, e.g. eu092025:2 — empty = all">
</div> </div>
<div class="row"><button class="small">Save card</button></div>
</form> </form>
</div> </div>
<div class="card"> <div class="card">
@@ -308,8 +309,10 @@ function renderGuns() {
.sort((a, b) => a.conn - b.conn); .sort((a, b) => a.conn - b.conn);
if (!conns.length) if (!conns.length)
html += `<div class="card"><div class="sub">${esc(cp)} connected — no gun status yet</div></div>`; html += `<div class="card"><div class="sub">${esc(cp)} connected — no gun status yet</div></div>`;
const cpCfg = (status.chargers || {})[cp] || {};
for (const { conn, st } of conns) { for (const { conn, st } of conns) {
const gunName = conn === 1 ? "Gun 1 · EU (CCS)" : conn === 2 ? "Gun 2 · GB/T" : `Gun ${conn}`; let gunName = (cpCfg.guns || {})[conn] || `Gun ${conn}`;
if (cps.length > 1) gunName = `${cpCfg.label || cp} · ${gunName}`;
const active = txByGun[`${cp}/${conn}`]; const active = txByGun[`${cp}/${conn}`];
const may = scopeOk(`charger:${cp}:${conn}`); const may = scopeOk(`charger:${cp}:${conn}`);
const canStart = may && !active && (st === "Preparing" || st === "Available"); const canStart = may && !active && (st === "Preparing" || st === "Available");
@@ -408,22 +411,24 @@ async function loadSessions() {
// ---- admin tab ---- // ---- admin tab ----
async function loadAdmin() { async function loadAdmin() {
try { try {
const al = await api("/allowlist"); const [al, users] = await Promise.all([api("/allowlist"), api("/users")]);
$("mode-label").textContent = al.learn_mode ? "Learn mode" : "Enforcing allowlist"; $("mode-label").textContent = al.learn_mode ? "Learn mode" : "Enforcing allowlist";
$("mode-btn").textContent = al.learn_mode ? "Enforce" : "Back to learn"; $("mode-btn").textContent = al.learn_mode ? "Enforce" : "Back to learn";
$("mode-btn").dataset.learn = al.learn_mode; $("mode-btn").dataset.learn = al.learn_mode;
$("allowlist").innerHTML = Object.entries(al.authorized).map(([tag, e]) => `<tr> $("allowlist").innerHTML = Object.entries(al.authorized).map(([tag, e]) => `<tr>
<td class="sub">${esc(tag)}</td><td>${esc(e.name)}</td> <td class="sub">${esc(tag)}</td><td>${esc(e.name)}</td>
<td>${e.connectors ? e.connectors.join(",") : "all"}</td> <td>${e.user ? esc(e.user) : '<span class="sub">—</span>'}</td>
<td class="sub">${e.guns ? esc(e.guns.join(", ")) : "all"}</td>
<td><button class="danger small" onclick="delAllowlist('${esc(tag)}')">&#10005;</button></td> <td><button class="danger small" onclick="delAllowlist('${esc(tag)}')">&#10005;</button></td>
</tr>`).join(""); </tr>`).join("");
$("a-user").innerHTML = `<option value="">No user linked</option>` +
users.map(u => `<option value="${esc(u.name)}">${esc(u.name)}</option>`).join("");
const seen = Object.entries(al.seen || {}).filter(([tag]) => !(tag in al.authorized)); const seen = Object.entries(al.seen || {}).filter(([tag]) => !(tag in al.authorized));
$("seen-tags").innerHTML = seen.length $("seen-tags").innerHTML = seen.length
? `<div class="sub" style="margin-top:8px">Seen but not enrolled:</div>` + seen.map(([tag, s]) => ? `<div class="sub" style="margin-top:8px">Seen but not enrolled:</div>` + seen.map(([tag, s]) =>
`<div class="row" style="padding:4px 0"><div class="grow sub">${esc(tag)} (&times;${s.count})</div> `<div class="row" style="padding:4px 0"><div class="grow sub">${esc(tag)} (&times;${s.count})</div>
<button class="small secondary" onclick="$('a-tag').value='${esc(tag)}';$('a-name').focus()">Enroll</button></div>`).join("") <button class="small secondary" onclick="$('a-tag').value='${esc(tag)}';$('a-name').focus()">Enroll</button></div>`).join("")
: ""; : "";
const users = await api("/users");
$("users").innerHTML = users.map(u => `<tr> $("users").innerHTML = users.map(u => `<tr>
<td>${esc(u.name)}</td><td class="sub">${esc(u.scopes.join(" "))}</td> <td>${esc(u.name)}</td><td class="sub">${esc(u.scopes.join(" "))}</td>
<td><button class="danger small" onclick="delUser('${esc(u.name)}')">&#10005;</button></td> <td><button class="danger small" onclick="delUser('${esc(u.name)}')">&#10005;</button></td>
@@ -441,12 +446,14 @@ async function toggleMode() {
async function addAllowlist(ev) { async function addAllowlist(ev) {
ev.preventDefault(); ev.preventDefault();
const body = { name: $("a-name").value.trim(), kind: $("a-kind").value }; const body = { name: $("a-name").value.trim(), kind: $("a-kind").value };
const conns = $("a-conn").value.trim(); if ($("a-user").value) body.user = $("a-user").value;
if (conns) body.connectors = conns.split(",").map(s => +s.trim()).filter(Boolean); const guns = $("a-guns").value.trim();
if (guns) body.guns = guns.split(",").map(s => s.trim()).filter(Boolean);
try { try {
await api(`/allowlist/${encodeURIComponent($("a-tag").value.trim())}`, await api(`/allowlist/${encodeURIComponent($("a-tag").value.trim())}`,
{ method: "PUT", body: JSON.stringify(body) }); { method: "PUT", body: JSON.stringify(body) });
$("a-tag").value = $("a-name").value = $("a-conn").value = ""; $("a-tag").value = $("a-name").value = $("a-guns").value = "";
$("a-user").value = "";
loadAdmin(); loadAdmin();
} catch (e) { toast(e.message); } } catch (e) { toast(e.message); }
return false; return false;
+6 -1
View File
@@ -17,7 +17,12 @@ First card tapped on the real charger: idTag `1000000000000393` → Authorize
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"`). 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"`).
Since 2026-07-11 a card can be **restricted per gun**: an optional `"connectors": [2]` on its allowlist entry makes `decide()` reject it on any other connector. The check fires at `StartTransaction` (the only message that carries the connector); the preceding `Authorize` (tap) still says Accepted — harmless on this charger, because `AuthorizeRemoteTxRequests=false` makes `StartTransaction` the decisive call anyway (see the probe facts below). ✅ verified with a fake charge point: gun-2-only card → `Invalid`/tx 0 on gun 1, Accepted on gun 2. Since 2026-07-11 a card can be **linked to a user and restricted per gun**:
- `"user": "julian"` on the allowlist entry ties the card to a user account — sessions started with it attribute to that person in the history, and the owner sees their card's sessions even without gun-wide permissions (ownership is looked up live, so linking is retroactive for history visibility).
- `"guns": ["eu092025:2"]` restricts the card to specific guns, **charger-qualified** (fnmatch patterns, so `"eu092025:*"` = all guns of one charger) — multi-charger-safe by construction. The check fires at `StartTransaction` (the only message that carries the connector); the preceding `Authorize` (tap) still says Accepted — harmless on this charger, because `AuthorizeRemoteTxRequests=false` makes `StartTransaction` the decisive call anyway (see the probe facts below). ✅ verified with a fake charge point: gun-2-only card → `Invalid`/tx 0 on gun 1, Accepted on gun 2.
Both are editable from the panel's Admin tab (owner dropdown + guns field).
## 2. By vehicle / chassis — ❌ CLOSED: not supported (2026-07-09) ## 2. By vehicle / chassis — ❌ CLOSED: not supported (2026-07-09)
+2 -1
View File
@@ -40,7 +40,8 @@ backend/ (run: venv\Scripts\python -m backend.main, from the repo root)
## Design facts ## Design facts
- Carried over from the proven discovery code: the `decide()` gate ([[authorization]]) — now with optional per-gun card restriction (`"connectors": [2]`) — 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, learn mode, 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`. - **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. - 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 `sessions.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. - **Consumption tracking** (`store.py`, 2026-07-11): every `StartTransaction` opens a row in `sessions.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.
+4
View File
@@ -71,3 +71,7 @@ Owner requirement: per-user permissions (gun 1 vs gun 2 of eu092025, per-relay o
## [2026-07-11] meta | Consumption tracking (SQLite) + the PWA control panel ## [2026-07-11] meta | Consumption tracking (SQLite) + the PWA control panel
Owner requirement: button-push start when a gun is ready (and permitted) + "who charged when and how many kWh". Built store.py (sessions.db: sessions with resolved who/started/ended/Wh + per-minute samples energy/power/SoC; tx ids survive restarts; stop falls back to store after restart), /api/sessions with visibility rules (own + in-scope guns; admin all), and the phase-3 web panel in backend/static/ (vanilla JS PWA at /: login, gun cards with scope- and readiness-gated Start/Stop, relay toggles, history tab, admin tab with allowlist/users/mode). Fixed a sqlite connection leak (with-connect commits but never closes). Smoke test 28 -> 37 checks, all passing. Updated [[backend]], [[architecture-plan]] (phases 1-3 all done), [[overview]], [[index]]. Owner requirement: button-push start when a gun is ready (and permitted) + "who charged when and how many kWh". Built store.py (sessions.db: sessions with resolved who/started/ended/Wh + per-minute samples energy/power/SoC; tx ids survive restarts; stop falls back to store after restart), /api/sessions with visibility rules (own + in-scope guns; admin all), and the phase-3 web panel in backend/static/ (vanilla JS PWA at /: login, gun cards with scope- and readiness-gated Start/Stop, relay toggles, history tab, admin tab with allowlist/users/mode). Fixed a sqlite connection leak (with-connect commits but never closes). Smoke test 28 -> 37 checks, all passing. Updated [[backend]], [[architecture-plan]] (phases 1-3 all done), [[overview]], [[index]].
## [2026-07-11] meta | Cards linked to users; multi-charger gaps closed
Owner requirements: cards must belong to a person (not float around as "RFID card A (tapped first...)"), and adding a second charger must be clean. Allowlist entries now take "user" (sessions attribute to the person; owner sees their card's history) and charger-qualified "guns": ["eu092025:2"] (fnmatch; replaces the charger-blind "connectors" field). Gun display names moved from hardcoded panel JS to a "chargers" config section served via /api/status. Adding a charger = point it at the same URL with a unique ChargerID + grant charger:<id>:<gun> scopes. Panel admin tab: owner dropdown + guns field. Smoke test 37 -> 42 checks. Updated [[authorization]], [[backend]].