feat 🔌 shelly-mcp set_auth-Tool + Digest-Auth-Fallback (TP17 Geräte-PW)
- set_auth: setzt einheitliches Admin-PW (SHELLY_DEVICE_PW) via Shelly.SetAuth,
realm=Geräte-ID, ha1=sha256("admin:realm:pw") pro Gerät; guarded (confirm/dry-run).
- _rpc: HTTP-Digest-Fallback (user admin) bei 401 → Geräte bleiben nach set_auth managebar.
- .env.example/README: SHELLY_DEVICE_PW dokumentiert (getrennt vom WLAN-PSK); Rollout mit PW-Schritt.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -14,9 +14,11 @@ Config via env (see .env.example):
|
||||
|
||||
Run: python3 server.py (loads ./.env if present)
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
# reuse the read-only recon logic
|
||||
@@ -38,6 +40,7 @@ if os.path.exists(_envfile):
|
||||
|
||||
IOT_SSID = os.environ.get("SHELLY_IOT_SSID", "dirtyvader-iot")
|
||||
IOT_PSK = os.environ.get("SHELLY_IOT_PSK", "")
|
||||
DEVICE_PW = os.environ.get("SHELLY_DEVICE_PW", "") # uniform admin password (Shelly.SetAuth)
|
||||
SWEEP = os.environ.get("SHELLY_SWEEP", "10.40.41.180-250")
|
||||
HOST = os.environ.get("SHELLY_MCP_HOST", "127.0.0.1")
|
||||
PORT = int(os.environ.get("SHELLY_MCP_PORT", "3030"))
|
||||
@@ -50,12 +53,27 @@ mcp = FastMCP("shelly-mcp", host=HOST, port=PORT, stateless_http=True,
|
||||
|
||||
# ---------------- helpers ----------------
|
||||
def _rpc(ip: str, method: str, params: dict | None = None, timeout: float = 6.0) -> dict:
|
||||
"""Gen2+ Shelly RPC over HTTP POST /rpc."""
|
||||
"""Gen2+ Shelly RPC over HTTP POST /rpc.
|
||||
|
||||
Falls back to HTTP digest auth (user 'admin' / SHELLY_DEVICE_PW) if the
|
||||
device requires authentication — so devices stay manageable after set_auth.
|
||||
"""
|
||||
body = json.dumps({"id": 1, "method": method, "params": params or {}}).encode()
|
||||
req = urllib.request.Request(f"http://{ip}/rpc", data=body,
|
||||
headers={"Content-Type": "application/json"})
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.load(r)
|
||||
|
||||
def _mk():
|
||||
return urllib.request.Request(f"http://{ip}/rpc", data=body,
|
||||
headers={"Content-Type": "application/json"})
|
||||
try:
|
||||
with urllib.request.urlopen(_mk(), timeout=timeout) as r:
|
||||
return json.load(r)
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code == 401 and DEVICE_PW:
|
||||
mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
|
||||
mgr.add_password(None, f"http://{ip}/rpc", "admin", DEVICE_PW)
|
||||
opener = urllib.request.build_opener(urllib.request.HTTPDigestAuthHandler(mgr))
|
||||
with opener.open(_mk(), timeout=timeout) as r:
|
||||
return json.load(r)
|
||||
raise
|
||||
|
||||
|
||||
def _sweep(spec: str | None = None) -> list[dict]:
|
||||
@@ -138,6 +156,41 @@ def set_sta(ip: str, confirm: bool = False, ssid: str | None = None) -> dict:
|
||||
return {**plan, "ok": False, "error": f"{type(e).__name__}: {e}"}
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def set_auth(ip: str, confirm: bool = False) -> dict:
|
||||
"""MIGRATION ACTION — set the uniform admin password (SHELLY_DEVICE_PW) on a Shelly (Gen2+).
|
||||
|
||||
Enables HTTP digest auth: user 'admin', realm = the device id (per-device),
|
||||
ha1 = sha256("admin:<realm>:<password>"). Same cleartext password across the
|
||||
fleet, different ha1 per device. After this, _rpc authenticates automatically.
|
||||
|
||||
Run this AFTER the device is verified on VLAN30 (last step per device).
|
||||
- confirm MUST be true to write; SHELLY_DEVICE_PW must be set.
|
||||
- confirm=false is a dry-run: returns the computed realm (no write).
|
||||
"""
|
||||
if not DEVICE_PW:
|
||||
return {"ip": ip, "ok": False, "error": "SHELLY_DEVICE_PW not set in environment"}
|
||||
try:
|
||||
info = _rpc(ip, "Shelly.GetDeviceInfo").get("result") or {}
|
||||
except Exception as e:
|
||||
return {"ip": ip, "ok": False, "error": f"{type(e).__name__}: {e}"}
|
||||
realm = info.get("id")
|
||||
if not realm:
|
||||
return {"ip": ip, "ok": False, "error": "could not read device id (realm)"}
|
||||
ha1 = hashlib.sha256(f"admin:{realm}:{DEVICE_PW}".encode()).hexdigest()
|
||||
if not confirm:
|
||||
return {"ip": ip, "ok": False, "dry_run": True, "realm": realm,
|
||||
"would_send": {"method": "Shelly.SetAuth",
|
||||
"params": {"user": "admin", "realm": realm,
|
||||
"ha1": ha1[:12] + "…"}}}
|
||||
try:
|
||||
res = _rpc(ip, "Shelly.SetAuth", {"user": "admin", "realm": realm, "ha1": ha1})
|
||||
return {"ip": ip, "ok": True, "realm": realm, "set_result": res,
|
||||
"note": "admin auth enabled; future RPC uses digest via SHELLY_DEVICE_PW"}
|
||||
except Exception as e:
|
||||
return {"ip": ip, "ok": False, "error": f"{type(e).__name__}: {e}"}
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def verify_on_iot(ip: str) -> dict:
|
||||
"""Verify a device now sits on the IOT SSID / VLAN30 (post-migration check).
|
||||
|
||||
Reference in New Issue
Block a user