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
+157
View File
@@ -0,0 +1,157 @@
"""User accounts, password hashing, sessions, and the scope matcher.
Everything is stdlib crypto: PBKDF2-HMAC-SHA256 for passwords, HMAC-signed
stateless tokens for sessions (they survive backend restarts; "logout" is the
client dropping its cookie). Users live in config.json -> "users":
"julian": {
"password": "pbkdf2$600000$<salt hex>$<hash hex>",
"scopes": ["admin"], # or charger:<cp>:<gun>, relay:<name>
"id_tag": "app-julian" # idTag used for their remote starts
}
Scopes are matched with fnmatch, so "relay:*" or "charger:eu092025:*" work.
"admin" implies every scope and is required for management endpoints.
CLI (from the repo root):
venv\\Scripts\\python -m backend.users add <name> --scopes admin
venv\\Scripts\\python -m backend.users list
venv\\Scripts\\python -m backend.users remove <name>
"""
import base64
import hashlib
import hmac
import secrets
import time
from fnmatch import fnmatch
from .config import CONFIG, save
PBKDF2_ITERATIONS = 600_000
SESSION_TTL = 30 * 24 * 3600 # 30 days
# ---- passwords ----
def hash_password(password: str) -> str:
salt = secrets.token_hex(16)
digest = hashlib.pbkdf2_hmac(
"sha256", password.encode(), bytes.fromhex(salt), PBKDF2_ITERATIONS
)
return f"pbkdf2${PBKDF2_ITERATIONS}${salt}${digest.hex()}"
def verify_password(password: str, stored: str) -> bool:
try:
scheme, iterations, salt, expected = stored.split("$")
if scheme != "pbkdf2":
return False
digest = hashlib.pbkdf2_hmac(
"sha256", password.encode(), bytes.fromhex(salt), int(iterations)
)
return hmac.compare_digest(digest.hex(), expected)
except (ValueError, AttributeError):
return False
# ---- sessions (stateless HMAC tokens) ----
def _secret() -> bytes:
return CONFIG["session_secret"].encode()
def _sign(payload: str) -> str:
return hmac.new(_secret(), payload.encode(), hashlib.sha256).hexdigest()
def mint_session(username: str) -> str:
payload = f"{username}|{int(time.time()) + SESSION_TTL}"
token = f"{payload}|{_sign(payload)}"
return base64.urlsafe_b64encode(token.encode()).decode()
def verify_session(token: str) -> str | None:
"""Return the username for a valid, unexpired token; None otherwise."""
try:
username, expires, signature = (
base64.urlsafe_b64decode(token.encode()).decode().split("|")
)
except Exception:
return None
if not hmac.compare_digest(_sign(f"{username}|{expires}"), signature):
return None
if int(expires) < time.time():
return None
if username not in CONFIG["users"]:
return None # deleted users lose their sessions
return username
# ---- scopes ----
def allowed(scopes: list, needed: str) -> bool:
return any(
grant in ("*", "admin") or fnmatch(needed, grant) for grant in scopes
)
# ---- user management (used by the CLI and the admin API) ----
def set_user(name: str, password: str | None = None, scopes: list | None = None) -> dict:
user = CONFIG["users"].get(name, {"scopes": [], "id_tag": f"app-{name}"})
if password is not None:
user["password"] = hash_password(password)
if scopes is not None:
user["scopes"] = scopes
user.setdefault("id_tag", f"app-{name}")
if "password" not in user:
raise ValueError(f"new user {name!r} needs a password")
CONFIG["users"][name] = user
save()
return user
def remove_user(name: str) -> None:
if CONFIG["users"].pop(name, None) is None:
raise KeyError(name)
save()
def public_view(name: str, user: dict) -> dict:
"""A user entry without the password hash — safe for /api/me and /api/users."""
return {"name": name, "scopes": user["scopes"], "id_tag": user.get("id_tag")}
def _cli() -> None:
import argparse
import getpass
parser = argparse.ArgumentParser(prog="backend.users", description=__doc__)
sub = parser.add_subparsers(dest="cmd", required=True)
p_add = sub.add_parser("add", help="add a user or update an existing one")
p_add.add_argument("name")
p_add.add_argument("--scopes", nargs="+", default=None,
help='e.g. admin, "charger:eu092025:1", "relay:*"')
sub.add_parser("list", help="list users and their scopes")
p_rm = sub.add_parser("remove", help="delete a user")
p_rm.add_argument("name")
args = parser.parse_args()
if args.cmd == "list":
for name, user in CONFIG["users"].items():
print(f"{name:20} scopes={user['scopes']} id_tag={user.get('id_tag')}")
if not CONFIG["users"]:
print("no users configured — the API is OPEN (anonymous admin)")
elif args.cmd == "add":
existing = args.name in CONFIG["users"]
password = getpass.getpass(f"{'New ' if not existing else ''}password for {args.name!r}: ")
if not existing or password:
confirm = getpass.getpass("Repeat password: ")
if password != confirm:
raise SystemExit("passwords do not match")
user = set_user(args.name, password=password or None, scopes=args.scopes)
print(f"{'updated' if existing else 'created'} {args.name!r}: scopes={user['scopes']}")
elif args.cmd == "remove":
remove_user(args.name)
print(f"removed {args.name!r}")
if __name__ == "__main__":
_cli()