feat(backend): production backend — CSMS, multi-user auth, relays, session store, web panel

One FastAPI process on port 9000 (the charger's hardcoded URL), replacing
discovering/station.py for production:

- csms.py: OCPP 1.6J handlers ported from the proven discovery code; the
  decide() gate now supports per-gun RFID restriction ("connectors": [2])
  enforced at StartTransaction
- users.py: username/password auth (PBKDF2), stateless HMAC sessions
  (cookie + bearer, 30 days), fnmatch permission scopes
  (charger:<cp>:<gun>, relay:<name>, admin) and a user CLI
- relays.py: local tinytuya control of the SmartLife/Tuya WiFi relays
  (no cloud; needs one-time id/local-key extraction via tinytuya wizard)
- store.py: SQLite consumption tracking — who charged, when, how many kWh,
  per-minute energy/power/SoC samples; tx ids survive restarts
- routes.py: /api/* with per-scope checks, allowlist/user CRUD, runtime
  learn-mode flip, session history with visibility rules
- static/: self-contained vanilla-JS PWA — login, per-gun start/stop gated
  by scope + gun readiness, relay toggles, history, admin tab

config.json (password hashes, session secret, Tuya keys) and sessions.db
are gitignored; config.example.json documents the shape. Covered by a
37-check smoke test incl. a fake charge point over the real WS route.
This commit is contained in:
2026-07-11 18:58:09 +02:00
parent 5c88e8fa3c
commit d7b17d9cb2
16 changed files with 1794 additions and 0 deletions
+47
View File
@@ -0,0 +1,47 @@
"""Backend configuration — one JSON file, config.json, next to this module.
Holds the charger allowlist (learn_mode + authorized idTags, same shape the
discovery phase used), the user accounts with their permission scopes, and the
Tuya relay registry. config.json is gitignored because it contains secrets
(password hashes, the session-signing secret, Tuya local keys);
config.example.json documents the shape.
"""
import json
import secrets
from pathlib import Path
HERE = Path(__file__).resolve().parent
CONFIG_PATH = HERE / "config.json"
DEFAULTS = {
"learn_mode": True,
"users": {}, # name -> {"password": pbkdf2 hash, "scopes": [...], "id_tag": ...}
"authorized": {}, # idTag -> {"name", "kind": "card|app|car", optional "connectors": [1]}
"relays": {}, # name -> {"id", "key", "ip", "version", "switch", "label"}
}
def load() -> dict:
if CONFIG_PATH.exists():
cfg = json.loads(CONFIG_PATH.read_text(encoding="utf-8"))
else:
cfg = {}
for key, default in DEFAULTS.items():
cfg.setdefault(key, default if not isinstance(default, dict) else dict(default))
return cfg
CONFIG = load()
if not CONFIG.get("session_secret"):
CONFIG["session_secret"] = secrets.token_hex(32)
CONFIG_PATH.write_text(
json.dumps(CONFIG, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
)
def save() -> None:
CONFIG_PATH.write_text(
json.dumps(CONFIG, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
)