"""Per-user Windows connection companion. No platform/application secrets.""" import argparse import asyncio import json import os import secrets import ssl import subprocess import sys import time import uuid from pathlib import Path import httpx import psutil from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey from .crypto import load_private, load_public, pem_private, raw_public, sign, verified, verify_device from .windows_keys import protect BASE = Path(__file__).resolve().parent.parent URL = "https://10.77.76.13" def save(path, value): temp = path.with_suffix(path.suffix + ".tmp") temp.write_text(json.dumps(value, ensure_ascii=False, indent=2), encoding="utf-8") os.replace(temp, path) def secure_directory(directory): directory.mkdir(parents=True, exist_ok=True) # SID avoids localized account names. Fail closed if ACL protection fails. result = subprocess.run(["whoami", "/user", "/fo", "csv", "/nh"], capture_output=True, text=True, check=True) import csv sid = list(csv.reader([result.stdout.strip()]))[0][1] subprocess.run(["icacls", str(directory), "/inheritance:r", "/grant:r", f"*{sid}:(OI)(CI)F", "*S-1-5-18:(OI)(CI)F"], capture_output=True, check=True, creationflags=subprocess.CREATE_NO_WINDOW) def prepare(directory): secure_directory(directory) for name in ("server.pem", "ca.pem", "connector.pub"): target = directory / name if not target.exists(): target.write_bytes((BASE / "trust" / name).read_bytes()) if not (directory / "device.json").exists(): if (directory / "device.key.dpapi").exists() or (directory / "device.key").exists(): raise RuntimeError("发现不完整的设备身份,请保留目录并联系管理员恢复。") private = Ed25519PrivateKey.generate() (directory / "device.key.dpapi").write_bytes(protect(pem_private(private))) save(directory / "device.json", {"host_id": uuid.uuid4().hex, "owner": None}) def tls(directory): return ssl.create_default_context(cafile=str(directory / "server.pem")) def import_existing(directory, source): """Explicit migration; only public trust and this PC's identity, never app keys.""" if source.resolve() == directory.resolve(): raise ValueError("请选择旧设备目录。") if any((directory / name).exists() for name in ("device.json", "device.key.dpapi", "device.key")): raise RuntimeError("本目录已有设备身份。请使用已有身份继续,不能用导入覆盖。") config = json.loads((source / "device.json").read_text(encoding="utf-8-sig")) for name in ("server.pem", "ca.pem", "connector.pub"): if (source / name).read_bytes().strip() != (BASE / "trust" / name).read_bytes().strip(): raise ValueError("旧设备的服务信任与本安装包不符,请联系管理员。") cert = (source / "device.pem").read_text(encoding="utf-8") public = verify_device(cert, (source / "ca.pem").read_bytes(), config["host_id"]) private = load_private(source / "device.key") if raw_public(public) != raw_public(private.public_key()): raise ValueError("设备证书与本机私钥不匹配。") secure_directory(directory) for name in ("device.pem", "server.pem", "ca.pem", "connector.pub"): (directory / name).write_bytes((source / name).read_bytes()) (directory / "device.key.dpapi").write_bytes(protect(pem_private(private))) save(directory / "device.json", config) # Preserve local replay journal using SQLite's consistent backup API. if (source / "journal.sqlite").is_file(): import sqlite3 with sqlite3.connect(source / "journal.sqlite") as original, sqlite3.connect(directory / "journal.sqlite") as target: original.backup(target) return {"message": "旧设备导入成功,Work绑定已保留。请先停止旧PowerShell桥接窗口,再点击启动连接。"} def enrollment(directory): prepare(directory) cfg = json.loads((directory / "device.json").read_text()) if (directory / "device.pem").exists(): verify_device((directory / "device.pem").read_text(), (directory / "ca.pem").read_bytes(), cfg["host_id"]) return {"message": "设备已注册,可在Work获取绑定码后绑定。已有绑定可直接启动连接。"} with httpx.Client(verify=tls(directory), trust_env=False, timeout=15) as http: key = load_private(directory / "device.key") proof = sign({"host_id": cfg["host_id"], "purpose": "device-enroll-v1", "ts": int(time.time()), "nonce": secrets.token_hex(16)}, key) response = http.post(URL + "/device/register", json={"host_id": cfg["host_id"], "proof": proof, "public_key": key.public_key().public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo).decode()}) if response.status_code not in {200, 201}: raise RuntimeError("自动注册失败:HTTP " + str(response.status_code) + ";请确认ECS已安装1.067自动注册更新。") receipt = verified(response.json(), load_public(directory / "connector.pub")) if receipt.get("status") != "registered" or receipt["host_id"] != cfg["host_id"]: raise ValueError("注册回执身份不符") public = verify_device(receipt["cert"], (directory / "ca.pem").read_bytes(), cfg["host_id"]) if raw_public(public) != raw_public(key.public_key()): raise ValueError("注册证书公钥不符") temp = directory / "device.pem.tmp" temp.write_text(receipt["cert"], encoding="utf-8") os.replace(temp, directory / "device.pem") (directory / "enrollment.json").unlink(missing_ok=True) return {"message": "设备已自动注册,无需管理员审批。请在Work获取绑定码,填写后点击绑定并连接。"} def managed_processes(directory): """Only processes with our absolute entry path AND exact device directory.""" state = directory / "processes.json" if not state.exists(): return [] result = [] for item in json.loads(state.read_text()).get("processes", []): try: proc = psutil.Process(item["pid"]) command = proc.cmdline() if (abs(proc.create_time() - item["created"]) < 0.1 and str(BASE / "entry.py") in command and str(directory) in command): result.append(proc) except psutil.Error: pass return result def stop(directory): procs = managed_processes(directory) # Supervisor owns and terminates only its own child handles in its finally block. (directory / "stop.flag").touch() _, alive = psutil.wait_procs(procs, timeout=8) for proc in alive: proc.terminate() return {"message": "已停止本安装包启动的连接进程。手工启动的旧桥接请在原窗口按Ctrl+C停止。"} def start(directory, root): from .process_lock import DeviceProcessLock with DeviceProcessLock(directory / "control"): return _start(directory, root) def _start(directory, root): cfg = json.loads((directory / "device.json").read_text()) if not cfg.get("owner") or not (directory / "device.pem").exists(): raise RuntimeError("请先完成设备准入和Work绑定。") if managed_processes(directory): return {"message": "连接进程已运行,请点击状态查看。"} (directory / "stop.flag").unlink(missing_ok=True) log = (directory / "bridge.log").open("a", encoding="utf-8") proc = subprocess.Popen([sys.executable, str(BASE / "entry.py"), "supervise", "--directory", str(directory), "--root", str(root)], stdout=log, stderr=log, creationflags=subprocess.CREATE_NO_WINDOW) log.close() save(directory / "processes.json", {"processes": [{"pid": proc.pid, "created": psutil.Process(proc.pid).create_time()}]}) return {"message": "连接进程已启动;约30秒后点击状态,再到Work发送 /主机名 验证。"} def supervise(directory, root): from .process_lock import DeviceProcessLock lockdir = directory / "supervisor" with DeviceProcessLock(lockdir): children = [] def record_children(): processes = [psutil.Process(os.getpid())] + [psutil.Process(p.pid) for p in children if p.poll() is None] save(directory / "processes.json", {"processes": [{"pid": p.pid, "created": p.create_time()} for p in processes]}) try: with httpx.Client(trust_env=False, timeout=1) as client: try: client.get("http://127.0.0.1:18643/health") except httpx.ConnectError: pass else: raise RuntimeError("原生API端口18643已被占用,请先停止旧连接。") native = subprocess.Popen([sys.executable, str(BASE / "entry.py"), "native", "--directory", str(directory), "--root", str(root)]) children.append(native) record_children() for _ in range(90): if (directory / "stop.flag").exists(): return if native.poll() is not None: raise RuntimeError("本机原生API启动失败,请检查安装配置。") try: from .hainuo1065 import Hainuo1065Agent async def probe(): agent = Hainuo1065Agent(directory / "hainuo-native.json") try: return await agent.probe() finally: await agent.close() asyncio.run(probe()) break except Exception: time.sleep(1) else: raise RuntimeError("本机原生API未就绪。") bridge = subprocess.Popen([sys.executable, str(BASE / "entry.py"), "bridge", "--directory", str(directory), "--root", str(root)]) children.append(bridge) record_children() while not (directory / "stop.flag").exists(): if any(proc.poll() is not None for proc in children): raise RuntimeError("连接子进程已退出,请查看状态后重新启动。") time.sleep(0.5) finally: for proc in reversed(children): if proc.poll() is None: proc.terminate() try: proc.wait(timeout=5) except subprocess.TimeoutExpired: proc.kill() def main(): parser = argparse.ArgumentParser() parser.add_argument("action", choices=["import", "enroll", "bind", "start", "stop", "status", "pair", "supervise", "native", "bridge"]) parser.add_argument("--directory", type=Path, required=True) parser.add_argument("--root", type=Path, required=True) args = parser.parse_args() directory, root = args.directory.resolve(), args.root.resolve() directory.mkdir(parents=True, exist_ok=True) try: if args.action == "import": result = import_existing(directory, Path(sys.stdin.readline().strip())) elif args.action == "enroll": result = enrollment(directory) elif args.action == "bind": from .device import bind_device code = sys.stdin.readline().strip() if not code: raise ValueError("请填写Work机器人新生成的绑定码。") enrollment(directory) stop(directory) asyncio.run(bind_device(directory, URL, code, tls_verify=tls(directory))) result = start(directory, root) result["message"] = "Work绑定成功。" + result["message"] elif args.action == "start": result = start(directory, root) elif args.action == "stop": result = stop(directory) elif args.action == "pair": from .device import pair_browser receipt = asyncio.run(pair_browser(directory, URL, tls_verify=tls(directory))) result = {"message": "网页:" + receipt["url"] + "\n一次性配对码(120秒):" + receipt["code"]} elif args.action == "status": cfg = json.loads((directory / "device.json").read_text()) if (directory / "device.json").exists() else {} log = directory / "bridge.log" tail = log.read_bytes()[-6000:].decode("utf-8", errors="replace") if log.exists() else "" result = {"message": "设备:" + cfg.get("host_id", "未申请") + "\nWork身份:" + (cfg.get("owner") or "未绑定") + "\n连接进程:" + ("运行中(请在Work发送 /主机名 确认当前链路)" if managed_processes(directory) else "未运行") + "\n" + tail[-2500:]} elif args.action == "supervise": return supervise(directory, root) elif args.action == "native": import importlib.util spec = importlib.util.spec_from_file_location("native_companion", BASE / "hainuo_native_api.py") module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) key = module.prepare_environment(root, "hainuo", 18643, directory / "hainuo-native.json") import logging logging.disable(logging.CRITICAL) return asyncio.run(module.serve_native(18643, key)) else: from .device import run_device return asyncio.run(run_device(directory, "wss://10.77.76.13/device/ws", ssl_context=tls(directory), hainuo_config=directory / "hainuo-native.json")) print(json.dumps(result, ensure_ascii=False)) except KeyboardInterrupt: pass except Exception as error: # Native exception bodies may include URLs or secrets; emit bounded known messages only. message = str(error) if isinstance(error, (RuntimeError, ValueError)) else type(error).__name__ + ";请检查网络、证书、安装目录。" print(json.dumps({"message": message[:600], "error": True}, ensure_ascii=False)) raise SystemExit(1) from None if __name__ == "__main__": main()