# -*- coding: utf-8 -*- """webhost 宿主:FastAPI 后端。 - 承载平台登录态(复用 desktop/shared 的共享登录态单一真源,真实登录/校验) - 场景插件注册表 + 表单 schema - 执行 run 到 worker 线程,经 /ws 广播 日志/进度/完成 - 挂载前端构建产物(frontend/dist)实现单产物 """ from __future__ import annotations import asyncio import json import logging import os import socket import subprocess import secrets import sys import threading import time import uuid from contextlib import asynccontextmanager from datetime import datetime from pathlib import Path from fastapi import FastAPI, HTTPException, Request, Response, WebSocket from pydantic import BaseModel from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import HTMLResponse, RedirectResponse from fastapi.staticfiles import StaticFiles from urllib.parse import urlencode from webhost.backend import auth as platform_auth from webhost.backend import licensing from webhost.backend import scheduler as _scheduler from webhost.backend import winjob as _winjob from webhost.backend.hub import HUB from webhost.backend.plugins import PLUGINS, load_plugins # PLUGINS 为注册表,启动时显式填装 PORT = 8799 DIST = Path(__file__).resolve().parents[1] / "frontend" / "dist" _LOGGER = logging.getLogger(__name__) # ==================== 配置固化:加载本模块 env(webhost/.env;免命令行传参;环境变量优先) ==================== def _load_dotenv() -> None: """轻量读取 webhost/.env,灌入 os.environ(仅当变量缺失时)。UTF-8、'#'/'空行'跳过。""" env_path = Path(__file__).resolve().parents[1] / ".env" if not env_path.is_file(): return try: for _ln in env_path.read_text(encoding="utf-8").splitlines(): _line = _ln.strip() if not _line or _line.startswith("#") or "=" not in _line: continue _k, _v = _line.split("=", 1) _k, _v = _k.strip(), _v.strip() if _k and _k not in os.environ: os.environ[_k] = _v except OSError as _exc: # noqa: BLE001 _LOGGER.warning("读取 .env 失败: %s", _exc) _load_dotenv() # ==================== 插件权限源(阶段二:控制面接口;默认全量兜底) ==================== PLUGIN_SOURCE = os.getenv("PLUGIN_SOURCE", "all") # all | controlplane CONTROLPLANE_URL = os.getenv("CONTROLPLANE_URL", "").rstrip("/") CONTROLPLANE_ACCOUNT = os.getenv("CONTROLPLANE_ACCOUNT", "") CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "") # 钉钉扫码登录(可选):配置了钉钉开放平台应用后前端显示扫码入口。 # 未配置时仅保留账号+密码登录。真实扫码 OAuth 在中心机换取工号/姓名后走 /api/admin/dingtalk/login。 # 兼容旧配置名 DINGTALK_APPKEY:任一名非空即视为已启用扫码。 DINGTALK_APP_KEY = os.getenv("DINGTALK_APP_KEY", "") or os.getenv("DINGTALK_APPKEY", "") # 统一账户体系为真源:登录态由后端 cookie 会话维护(账号在统一后端 accounts 表)。 # cookie 会话:token -> (account, 活跃时间戳);登录后 set-cookie,进程内保持,供代理转发账号。 SESSION_COOKIE = "cp_session" # 会话空闲有效期:7 天滑动续期(每次有效请求刷新 TTL;天天用永不重登,超期需重登) _SESS_TTL = 7 * 24 * 3600 _SESS: dict[str, tuple] = {} _SESS_LOCK = threading.Lock() # 本机会话落盘文件:重启后端不丢会话(兑现"双击壳直接进插件页、不必每次重登") _SESS_FILE = Path(__file__).resolve().parents[1] / "_cp_sessions.json" def _sess_persist(): """把本机会话快照落盘为首存(token → [account, 最近活跃ts]),进程重启后仍有效。""" try: with _SESS_LOCK: _payload = {t: [a, int(_ts)] for t, (a, _ts) in _SESS.items()} _SESS_FILE.write_text(json.dumps(_payload, ensure_ascii=False), encoding="utf-8") except OSError as _exc: # noqa: BLE001 _LOGGER.warning("本机会话持久化失败: %s", _exc) def _sess_load(): """启动时从磁盘恢复本机会话(惰性丢弃已过期条)。""" if not _SESS_FILE.is_file(): return try: _raw = json.loads(_SESS_FILE.read_text(encoding="utf-8")) except (OSError, ValueError): return _now = time.time() with _SESS_LOCK: for _t, _it in (_raw or {}).items(): try: _a, _ts = _it[0], float(_it[1]) except (KeyError, IndexError, TypeError, ValueError): continue if _now - _ts <= _SESS_TTL: _SESS[_t] = (_a, _ts) def _sess_account(request) -> str: """从请求 cookie 会话解析当前登录账号;未登录/过期返回空串(过期顺手清理并落盘)。""" token = request.cookies.get(SESSION_COOKIE, "") account = "" with _SESS_LOCK: item = _SESS.get(token) if item: _account, _ts = item if time.time() - _ts <= _SESS_TTL: _SESS[token] = (_account, time.time()) # 滑动续期 account = _account else: _SESS.pop(token, None) if account: _sess_persist() # 滑动续期也落盘,重启后仍有效 return account def _require_login(request: Request) -> str: """业务执行接口的统一登录门槛:未登录统一账户(无有效会话 cookie)则拒绝。""" account = _sess_account(request) if not account: raise HTTPException(401, "未登录:请先登录统一账户") return account _sess_load() # 启动即恢复本机会话(重启后端不丢会话) # 平台登录态:标签/展示名来自 auth,在线状态实时校验(非内存假状态) PLATFORMS: dict = {p["id"]: {"id": p["id"], "label": p["label"]} for p in platform_auth.platforms()} # 运行会话:run_id -> {status, account, result, error} RUNS: dict = {} RUN_LOCK = threading.Lock() MAX_RUNS = 50 # 运行历史上限,超出丢弃最旧记录,避免内存无限增长 # 插件权限白名单(启动时决定;执行子进程透传同款白名单,保证两侧加载一致) ALLOWED: set | None = None # 平台命名空间并发闸:同平台(hr/oa/…)任务串行执行,保护共享登录态 cookies 不被并发争抢 _NS_LOCKS: dict[str, threading.Lock] = {} _NS_GUARD = threading.Lock() def _ns_gate(platform: str) -> threading.Lock: key = (platform or "").strip() or "local" with _NS_GUARD: if key not in _NS_LOCKS: _NS_LOCKS[key] = threading.Lock() return _NS_LOCKS[key] def _set_run(run_id: str, **kw) -> None: """更新运行记录字段(保留 account 等既有键)。""" with RUN_LOCK: run = RUNS.get(run_id) if run is not None: run.update(kw) class RunReq(BaseModel): plugin_id: str fields: dict = {} def _resolve_allowed() -> set | None: """按权限源决定可加载插件白名单。None = 全量加载(默认/控制面不可达兜底)。""" if PLUGIN_SOURCE != "controlplane" or not CONTROLPLANE_URL: return None if not CONTROLPLANE_ACCOUNT: _LOGGER.warning("PLUGIN_SOURCE=controlplane 但未设置 CONTROLPLANE_ACCOUNT,回退全量加载") return None import requests headers = {"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {} try: r = requests.get(f"{CONTROLPLANE_URL}/api/plugins", params={"account": CONTROLPLANE_ACCOUNT}, headers=headers, timeout=5) r.raise_for_status() allowed = {p["id"] for p in r.json().get("plugins", [])} _LOGGER.info("控制面权限清单(%s):%s", CONTROLPLANE_ACCOUNT, sorted(allowed) or "(空)") return allowed except Exception as _exc: # noqa: BLE001 _LOGGER.error("拉取控制面权限清单失败,回退全量加载:%s", _exc) return None # ==================== 统一后端(数据库 API)代理:底座前端访问统一后端的唯一通道 ==================== # 底座前端不直连统一后端/数据库;全部经本层代理转发,并注入「当前登录账号 + 内部凭证」。 def _cp_headers(request: Request) -> dict: h = {"X-Admin-User": _sess_account(request)} if CONTROLPLANE_TOKEN: h["X-API-Token"] = CONTROLPLANE_TOKEN return h def _cp_call(method: str, path: str, **kw) -> dict: if not CONTROLPLANE_URL: raise HTTPException(503, "统一后端未配置(CONTROLPLANE_URL)") import requests r = requests.request(method, f"{CONTROLPLANE_URL}{path}", timeout=30, **kw) try: body = r.json() except ValueError: body = {"detail": r.text[:300]} if r.status_code >= 400: raise HTTPException(r.status_code, body.get("detail", f"统一后端 {r.status_code}")) return body # ==================== 产品化:离线授权同步 + 单活调度终止注册表 ==================== def _sync_licensing(account: str) -> None: """联网拉取并缓存 中心机公钥 + 该账号离线授权票据 + 管控清单;成功后补报离线记录。 离线票据/管控清单持久化到 %LOCALAPPDATA%\\37duAutomation,供断网时在线验签运行。 """ if not CONTROLPLANE_URL or not account: return import requests headers = {"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {} r = requests.get(f"{CONTROLPLANE_URL}/api/me/pubkey", headers=headers, timeout=5) r.raise_for_status() licensing.cache_public_key(r.json().get("pub", "")) r = requests.get(f"{CONTROLPLANE_URL}/api/me/license", params={"account": account}, headers=headers, timeout=5) r.raise_for_status() licensing.save_license(r.json()) r = requests.get(f"{CONTROLPLANE_URL}/api/me/control-list", headers=headers, timeout=5) r.raise_for_status() licensing.save_control(r.json()) licensing.flush_offline_reports() @asynccontextmanager async def lifespan(app: FastAPI): HUB.bind(asyncio.get_running_loop()) # 显式加载插件:默认全量;配置 controlplane 源则按账号权限白名单加载 global ALLOWED ALLOWED = _resolve_allowed() load_plugins(ALLOWED) # 产品化初始化:授权缓存 + 单活调度 + 启动即同步离线票据 licensing.init(CONTROLPLANE_URL, threading.Lock()) _scheduler.init_active() if CONTROLPLANE_URL: try: _sync_licensing(CONTROLPLANE_ACCOUNT) _LOGGER.info("启动同步离线授权票据成功(账号 %s)", CONTROLPLANE_ACCOUNT) except Exception as _exc: # noqa: BLE001 首启/断网时同步失败不阻断,离线用缓存兜底 _LOGGER.warning("启动同步离线授权票据失败:%s", _exc) yield app = FastAPI(title="37du Web Host", lifespan=lifespan) app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]) @app.get("/api/admin/me") def admin_me(request: Request) -> dict: """当前登录账号是否管理员(会话 cookie)。 账号一律以**壳本机会话**为准(登录即有效);is_admin/部门 尽量从云端补齐, 云端未授信 X-Admin-User(未配 CONTROLPLANE_TOKEN)或不可达时,仅降级 is_admin=False, 不影响员工正常进入插件页(前端以 account 非空判登录)。 """ account = _sess_account(request) if not account: return {"account": "", "is_admin": False, "dept": "", "nickname": ""} try: r = _cp_call("GET", "/api/admin/me", headers=_cp_headers(request)) if r.get("account") == account: return r except HTTPException: pass return {"account": account, "is_admin": False, "dept": "", "nickname": ""} class _LoginIn(BaseModel): account: str password: str @app.post("/api/admin/login") def admin_login(b: _LoginIn, response: Response) -> dict: """统一账户登录:校验账号+密码通过后,写会话 cookie 记为当前登录账号。""" try: r = _cp_call("POST", "/api/admin/auth", headers={"X-Admin-User": b.account.strip(), **({"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {}), "Content-Type": "application/json"}, json={"account": b.account, "password": b.password}) except HTTPException as e: raise e if not r.get("ok"): return r token = uuid.uuid4().hex with _SESS_LOCK: _SESS[token] = (b.account.strip(), time.time()) _sess_persist() response.set_cookie(SESSION_COOKIE, token, httponly=True, samesite="lax") # 登录成功即联网同步该账号的离线授权票据 + 管控清单 + 中心机公钥(供离线运行) if CONTROLPLANE_URL: try: _sync_licensing(b.account.strip()) except Exception as _exc: # noqa: BLE001 同步失败不影响登录本身 _LOGGER.warning("登录后同步离线授权票据失败:%s", _exc) return {**r, "account": b.account.strip()} class _DingTalkIn(BaseModel): account: str # 钉钉工号(作为统一账号) nickname: str = "" # 钉钉姓名 dingtalk_uid: str = "" # 钉钉 userid/openId(便于二次扫码精确复用) @app.post("/api/admin/dingtalk/login") def admin_dingtalk_login(d: _DingTalkIn, response: Response) -> dict: """钉钉扫码登录(链接授权后回跳):account/nickname 已由中心机换取,直接建立会话。""" if not d.account: raise HTTPException(400, "工号不能为空") return _dingtalk_establish(d.account.strip(), d.nickname, d.dingtalk_uid, response) def _dingtalk_establish(account: str, nickname: str, dingtalk_uid: str, response: Response) -> dict: """统一建立钉钉账号会话:中心机找建账号 → 写本机会话 cookie → 同步离线票据。 账号密码登录与两种钉钉扫码(链接授权 / 内嵌二维码)共用此通路,保证登录态一致。 """ r = _cp_call( "POST", "/api/admin/dingtalk/auth", headers=({"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {}), json={"account": account, "nickname": nickname, "dingtalk_uid": dingtalk_uid}) acct = r.get("account") or account token = uuid.uuid4().hex with _SESS_LOCK: _SESS[token] = (acct, time.time()) _sess_persist() response.set_cookie(SESSION_COOKIE, token, httponly=True, samesite="lax") if CONTROLPLANE_URL: try: _sync_licensing(acct) except Exception as _exc: # noqa: BLE001 同步失败不影响登录本身 _LOGGER.warning("登录后同步离线授权票据失败:%s", _exc) return {"ok": True, "account": acct, "is_admin": bool(r.get("is_admin")), "created": bool(r.get("created")), "must_change_pwd": bool(r.get("must_change_pwd"))} class _InlineIn(BaseModel): code: str # 内嵌二维码扫码后钉钉 JS 返回的 loginTmpCode @app.post("/api/admin/dingtalk/inline") def admin_dingtalk_inline(d: _InlineIn, response: Response) -> dict: """内嵌二维码扫码登录:loginTmpCode → 中心机换工号/姓名 → 建立会话。 登录页用钉钉 DDLogin 在本页内渲染二维码,扫码后前端拿到 loginTmpCode 传本接口, 由中心机换出工号/姓名(可信身份源),再走 _dingtalk_establish 建会话——全程不弹浏览器。 """ if not d.code.strip(): raise HTTPException(400, "缺少扫码截图码") if not CONTROLPLANE_URL: raise HTTPException(503, "未配置中心机地址,无法扫码登录") info = _cp_call( "POST", "/api/admin/dingtalk/sns", headers=({"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {}), json={"code": d.code.strip()}) account = (info.get("account") or "").strip() if not account: raise HTTPException(401, "扫码未解析到有效账号,请重新扫码") return _dingtalk_establish(account, info.get("nickname") or "", info.get("unionid") or "", response) @app.get("/api/admin/dingtalk/inline_qr") def admin_dingtalk_inline_qr(request: Request) -> dict: """内嵌二维码登录:代理中心机构造 DDLogin 的 goto 参数(登录页在本页内渲染二维码)。""" if not CONTROLPLANE_URL: raise HTTPException(503, "未配置中心机地址,无法扫码登录") back = f"{request.url.scheme}://{request.url.netloc}/api/admin/dingtalk/cb" return _cp_call( "GET", "/api/admin/dingtalk/inline_qr", params={"back": back}, headers=({"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {})) # ==================== v3 钉钉直连接登录:/api/auth/dingtalk + /auth/done(§2.1,待 §0 验证后实测) ==================== # 浏览器跳转模型:壳生成 state → 打开钉钉授权URL(redirect_uri=http://localhost:8799/auth/done) # → 用户本机浏览器带回 code+state → 壳校验 state → POST 云端 /auth/exchange{code} 换工号+云端token → 建本机会话。 # 云端只参与换 token,AppSecret 不出云端;会话存本机、重启不掉(见上方 _SESS 持久化)。 _LOGIN_STATE_TTL = 5 * 60 # state 有效期(秒) _LOGIN_STATES: dict[str, float] = {} # state -> expiry(待回跳校验) _LOGIN_LOCK = threading.Lock() # account -> 最近云端会话 token(7 天,供壳后续调 /api/plugins 用 Bearer,见 §2.2) _ACCT_CLOUD_TOKEN: dict[str, str] = {} def _login_state_new() -> str: with _LOGIN_LOCK: _now = time.time() for s in [s for s, e in _LOGIN_STATES.items() if e < _now]: _LOGIN_STATES.pop(s, None) state = secrets.token_urlsafe(24) _LOGIN_STATES[state] = _now + _LOGIN_STATE_TTL return state def _login_state_take(state: str) -> bool: with _LOGIN_LOCK: exp = _LOGIN_STATES.pop(state, None) return bool(exp and exp >= time.time()) def _auth_done_page(text: str) -> HTMLResponse: return HTMLResponse(f"""
{text}
""") @app.get("/api/auth/dingtalk") def auth_dingtalk_url() -> dict: """生成并返回钉钉扫码授权 URL(redirect_uri=本机 /auth/done)。前端「钉钉登录」当前窗口跳转该 URL。""" if not DINGTALK_APP_KEY: raise HTTPException(503, "未配置钉钉开放平台应用(DINGTALK_APP_KEY)") if not CONTROLPLANE_URL: raise HTTPException(503, "未配置中心机地址(CONTROLPLANE_URL)") state = _login_state_new() redirect_uri = f"http://localhost:{PORT}/auth/done" login_url = "https://login.dingtalk.com/oauth2/challenge.htm?" + urlencode({ "redirect_uri": redirect_uri, "response_type": "code", "client_id": DINGTALK_APP_KEY, "scope": "openid", "prompt": "consent", "state": state}) return {"url": login_url, "state": state} @app.get("/auth/done") def auth_done(code: str = "", state: str = "", error: str = "") -> Response: """钉钉回跳落点(浏览器):收 code+state → 校验 state → 云端 /auth/exchange 换工号 → 建本机会话。 成功后写会话 cookie 并 302 回主页;任何失败给 HTML 提示,不建立会话。 """ if error: return _auth_done_page("钉钉登录被取消或失败,请返回重试。") if not (code and state) or not _login_state_take(state): return _auth_done_page("登录状态无效或已过期,请返回重新扫码。") try: info = _cp_call("POST", "/auth/exchange", json={"code": code}) except HTTPException as e: return _auth_done_page(f"登录失败:{e.detail}") account = (info.get("account") or "").strip() if not account or not info.get("exists"): return _auth_done_page("账号未开通或未解析到有效工号,请联系管理员。") # 建本机会话(写内存+落盘+set-cookie),并存云端 token 供后续调云端 API(§2.2)。 _token = uuid.uuid4().hex with _SESS_LOCK: _SESS[_token] = (account, time.time()) _sess_persist() if info.get("token"): _ACCT_CLOUD_TOKEN[account] = info["token"] resp = RedirectResponse("/") resp.set_cookie(SESSION_COOKIE, _token, httponly=True, samesite="lax") if CONTROLPLANE_URL: try: _sync_licensing(account) except Exception as _exc: # noqa: BLE001 同步失败不影响登录 _LOGGER.warning("登录后同步离线授权票据失败:%s", _exc) return resp # ==================== 钉钉真实扫码:扫码URL + 静默回调页 ==================== # 扫码 URL 指向中心机 /api/admin/dingtalk/scan(back 回跳到本机 /cb); # 扫码成功 → 中心机 /cb 302 回本机 /cb?account=&nickname= → 本页静默调 dingtalk/login 建会话 # → 刷新父窗口(登录完成)。身份源为钉钉+中心机(可信),与账号密码登录同会话机制。 _DINGTALK_CB_HTML = """