Add self-contained relay deployment project and operational guidance
This commit is contained in:
@@ -0,0 +1,190 @@
|
||||
"""PC-side user OAuth and calendar operations. Tokens are DPAPI-protected only here."""
|
||||
import hashlib
|
||||
import json
|
||||
import secrets
|
||||
import ssl
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote, urlsplit
|
||||
|
||||
import httpx
|
||||
from .crypto import canonical, load_private, sign
|
||||
from .windows_keys import protect, unprotect
|
||||
from .process_lock import DeviceProcessLock
|
||||
|
||||
|
||||
class WorkError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
class AuthorizationRequired(WorkError):
|
||||
def __init__(self, url):
|
||||
self.url = url
|
||||
super().__init__("需要本人Work授权,请打开授权链接,完成后重新发起原任务;尚未执行平台写操作。")
|
||||
|
||||
|
||||
def atomic_secret(path, data):
|
||||
temp = path.with_suffix(".tmp")
|
||||
temp.write_bytes(protect(json.dumps(data, ensure_ascii=False).encode()))
|
||||
temp.replace(path)
|
||||
|
||||
|
||||
class WorkClient:
|
||||
def __init__(self, directory, url="https://10.77.76.13", *, transport=None):
|
||||
self.directory = Path(directory)
|
||||
self.config = json.loads((self.directory / "device.json").read_text(encoding="utf-8-sig"))
|
||||
if not self.config.get("owner"):
|
||||
raise WorkError("请先绑定本人Work身份。")
|
||||
context = ssl.create_default_context(cafile=str(self.directory / "server.pem"))
|
||||
self.http = httpx.Client(base_url=url.rstrip("/"), verify=context, trust_env=False,
|
||||
timeout=25, follow_redirects=False, transport=transport)
|
||||
self.owner = self.config["owner"]
|
||||
self.path = self.directory / "work-user-tokens.dpapi"
|
||||
self.pending = self.directory / "work-oauth-pending.dpapi"
|
||||
|
||||
def close(self):
|
||||
self.http.close()
|
||||
|
||||
def read(self, path):
|
||||
return json.loads(unprotect(path.read_bytes()))
|
||||
|
||||
def proof(self, purpose, payload):
|
||||
return sign({"host_id": self.config["host_id"], "purpose": purpose, "ts": int(time.time()),
|
||||
"nonce": secrets.token_hex(16), "payload_hash": hashlib.sha256(canonical(payload)).hexdigest()},
|
||||
load_private(self.directory / "device.key"))
|
||||
|
||||
def authorize(self):
|
||||
if self.pending.exists():
|
||||
data = self.read(self.pending)
|
||||
if data.get("owner") == self.owner and data["deadline"] > time.time():
|
||||
return data["authorization_url"]
|
||||
response = self.http.post("/oauth/start", json={"host_id": self.config["host_id"],
|
||||
"proof": self.proof("work-oauth-v1", {})})
|
||||
if response.status_code != 201:
|
||||
raise WorkError("授权事务创建失败(HTTP " + str(response.status_code) + "),请检查ECS平台配置。")
|
||||
data = response.json()
|
||||
if urlsplit(data["authorization_url"]).scheme != "https":
|
||||
raise WorkError("授权地址必须使用HTTPS。")
|
||||
data.update(owner=self.owner, deadline=time.time() + data["expires_in"])
|
||||
atomic_secret(self.pending, data)
|
||||
return data["authorization_url"]
|
||||
|
||||
def save_tokens(self, data):
|
||||
if data.get("open_id") != self.owner or not data.get("user_access_token"):
|
||||
raise WorkError("授权账号与本机Work绑定账号不一致,请使用本人账号重新授权。")
|
||||
now = time.time()
|
||||
data = {**data, "expires_at": now + int(data["expires_in"]),
|
||||
"refresh_expires_at": now + int(data.get("refresh_expires_in", 0)), "needs_authorization": False}
|
||||
atomic_secret(self.path, data)
|
||||
return data
|
||||
|
||||
def access_token(self):
|
||||
# Shared across GUI and Agent calls; never rotate the same token concurrently.
|
||||
with DeviceProcessLock(self.directory / "work-token-lock"):
|
||||
if self.path.exists():
|
||||
data = self.read(self.path)
|
||||
if data.get("open_id") == self.owner and not data.get("needs_authorization"):
|
||||
if data["expires_at"] > time.time() + 120:
|
||||
return data["user_access_token"]
|
||||
if data.get("refresh_token") and data.get("refresh_expires_at", 0) > time.time():
|
||||
# Mark before network; ambiguous failure must not reuse a rotating refresh token.
|
||||
atomic_secret(self.path, {**data, "needs_authorization": True})
|
||||
try:
|
||||
response = self.http.post("/oauth/refresh", json={"refresh_token": data["refresh_token"]})
|
||||
if response.status_code != 200:
|
||||
raise WorkError("刷新失败")
|
||||
data = self.save_tokens(response.json())
|
||||
return data["user_access_token"]
|
||||
except (httpx.HTTPError, ValueError, WorkError):
|
||||
raise AuthorizationRequired(self.authorize()) from None
|
||||
if self.pending.exists():
|
||||
pending = self.read(self.pending)
|
||||
if pending.get("owner") == self.owner and pending["deadline"] > time.time():
|
||||
response = self.http.get("/oauth/claim", params={"state": pending["state"]},
|
||||
headers={"X-OAuth-Claim-Secret": pending["claim_secret"]})
|
||||
if response.status_code == 200:
|
||||
data = self.save_tokens(response.json())
|
||||
self.pending.unlink(missing_ok=True)
|
||||
return data["user_access_token"]
|
||||
if response.status_code not in {202}:
|
||||
self.pending.unlink(missing_ok=True)
|
||||
raise AuthorizationRequired(self.authorize())
|
||||
|
||||
def status(self):
|
||||
try:
|
||||
token = self.access_token()
|
||||
return {"authorized": True, "owner": self.owner, "message": "本人用户授权可用;令牌未输出。",
|
||||
"local_time": datetime.now().astimezone().isoformat()}
|
||||
except AuthorizationRequired as error:
|
||||
return {"authorized": False, "authorization_url": error.url, "message": str(error)}
|
||||
|
||||
def api(self, method, path, params=None, body=None, operation_id=""):
|
||||
token = self.access_token()
|
||||
payload = {"method": method, "path": path, "params": params or {}, "body": body or {},
|
||||
"operation_id": operation_id, "token_hash": hashlib.sha256(token.encode()).hexdigest()}
|
||||
proof = self.proof("work-api-v1", payload)
|
||||
wire = {k: v for k, v in payload.items() if k != "token_hash"}
|
||||
response = self.http.post("/work/api", headers={"Authorization": "Bearer " + token},
|
||||
json={**wire, "host_id": self.config["host_id"], "proof": proof})
|
||||
if response.status_code == 401:
|
||||
# Do not repeat a business write automatically, even when auth fails.
|
||||
if self.path.exists():
|
||||
data = self.read(self.path)
|
||||
data["expires_at"] = 0
|
||||
atomic_secret(self.path, data)
|
||||
raise WorkError("用户令牌已失效。本次未重试,请检查授权后再核对操作状态。")
|
||||
if response.status_code != 200:
|
||||
raise WorkError("平台代理失败(HTTP " + str(response.status_code) + ");未重试。")
|
||||
return response.json()
|
||||
|
||||
def primary_calendar(self):
|
||||
result = self.api("POST", "/open-apis/calendar/v4/calendars/primary", {"user_id_type": "open_id"})
|
||||
if result.get("status") != "completed":
|
||||
return result
|
||||
calendars = result.get("data", {}).get("calendars", [])
|
||||
own = [c["calendar"] for c in calendars if c.get("user_id") == self.owner and c.get("calendar")]
|
||||
if not own and len(calendars) == 1 and not calendars[0].get("user_id") and calendars[0].get("calendar"):
|
||||
own = [calendars[0]["calendar"]]
|
||||
if len(own) != 1:
|
||||
raise WorkError("没有唯一确定的本人主日历,请先查询日历列表并明确选择。")
|
||||
return {"status": "completed", "calendar": own[0]}
|
||||
|
||||
def create_event(self, summary, start_iso, end_iso, attendee_open_ids, operation_id, description="", calendar_id=""):
|
||||
import re
|
||||
if not re.fullmatch(r"[A-Za-z0-9_-]{8,80}", operation_id):
|
||||
raise WorkError("创建日程需8到80位稳定operation_id,重试不得换ID。")
|
||||
if not summary.strip() or len(summary) > 1000:
|
||||
raise WorkError("日程主题不能为空或超过1000字符。")
|
||||
start, end = datetime.fromisoformat(start_iso), datetime.fromisoformat(end_iso)
|
||||
if start.tzinfo is None or end.tzinfo is None or end <= start:
|
||||
raise WorkError("起止时间必须包含时区且结束晚于开始;不要猜测时区或时长。")
|
||||
if any(not isinstance(x, str) or not x.startswith("ou_") for x in attendee_open_ids):
|
||||
raise WorkError("参会人必须为当前应用身份域的open_id,请先搜索并确认,不能把姓名/工号直接当ID。")
|
||||
if not calendar_id:
|
||||
primary = self.primary_calendar()
|
||||
if primary.get("status") != "completed":
|
||||
return primary
|
||||
calendar_id = primary["calendar"]["calendar_id"]
|
||||
path = "/open-apis/calendar/v4/calendars/" + quote(calendar_id, safe="") + "/events"
|
||||
body = {"summary": summary, "description": description, "need_notification": True,
|
||||
"start_time": {"timestamp": str(int(start.timestamp())), "timezone": "Asia/Shanghai"},
|
||||
"end_time": {"timestamp": str(int(end.timestamp())), "timezone": "Asia/Shanghai"}}
|
||||
result = self.api("POST", path, {"user_id_type": "open_id"}, body, operation_id)
|
||||
event = result.get("data", {}).get("event", {})
|
||||
if result.get("status") == "duplicate" and result.get("previous_status") == "completed":
|
||||
event = {"event_id": result.get("event_id"), "app_link": result.get("app_link")}
|
||||
elif result.get("status") != "completed":
|
||||
return result
|
||||
if not event.get("event_id"):
|
||||
raise WorkError("平台未返回event_id,不能认定创建成功或继续邀请。")
|
||||
ids = sorted(set([self.owner] + list(attendee_open_ids)))
|
||||
invite = self.api("POST", path + "/" + quote(event["event_id"], safe="") + "/attendees",
|
||||
{"user_id_type": "open_id"},
|
||||
{"attendees": [{"type": "user", "user_id": x} for x in ids], "need_notification": True},
|
||||
operation_id + "_attendees")
|
||||
invited = invite.get("status") == "completed" or (invite.get("status") == "duplicate" and invite.get("previous_status") == "completed")
|
||||
return {"status": "completed" if invited else "partial", "event_created": True,
|
||||
"calendar_id": calendar_id, "event_id": event["event_id"], "app_link": event.get("app_link"),
|
||||
"attendees_invited": invited, "invite_result": invite,
|
||||
"message": "日程已创建并提交参会人邀请;不代表对方已接受。" if invited else "日程已创建,但邀请未完成;保留原操作ID和event_id处理,勿重新创建日程。"}
|
||||
Reference in New Issue
Block a user