207 lines
10 KiB
Python
207 lines
10 KiB
Python
"""Reference PC bridge. No shell/PowerShell execution; local read-only diagnostics."""
|
|
import asyncio
|
|
import contextlib
|
|
import json
|
|
import os
|
|
import secrets
|
|
import socket
|
|
import sqlite3
|
|
import time
|
|
from pathlib import Path
|
|
from urllib.parse import urlsplit
|
|
|
|
import httpx
|
|
from cryptography.hazmat.primitives.asymmetric import x25519
|
|
from websockets.asyncio.client import connect
|
|
|
|
from .crypto import (load_private, load_public, open_envelope, raw_public, seal, sign,
|
|
verified, verify_device)
|
|
|
|
|
|
class DeviceJournal:
|
|
def __init__(self, path):
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
self.db = sqlite3.connect(path)
|
|
self.db.execute("CREATE TABLE IF NOT EXISTS consumed(turn_id TEXT PRIMARY KEY, ts REAL NOT NULL)")
|
|
self.db.commit()
|
|
|
|
def consume(self, turn):
|
|
with self.db:
|
|
return self.db.execute("INSERT OR IGNORE INTO consumed VALUES(?,?)", (turn, time.time())).rowcount == 1
|
|
|
|
def close(self):
|
|
self.db.close()
|
|
|
|
|
|
async def execute_readonly(text, root: Path | None):
|
|
if text in {"/主机名", "hostname"}:
|
|
return socket.gethostname()
|
|
if text.startswith("/回显 "):
|
|
return text[4:][:16000]
|
|
if text.startswith("/读取 "):
|
|
if root is None:
|
|
return "未配置测试文件目录。"
|
|
base = root.resolve(strict=True)
|
|
try:
|
|
path = (base / text[4:].strip()).resolve(strict=True)
|
|
if path == base or not path.is_relative_to(base) or not path.is_file():
|
|
return "拒绝:文件不在允许的测试目录。"
|
|
if path.stat().st_size > 32768:
|
|
return "拒绝:测试文件超过32KB。"
|
|
return path.read_text(encoding="utf-8")[:16000]
|
|
except (OSError, UnicodeError, ValueError):
|
|
return "拒绝:文件不存在、不可读或不是UTF-8文本。"
|
|
return "当前桥接客户端仅开放只读诊断:/主机名、/回显 内容、/读取 相对路径;尚未接入海诺本地Agent接口。"
|
|
|
|
|
|
class LocalAgent:
|
|
"""Explicit adapter contract, not a claim of compatibility with installer 1.065."""
|
|
def __init__(self, url, transport=None):
|
|
parts = urlsplit(url)
|
|
if parts.scheme != "http" or parts.hostname not in {"127.0.0.1", "::1"} or parts.username or parts.password or parts.fragment:
|
|
raise ValueError("local Agent must use a fixed loopback HTTP endpoint")
|
|
self.url = url
|
|
self.http = httpx.AsyncClient(timeout=30, follow_redirects=False, transport=transport, trust_env=False)
|
|
|
|
async def execute(self, text, owner, turn):
|
|
headers = {}
|
|
if os.environ.get("HN_LOCAL_AGENT_TOKEN"):
|
|
headers["Authorization"] = "Bearer " + os.environ["HN_LOCAL_AGENT_TOKEN"]
|
|
try:
|
|
async with self.http.stream("POST", self.url, headers=headers,
|
|
json={"text": text, "open_id": owner, "turn_id": turn,
|
|
"channel": "im", "read_only": True}) as response:
|
|
if response.status_code != 200:
|
|
return "本机Agent未返回成功结果,请查看本机服务状态。"
|
|
body = b""
|
|
async for chunk in response.aiter_bytes():
|
|
body += chunk
|
|
if len(body) > 65536:
|
|
return "本机Agent结果超过限制。"
|
|
result = json.loads(body)["result"]
|
|
if not isinstance(result, str):
|
|
return "本机Agent响应格式不匹配。"
|
|
return result[:16000]
|
|
except (httpx.HTTPError, ValueError, KeyError):
|
|
return "本机Agent连接失败或响应格式不匹配。"
|
|
|
|
async def close(self):
|
|
await self.http.aclose()
|
|
|
|
|
|
async def bind_device(directory: Path, connector_url: str, code: str, *, tls_verify=True):
|
|
config = json.loads((directory / "device.json").read_text(encoding="utf-8"))
|
|
private = load_private(directory / "device.key")
|
|
proof = sign({"host_id": config["host_id"], "code": code, "ts": int(time.time())}, private)
|
|
async with httpx.AsyncClient(verify=tls_verify, follow_redirects=False, timeout=15) as http:
|
|
response = await http.post(connector_url.rstrip("/") + "/device/bind",
|
|
json={"host_id": config["host_id"], "proof": proof})
|
|
if response.status_code != 200:
|
|
raise RuntimeError(f"binding failed: HTTP {response.status_code}")
|
|
receipt = verified(response.json(), load_public(directory / "connector.pub"))
|
|
if receipt["host_id"] != config["host_id"]:
|
|
raise ValueError("wrong binding receipt")
|
|
config["owner"] = receipt["owner"]
|
|
temp = directory / "device.json.tmp"
|
|
temp.write_text(json.dumps(config, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
temp.replace(directory / "device.json")
|
|
|
|
|
|
async def pair_browser(directory: Path, connector_url: str, *, tls_verify=True):
|
|
config = json.loads((directory / "device.json").read_text(encoding="utf-8-sig"))
|
|
if not config.get("owner"):
|
|
raise RuntimeError("device must be bound first")
|
|
key = load_private(directory / "device.key")
|
|
proof = sign({"host_id": config["host_id"], "owner": config["owner"],
|
|
"purpose": "h5-pair-v1", "ts": int(time.time()), "nonce": secrets.token_hex(16)}, key)
|
|
async with httpx.AsyncClient(verify=tls_verify, trust_env=False, follow_redirects=False, timeout=15) as client:
|
|
response = await client.post(connector_url.rstrip("/") + "/device/web-pair",
|
|
json={"host_id": config["host_id"], "proof": proof})
|
|
if response.status_code != 200:
|
|
raise RuntimeError(f"browser pairing failed: HTTP {response.status_code}")
|
|
result = verified(response.json(), load_public(directory / "connector.pub"))
|
|
if result["host_id"] != config["host_id"]:
|
|
raise ValueError("wrong pairing receipt")
|
|
return result
|
|
|
|
|
|
async def run_device(directory: Path, router_url: str, *, root=None, once=False, ssl_context=None,
|
|
stop_event=None, connected_event=None, agent_url=None, hainuo_config=None):
|
|
config = json.loads((directory / "device.json").read_text(encoding="utf-8"))
|
|
if not config.get("owner"):
|
|
raise RuntimeError("bind device before starting")
|
|
host, owner = config["host_id"], config["owner"]
|
|
key = load_private(directory / "device.key")
|
|
connector = load_public(directory / "connector.pub")
|
|
cert = (directory / "device.pem").read_text(encoding="utf-8")
|
|
verify_device(cert, (directory / "ca.pem").read_bytes(), host)
|
|
journal = DeviceJournal(directory / "journal.sqlite")
|
|
if agent_url and hainuo_config:
|
|
raise ValueError("choose one Agent adapter")
|
|
if hainuo_config:
|
|
from .hainuo1065 import Hainuo1065Agent
|
|
agent = Hainuo1065Agent(hainuo_config)
|
|
else:
|
|
agent = LocalAgent(agent_url) if agent_url else None
|
|
stop_event = stop_event or asyncio.Event()
|
|
delay = 1
|
|
try:
|
|
while not stop_event.is_set():
|
|
try:
|
|
kwargs = {"ssl": ssl_context} if router_url.startswith("wss://") and ssl_context else {}
|
|
async with connect(router_url, max_size=262144, open_timeout=10, ping_interval=10,
|
|
proxy=None, **kwargs) as ws:
|
|
challenge = json.loads(await ws.recv())["challenge"]
|
|
ephemeral = x25519.X25519PrivateKey.generate()
|
|
session = secrets.token_hex(16)
|
|
proof = sign({"host_id": host, "session_id": session, "challenge": challenge,
|
|
"kx": raw_public(ephemeral.public_key()), "ts": int(time.time())}, key)
|
|
await ws.send(json.dumps({"host_id": host, "cert": cert, "proof": proof}))
|
|
accepted = json.loads(await ws.recv())
|
|
if accepted.get("type") != "connected":
|
|
raise RuntimeError("device connection rejected")
|
|
if connected_event:
|
|
connected_event.set()
|
|
delay = 1
|
|
while not stop_event.is_set():
|
|
try:
|
|
raw = await asyncio.wait_for(ws.recv(), timeout=1)
|
|
except asyncio.TimeoutError:
|
|
continue
|
|
data = json.loads(raw)
|
|
payload = open_envelope(data["envelope"], ephemeral, connector,
|
|
host_id=host, session_id=session)
|
|
if payload.get("owner") != owner or payload.get("type") != "instruction":
|
|
continue
|
|
turn = payload["turn_id"]
|
|
if not isinstance(turn, str) or len(turn) > 128:
|
|
continue
|
|
if not journal.consume(turn):
|
|
result = "该请求已处理,拒绝重复执行。"
|
|
elif payload.get("read_only") is not True or payload.get("channel") != "im":
|
|
result = "拒绝:通道或操作类型不受支持。"
|
|
else:
|
|
if agent and payload["text"].startswith("/助手 "):
|
|
result = await agent.execute(payload["text"][4:], owner, turn)
|
|
else:
|
|
result = await execute_readonly(payload["text"], root)
|
|
reply = seal({"type": "result", "turn_id": turn, "result": result},
|
|
payload["reply_key"], key, host_id=host, session_id=session)
|
|
await ws.send(json.dumps({"type": "reply", "turn_id": turn, "envelope": reply}))
|
|
if once:
|
|
return
|
|
except asyncio.CancelledError:
|
|
raise
|
|
except Exception:
|
|
if once:
|
|
raise
|
|
# No payloads/URLs/credentials in logs, bounded reconnect backoff + jitter.
|
|
print("设备连接中断,等待重连。", flush=True)
|
|
with contextlib.suppress(asyncio.TimeoutError):
|
|
await asyncio.wait_for(stop_event.wait(), timeout=delay + secrets.randbelow(1000) / 1000)
|
|
delay = min(delay * 2, 30)
|
|
finally:
|
|
journal.close()
|
|
if agent:
|
|
await agent.close()
|