"""Подписывает JWT ключом из .storage/auth Home Assistant (внутри CT 106).""" import base64 import hashlib import hmac import json import time import urllib.request AUTH = "/opt/smart-lxc/homeassistant/config/.storage/auth" BASE = "http://127.0.0.1:8123" def b64(data): return base64.urlsafe_b64encode(data).rstrip(b"=") def make_jwt(payload, key): header = b64(json.dumps({"alg": "HS256", "typ": "JWT"}).encode()) body = b64(json.dumps(payload).encode()) signing = header + b"." + body if isinstance(key, str): key = key.encode() sig = b64(hmac.new(key, signing, hashlib.sha256).digest()) return (signing + b"." + sig).decode() def main(): try: data = json.load(open(AUTH, encoding="utf-8"))["data"] except Exception as e: print(" нет доступа к auth:", str(e)[:80]) return 1 users = {u["id"]: u for u in data.get("users") or []} tokens = [t for t in (data.get("refresh_tokens") or []) if t.get("token_type") in ("normal", "long_lived_access_token") and t.get("jwt_key")] print(" пользователей:", len(users), "| токенов с ключом:", len(tokens)) for t in tokens: user = users.get(t.get("user_id")) or {} if user.get("is_active") is False: continue tok = make_jwt({"iss": t["id"], "iat": int(time.time()), "exp": int(time.time()) + 365 * 24 * 3600}, t["jwt_key"]) req = urllib.request.Request(BASE + "/api/", headers={"Authorization": "Bearer " + tok}) try: with urllib.request.urlopen(req, timeout=10) as r: body = json.loads(r.read() or b"{}") except Exception as e: continue print(" ✅ доступ:", body.get("message"), "| пользователь:", user.get("name")) open("/root/.ha-token", "w", encoding="utf-8").write(tok) import os os.chmod("/root/.ha-token", 0o600) return 0 print(" не удалось подписать токен") return 1 if __name__ == "__main__": raise SystemExit(main())