import argparse import asyncio import json import os import secrets import ssl import uuid from datetime import datetime, timedelta, timezone from pathlib import Path import httpx from cryptography import x509 from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import ed25519 from cryptography.x509.oid import NameOID from .crypto import issue_ca, issue_device, load_private, pem_private def write_new(path, data, private=False): path.parent.mkdir(parents=True, exist_ok=True) with path.open("xb") as f: f.write(data if isinstance(data, bytes) else data.encode()) if private and os.name != "nt": path.chmod(0o600) def init_project(root: Path, hostname: str): if (root / ".env").exists(): raise RuntimeError(".env exists; init never overwrites credentials") ca_key, ca = issue_ca() signer = ed25519.Ed25519PrivateKey.generate() write_new(root / "operator/ca.key", pem_private(ca_key), True) write_new(root / "runtime/trust/ca.pem", ca.public_bytes(serialization.Encoding.PEM)) write_new(root / "runtime/connector/connector.key", pem_private(signer), True) write_new(root / "runtime/trust/connector.pub", signer.public_key().public_bytes( serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo)) tls_key = ed25519.Ed25519PrivateKey.generate() name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, hostname)]) now = datetime.now(timezone.utc) tls = (x509.CertificateBuilder().subject_name(name).issuer_name(name).public_key(tls_key.public_key()) .serial_number(x509.random_serial_number()).not_valid_before(now - timedelta(minutes=5)) .not_valid_after(now + timedelta(days=30)) .add_extension(x509.SubjectAlternativeName([x509.DNSName(hostname)]), critical=False) .sign(tls_key, algorithm=None)) write_new(root / "runtime/tls/server.key", pem_private(tls_key), True) write_new(root / "runtime/tls/server.pem", tls.public_bytes(serialization.Encoding.PEM)) redis_secret = secrets.token_hex(32) db_secret = secrets.token_hex(32) env = (f"HN_ENVIRONMENT=development\nHN_PUBLIC_HOST={hostname}\nHN_PUBLIC_URL=https://{hostname}\n" f"HN_ROUTER_URL=wss://{hostname}/device/ws\nHN_ADMIN_SECRET={secrets.token_hex(32)}\n" f"HN_INTERNAL_SECRET={secrets.token_hex(32)}\nHN_REDIS_PASSWORD={redis_secret}\n" f"HN_REDIS_URL=redis://:{redis_secret}@redis:6379/0\n" f"HN_POSTGRES_PASSWORD={db_secret}\nHN_DATABASE_URL=postgresql://hainuo:{db_secret}@postgres:5432/hainuo\n" "HN_FEISHU_ENABLED=false\nHN_FEISHU_API_BASE=https://open.feishu.cn\n" "HN_FEISHU_AUTHORIZE_URL=https://open.feishu.cn/open-apis/authen/v1/authorize\n" "HN_FEISHU_APP_ID=\nHN_FEISHU_APP_SECRET=\nHN_FEISHU_ENCRYPT_KEY=\n" "HN_FEISHU_VERIFICATION_TOKEN=\nHN_PROXY_ENABLED=false\nHN_DEVICE_DOMAIN=\n") write_new(root / ".env", env, True) print("已生成配置、连接器密钥、设备CA及临时TLS证书;未输出凭据。") print("operator/ca.key 仅保留在签发工作站,不要上传到ECS。临时TLS证书上线前须替换。") def device_request(directory): host = uuid.uuid4().hex private = ed25519.Ed25519PrivateKey.generate() write_new(directory / "device.key", pem_private(private), True) public = private.public_key().public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo).decode() write_new(directory / "request.json", json.dumps({"host_id": host, "public_key": public}, indent=2)) print("已在本机生成私钥和 request.json;仅将request.json交给签发工作站。") def issue(root, request_file, output): request = json.loads(request_file.read_text(encoding="utf-8")) host = request["host_id"] if len(host) != 32 or any(c not in "0123456789abcdef" for c in host): raise ValueError("invalid host identity") ca = x509.load_pem_x509_certificate((root / "runtime/trust/ca.pem").read_bytes()) public = serialization.load_pem_public_key(request["public_key"].encode()) if not isinstance(public, ed25519.Ed25519PublicKey): raise ValueError("Ed25519 required") cert = issue_device(load_private(root / "operator/ca.key"), ca, host, public) pem = cert.public_bytes(serialization.Encoding.PEM) write_new(output / "device.pem", pem) write_new(output / "ca.pem", (root / "runtime/trust/ca.pem").read_bytes()) write_new(output / "connector.pub", (root / "runtime/trust/connector.pub").read_bytes()) write_new(output / "device.json", json.dumps({"host_id": host, "owner": None}, indent=2)) write_new(output / "registration.json", json.dumps({"host_id": host, "cert": pem.decode()}, indent=2)) print("已签发设备证书;将device.pem、ca.pem、connector.pub、device.json交回原设备。") def main(): parser = argparse.ArgumentParser(description="海诺中继部署和设备工具") sub = parser.add_subparsers(dest="command", required=True) p = sub.add_parser("init") p.add_argument("--root", type=Path, default=Path(".")) p.add_argument("--hostname", required=True) p = sub.add_parser("serve") p.add_argument("role", choices=["connector", "router"]) p.add_argument("--host", default="127.0.0.1") p.add_argument("--port", type=int, default=8000) p = sub.add_parser("device-request") p.add_argument("--directory", type=Path, required=True) p = sub.add_parser("issue-device") p.add_argument("--root", type=Path, default=Path(".")) p.add_argument("--request", type=Path, required=True) p.add_argument("--output", type=Path, required=True) p = sub.add_parser("register") p.add_argument("--registration", type=Path, required=True) p.add_argument("--url", required=True) p.add_argument("--tls-ca", type=Path) p = sub.add_parser("bind") p.add_argument("--directory", type=Path, required=True) p.add_argument("--url", required=True) p.add_argument("--tls-ca", type=Path) p = sub.add_parser("device") p.add_argument("--directory", type=Path, required=True) p.add_argument("--url", required=True) p.add_argument("--tls-ca", type=Path) p.add_argument("--test-root", type=Path) p.add_argument("--agent-url", help="Explicit loopback read-only Agent adapter endpoint") p.add_argument("--hainuo-config", type=Path, help="Native installer-1.065 API adapter config; alternative to --agent-url") p = sub.add_parser("hainuo-probe") p.add_argument("--config", type=Path, required=True) p = sub.add_parser("web-pair") p.add_argument("--directory", type=Path, required=True) p.add_argument("--url", required=True) p.add_argument("--tls-ca", type=Path) for command in ("status", "binding-code", "dispatch", "revoke", "reconcile"): p = sub.add_parser(command) p.add_argument("--url", default="http://127.0.0.1:18081") p.add_argument("--tls-ca", type=Path) if command in {"binding-code", "dispatch"}: p.add_argument("--owner", required=True) if command == "dispatch": p.add_argument("--text", required=True) p.add_argument("--turn-id", default=None) if command == "revoke": p.add_argument("--host-id", required=True) args = parser.parse_args() if args.command == "init": init_project(args.root, args.hostname) elif args.command == "serve": import uvicorn uvicorn.run(f"relay.{args.role}:create_app", factory=True, host=args.host, port=args.port, workers=1, access_log=False, proxy_headers=False, ws_max_size=262144, ws_max_queue=16, log_level="warning") elif args.command == "device-request": device_request(args.directory) elif args.command == "issue-device": issue(args.root, args.request, args.output) elif args.command == "register": import getpass secret = os.environ.get("HN_ADMIN_SECRET") or getpass.getpass("Admin secret: ") context = ssl.create_default_context(cafile=str(args.tls_ca)) if args.tls_ca else True with httpx.Client(verify=context, follow_redirects=False, timeout=15) as client: response = client.post(args.url.rstrip("/") + "/admin/devices", headers={"X-Admin-Secret": secret}, json=json.loads(args.registration.read_text(encoding="utf-8"))) if response.status_code != 201: raise RuntimeError(f"register failed: HTTP {response.status_code}") print("设备登记成功。") elif args.command == "bind": import getpass from .device import bind_device code = getpass.getpass("Binding code: ") context = ssl.create_default_context(cafile=str(args.tls_ca)) if args.tls_ca else True asyncio.run(bind_device(args.directory, args.url, code, tls_verify=context)) print("绑定成功。") elif args.command == "device": from .device import run_device context = ssl.create_default_context(cafile=str(args.tls_ca)) if args.tls_ca else None asyncio.run(run_device(args.directory, args.url, root=args.test_root, ssl_context=context, agent_url=args.agent_url, hainuo_config=args.hainuo_config)) elif args.command == "hainuo-probe": from .hainuo1065 import Hainuo1065Agent async def probe(): adapter = Hainuo1065Agent(args.config) try: print(json.dumps(await adapter.probe(), ensure_ascii=False, indent=2)) finally: await adapter.close() asyncio.run(probe()) elif args.command == "web-pair": from .device import pair_browser context = ssl.create_default_context(cafile=str(args.tls_ca)) if args.tls_ca else True result = asyncio.run(pair_browser(args.directory, args.url, tls_verify=context)) print("网页地址:" + result["url"]) print("一次性网页配对码(120秒有效):" + result["code"]) else: import getpass secret = os.environ.get("HN_ADMIN_SECRET") or getpass.getpass("Admin secret: ") context = ssl.create_default_context(cafile=str(args.tls_ca)) if args.tls_ca else True with httpx.Client(verify=context, timeout=200, follow_redirects=False) as client: paths = {"status": "/admin/devices", "binding-code": "/admin/test/binding-code", "dispatch": "/admin/test/dispatch", "reconcile": "/admin/reconcile"} if args.command == "revoke": if len(args.host_id) != 32 or any(c not in "0123456789abcdef" for c in args.host_id): raise ValueError("invalid host identity") path = f"/admin/devices/{args.host_id}/revoke" else: path = paths[args.command] body = None if args.command in {"binding-code", "dispatch"}: body = {"open_id": args.owner, "text": getattr(args, "text", "binding")} if getattr(args, "turn_id", None): body["turn_id"] = args.turn_id response = client.request("GET" if args.command == "status" else "POST", args.url.rstrip("/") + path, headers={"X-Admin-Secret": secret}, json=body) if response.status_code != 200: raise RuntimeError(f"operation failed: HTTP {response.status_code}") print(json.dumps(response.json(), ensure_ascii=False, indent=2)) if __name__ == "__main__": main()