"""SealAI 认证业务逻辑层。 职责 ---- 1. SSO 换 Bearer token(快报 accesstoken → SealAI Bearer JWT) 2. Token 持久缓存(磁盘文件,CLI/Server 共用) 3. Client 对象内存缓存(模块级 dict,Server 连接池复用;CLI 进程结束自动回收) 4. 401 自动恢复:清除内存 client + 磁盘 token → 重取 → 单次重试 5. 对上层(commands/server)隐藏 SealAiClient 的创建与关闭 对外接口 -------- - get_whoami(corp_id, force_refresh) — 查询用户身份 - invalidate_token(corp_id) — 强制清除缓存(外部显式调用场景) 内部函数(服务层内部使用,不对外导出) -------------------------------------- - _resolve_corp_id(corp_id) — 解析 corp_id,None 时用当前企业 - _get_or_create_client(corp_id, force) — 带缓存的 client 工厂 - _sealai_call(corp_id, fn, *args, **kwargs) — 调用 SealAI API,401 时自动恢复并重试 缓存设计 -------- 磁盘(~/.config/ekb-cli/sealai_tokens.json): { "corpId": { "token": "...", "fetched_at": 1712345678 } } → CLI 进程间共享,TTL = _TOKEN_TTL 秒 内存(模块级 _client_cache): { "corpId": (SealAiClient, fetched_at_float) } → 进程内复用 httpx 连接池;CLI 进程结束自然回收,Server 长期保持 两层缓存的 TTL 相同(_TOKEN_TTL)。token 刷新时同步驱逐内存 client,确保 client 携带的 Authorization header 始终与最新 token 一致。 """ from __future__ import annotations import json import time from pathlib import Path from typing import Any, Callable import httpx from ekb_cli import config as ekb_config from ekb_cli.errors import NotLoggedInError, AuthenticationError, ApiResponseError from ekb_cli.api.sealai.client import SealAiClient from ekb_cli.api.sealai.auth_api import get_me as api_get_me from ekb_cli.api.sealai.schemas import MeData # ── 常量 ────────────────────────────────────────────────────────────────────── _TOKEN_CACHE_PATH = Path.home() / ".config" / "ekb-cli" / "sealai_tokens.json" _TOKEN_TTL = 3600 # 保守 1 小时,到期前强制刷新 # ── 内存 client 缓存 ────────────────────────────────────────────────────────── # key: corp_id, value: (SealAiClient, fetched_at) # CLI 进程结束自动回收;Server 进程中长期保持,复用 httpx 连接池。 _client_cache: dict[str, tuple[SealAiClient, float]] = {} # ── 磁盘 token 缓存(私有) ─────────────────────────────────────────────────── def _load_token_cache() -> dict: if _TOKEN_CACHE_PATH.exists(): try: return json.loads(_TOKEN_CACHE_PATH.read_text()) except (json.JSONDecodeError, OSError): pass return {} def _save_token_cache(cache: dict) -> None: _TOKEN_CACHE_PATH.parent.mkdir(parents=True, exist_ok=True) _TOKEN_CACHE_PATH.write_text(json.dumps(cache, indent=2, ensure_ascii=False)) def _fetch_token(corp_id: str, access_token: str) -> str: """用快报 accesstoken 向 SealAI 换取 Bearer JWT(SSO)。""" url = f"https://{corp_id.lower()}.sealai.cc/api/auth/oauth2/session/oem-hosecloud" try: resp = httpx.get( url, params={"token": access_token, "returnToken": "1"}, headers={"Accept": "application/json"}, timeout=15, follow_redirects=True, ) resp.raise_for_status() except httpx.HTTPStatusError as e: if e.response.status_code == 401: raise AuthenticationError("快报 token 无效,无法登录 SealAI") raise ApiResponseError(e.response.status_code, str(e)) data = resp.json() # 响应:{ "token": "..." } 或 { "data": { "token": "..." } } token = data.get("token") or (data.get("data") or {}).get("token") if not token: raise AuthenticationError(f"SealAI SSO 响应中未找到 token:{data}") return token def _get_bearer_token(corp_id: str, force_refresh: bool = False) -> str: """获取 Bearer token(优先读磁盘缓存,过期或 force_refresh 时重新换取)。 此函数为内部实现细节,外部不应直接调用。 """ cache = _load_token_cache() entry = cache.get(corp_id, {}) now = int(time.time()) if not force_refresh and entry.get("token") and (now - entry.get("fetched_at", 0)) < _TOKEN_TTL: return entry["token"] corp = ekb_config.get_corp(corp_id) if not corp: raise NotLoggedInError(f"企业 {corp_id} 未配置快报认证,请先运行 ekb auth add") token = _fetch_token(corp_id, corp["access_token"]) cache[corp_id] = {"token": token, "fetched_at": now} _save_token_cache(cache) return token # ── 对外公共接口 ────────────────────────────────────────────────────────────── def invalidate_token(corp_id: str) -> None: """清除指定企业的全部缓存(磁盘 token + 内存 client)。 调用场景: - 用户显式执行 --refresh 参数 - 服务层内部在 401 后自动调用(见 _sealai_call) 清除内存 client 是必要的:client 构造时已将 token 写入 Authorization header, token 失效后若继续复用 client,所有请求都会继续 401。 """ # 清磁盘 cache = _load_token_cache() cache.pop(corp_id, None) _save_token_cache(cache) # 清内存 _client_cache.pop(corp_id, None) def get_bearer_token(corp_id: str, force_refresh: bool = False) -> str: """获取当前企业的 Bearer JWT 字符串(主要供调试 / 外部集成使用)。 正常业务调用应走 _sealai_call,不需要直接拿 token。 """ if corp_id is None: corp_id = ekb_config.get_current_corp_id() if not corp_id: raise NotLoggedInError() return _get_bearer_token(corp_id, force_refresh=force_refresh) # ── 内部工具函数 ────────────────────────────────────────────────────────────── def _resolve_corp_id(corp_id: str | None) -> str: """将 None 解析为当前配置企业的 corp_id,未登录时抛 NotLoggedInError。""" if corp_id is not None: return corp_id resolved = ekb_config.get_current_corp_id() if not resolved: raise NotLoggedInError() return resolved def _get_or_create_client(corp_id: str, force_refresh: bool = False) -> SealAiClient: """带 TTL 缓存的 SealAiClient 工厂。 缓存命中条件: - 内存中有该 corp_id 的 client - 距创建时间未超过 _TOKEN_TTL - 未强制刷新 缓存未命中时:重新获取 token(走磁盘缓存或 SSO),创建新 client,写入内存缓存。 """ now = time.time() if not force_refresh: cached = _client_cache.get(corp_id) if cached: client, fetched_at = cached if now - fetched_at < _TOKEN_TTL: return client # 缓存未命中或强制刷新:获取 token,构造新 client token = _get_bearer_token(corp_id, force_refresh=force_refresh) client = SealAiClient(corp_id=corp_id, bearer_token=token) _client_cache[corp_id] = (client, now) return client def _sealai_call(corp_id: str, fn: Callable[..., Any], *args: Any, **kwargs: Any) -> Any: """统一的 SealAI API 调用入口,内置 401 自动恢复与单次重试。 调用流程: 1. 从缓存获取(或新建)SealAiClient 2. 调用 fn(client, *args, **kwargs) 3. 若抛 AuthenticationError(401): a. 清除内存 client + 磁盘 token(invalidate_token) b. 强制重新获取 token,构造新 client c. 重试一次 fn(new_client, *args, **kwargs) d. 若仍然 401 则向上抛出 所有 SealAI 业务函数都应通过此函数发起调用,不应自行管理 client。 """ client = _get_or_create_client(corp_id) try: return fn(client, *args, **kwargs) except AuthenticationError: # token 已被服务端吊销或提前失效,清缓存重试一次 invalidate_token(corp_id) client = _get_or_create_client(corp_id, force_refresh=True) return fn(client, *args, **kwargs) def get_whoami(corp_id: str | None = None, force_refresh: bool = False) -> MeData: """查询当前 SealAI 用户身份及租户信息。 commands/server 调用此函数,无需感知 SealAiClient 的存在。 Args: corp_id: 企业 ID,None 时使用当前配置企业 force_refresh: 强制刷新 Bearer token(token 被手动吊销后使用) """ resolved = _resolve_corp_id(corp_id) if force_refresh: invalidate_token(resolved) return _sealai_call(resolved, api_get_me)