新增 SealAI 子模块:认证层 + API 传输层 + 服务层
架构:融入现有三层结构,SealAI 作为各层的子目录与 HAB 模块并列 api/sealai/ - SealAiClient(Bearer JWT)+ auth_api + billing_api + schemas services/sealai/ - auth_service(SSO换token/缓存)+ billing_service config.py - 新增 get_corp(corp_id) 按ID查询企业配置 认证流程:快报 accesstoken → SSO 换 Bearer JWT → 缓存到 sealai_tokens.json 已验证:auth/me 和 billing/status 端点正常返回数据
This commit is contained in:
1 parent
bfce1fce77
commit
9d517defe3
10 files changed
+405
No files matched your search
@@ -0,0 +1,14 @@
|
||||
"""SealAI 传输层统一 re-export。
|
||||
|
||||
使用方(services/sealai/)只从这里导入,内部文件如何拆分对上层透明。
|
||||
"""
|
||||
|
||||
from ekb_cli.api.sealai.client import SealAiClient
|
||||
from ekb_cli.api.sealai.auth_api import get_me
|
||||
from ekb_cli.api.sealai.billing_api import get_billing_status
|
||||
|
||||
__all__ = [
|
||||
"SealAiClient",
|
||||
"get_me",
|
||||
"get_billing_status",
|
||||
]
|
||||
@@ -0,0 +1,14 @@
|
||||
"""SealAI 认证相关 API 封装(传输层)。
|
||||
|
||||
已逆向确认端点:
|
||||
GET /api/v1/auth/me 当前用户及租户信息
|
||||
"""
|
||||
|
||||
from ekb_cli.api.sealai.client import SealAiClient
|
||||
from ekb_cli.api.sealai.schemas import MeData, SealAiResponse
|
||||
|
||||
|
||||
def get_me(client: SealAiClient) -> MeData:
|
||||
"""获取当前登录用户及租户信息。"""
|
||||
raw = client.get("/api/v1/auth/me")
|
||||
return SealAiResponse[MeData].model_validate(raw).data
|
||||
@@ -0,0 +1,14 @@
|
||||
"""SealAI 计费 / 订阅相关 API 封装(传输层)。
|
||||
|
||||
已逆向确认端点:
|
||||
GET /api/v1/billing/status 订阅状态 + 功能配额列表
|
||||
"""
|
||||
|
||||
from ekb_cli.api.sealai.client import SealAiClient
|
||||
from ekb_cli.api.sealai.schemas import BillingStatusData, SealAiResponse
|
||||
|
||||
|
||||
def get_billing_status(client: SealAiClient) -> BillingStatusData:
|
||||
"""获取订阅状态及各功能配额使用情况。"""
|
||||
raw = client.get("/api/v1/billing/status")
|
||||
return SealAiResponse[BillingStatusData].model_validate(raw).data
|
||||
@@ -0,0 +1,82 @@
|
||||
"""SealAI HTTP 客户端(传输层)。
|
||||
|
||||
与快报主站的 EkbClient 并列,同属 api/ 传输层。
|
||||
区别:SealAI 用 Bearer JWT 认证,域名按企业 corpId 动态生成。
|
||||
|
||||
使用方:services/sealai/ 通过 get_sealai_client() 获取实例,
|
||||
不直接 import 此模块。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
import httpx
|
||||
from typing import Any
|
||||
|
||||
from ekb_cli.errors import AuthenticationError, ApiResponseError
|
||||
|
||||
|
||||
class SealAiClient:
|
||||
"""SealAI REST 客户端,所有请求携带 Authorization: Bearer {token}。"""
|
||||
|
||||
def __init__(self, corp_id: str, bearer_token: str):
|
||||
self.corp_id = corp_id
|
||||
self._base_url = f"https://{corp_id.lower()}.sealai.cc"
|
||||
self._client = httpx.Client(
|
||||
base_url=self._base_url,
|
||||
headers={
|
||||
"Authorization": f"Bearer {bearer_token}",
|
||||
"Accept": "application/json",
|
||||
"Content-Type": "application/json",
|
||||
"User-Agent": (
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
|
||||
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
||||
"Chrome/146.0.0.0 Safari/537.36"
|
||||
),
|
||||
},
|
||||
timeout=30,
|
||||
)
|
||||
|
||||
def _handle_error(self, e: httpx.HTTPStatusError) -> None:
|
||||
if e.response.status_code == 401:
|
||||
raise AuthenticationError("SealAI token 已过期,请重新登录")
|
||||
raise ApiResponseError(e.response.status_code, str(e))
|
||||
|
||||
def get(self, path: str, **params) -> Any:
|
||||
try:
|
||||
resp = self._client.get(path, params=params or None)
|
||||
resp.raise_for_status()
|
||||
except httpx.HTTPStatusError as e:
|
||||
self._handle_error(e)
|
||||
return resp.json()
|
||||
|
||||
def post(self, path: str, body: dict | None = None, **params) -> Any:
|
||||
try:
|
||||
resp = self._client.post(path, json=body or {}, params=params or None)
|
||||
resp.raise_for_status()
|
||||
except httpx.HTTPStatusError as e:
|
||||
self._handle_error(e)
|
||||
return resp.json()
|
||||
|
||||
def patch(self, path: str, body: dict | None = None) -> Any:
|
||||
try:
|
||||
resp = self._client.patch(path, json=body or {})
|
||||
resp.raise_for_status()
|
||||
except httpx.HTTPStatusError as e:
|
||||
self._handle_error(e)
|
||||
return resp.json()
|
||||
|
||||
def delete(self, path: str) -> Any:
|
||||
try:
|
||||
resp = self._client.delete(path)
|
||||
resp.raise_for_status()
|
||||
except httpx.HTTPStatusError as e:
|
||||
self._handle_error(e)
|
||||
return resp.json()
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *args):
|
||||
self._client.close()
|
||||
|
||||
def close(self):
|
||||
self._client.close()
|
||||
@@ -0,0 +1,124 @@
|
||||
"""SealAI 平台的 Pydantic 响应模型。
|
||||
|
||||
SealAI({corpId}.sealai.cc)是独立于快报主站的 Next.js 平台,
|
||||
认证使用 Bearer JWT,数据结构与快报 HAB 模块完全独立。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
from typing import Generic, Optional, TypeVar
|
||||
from pydantic import BaseModel
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
# ── 通用包装 ──────────────────────────────────────────────────────────────────
|
||||
|
||||
class SealAiResponse(BaseModel, Generic[T]):
|
||||
"""SealAI API 统一响应包装:{ data: T }"""
|
||||
data: T
|
||||
|
||||
class Config:
|
||||
extra = "allow"
|
||||
|
||||
|
||||
# ── 认证 ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
class HosecloudStaff(BaseModel):
|
||||
staffId: str
|
||||
name: str
|
||||
code: str = ""
|
||||
bindTime: int
|
||||
|
||||
class Config:
|
||||
extra = "allow"
|
||||
|
||||
|
||||
class SealAiUser(BaseModel):
|
||||
id: str
|
||||
tenantId: str
|
||||
name: str
|
||||
isAdmin: bool
|
||||
permissions: list[str]
|
||||
providerUserId: str # 对应快报 staffId
|
||||
hosecloudStaff: Optional[HosecloudStaff] = None
|
||||
|
||||
class Config:
|
||||
extra = "allow"
|
||||
|
||||
|
||||
class HoseCorpConfig(BaseModel):
|
||||
apiKey: str
|
||||
corporationId: str
|
||||
corporationName: str
|
||||
|
||||
class Config:
|
||||
extra = "allow"
|
||||
|
||||
|
||||
class SealAiTenant(BaseModel):
|
||||
id: str
|
||||
name: str
|
||||
tenantSlug: str # corpId 小写
|
||||
isDemo: bool
|
||||
logoUrl: Optional[str] = None
|
||||
hoseCorpConfig: HoseCorpConfig
|
||||
|
||||
class Config:
|
||||
extra = "allow"
|
||||
|
||||
|
||||
class MeData(BaseModel):
|
||||
user: SealAiUser
|
||||
tenant: SealAiTenant
|
||||
|
||||
class Config:
|
||||
extra = "allow"
|
||||
|
||||
|
||||
# ── 计费 ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
class Subscription(BaseModel):
|
||||
id: str
|
||||
tenantId: str
|
||||
planId: str
|
||||
status: str # "active" | "expired"
|
||||
startDate: str
|
||||
createdAt: str
|
||||
updatedAt: str
|
||||
|
||||
class Config:
|
||||
extra = "allow"
|
||||
|
||||
|
||||
class Feature(BaseModel):
|
||||
"""订阅功能项,三种形态:开关型 / 配额型 / 余额型"""
|
||||
code: str
|
||||
name: str
|
||||
# 开关型
|
||||
enabled: Optional[bool] = None
|
||||
# 配额型
|
||||
quota: Optional[int] = None
|
||||
used: Optional[int] = None
|
||||
remaining: Optional[int] = None
|
||||
# 余额型
|
||||
balance: Optional[int] = None
|
||||
totalQuota: Optional[int] = None
|
||||
totalUsed: Optional[int] = None
|
||||
nextResetDate: Optional[str] = None
|
||||
|
||||
class Config:
|
||||
extra = "allow"
|
||||
|
||||
|
||||
class BillingStatusData(BaseModel):
|
||||
subscriptions: list[Subscription]
|
||||
features: list[Feature]
|
||||
|
||||
class Config:
|
||||
extra = "allow"
|
||||
|
||||
def get_feature(self, code: str) -> Optional[Feature]:
|
||||
for f in self.features:
|
||||
if f.code == code:
|
||||
return f
|
||||
return None
|
||||
Whitespace-only changes.
@@ -35,6 +35,11 @@ def get_current_corp() -> Optional[dict]:
|
||||
return data["corps"].get(corp_id)
|
||||
|
||||
|
||||
def get_corp(corp_id: str) -> Optional[dict]:
|
||||
"""按 corp_id 获取指定企业认证信息(不要求是当前企业)。"""
|
||||
return _load()["corps"].get(corp_id)
|
||||
|
||||
|
||||
def add_corp(corp_id: str, name: str, access_token: str, staff_id: str) -> None:
|
||||
data = _load()
|
||||
data["corps"][corp_id] = {"name": name, "access_token": access_token, "staff_id": staff_id}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
"""SealAI 服务层统一 re-export。"""
|
||||
|
||||
from ekb_cli.services.sealai.auth_service import (
|
||||
get_sealai_client,
|
||||
get_bearer_token,
|
||||
invalidate_token,
|
||||
)
|
||||
from ekb_cli.services.sealai.billing_service import (
|
||||
query_billing_status,
|
||||
get_feature_usage,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"get_sealai_client",
|
||||
"get_bearer_token",
|
||||
"invalidate_token",
|
||||
"query_billing_status",
|
||||
"get_feature_usage",
|
||||
]
|
||||
@@ -0,0 +1,109 @@
|
||||
"""SealAI 认证业务逻辑层。
|
||||
|
||||
职责:SSO 换 Bearer token、本地缓存、自动刷新、对外暴露 get_sealai_client()。
|
||||
|
||||
认证流程:
|
||||
快报 accesstoken
|
||||
→ GET {corpId}.sealai.cc/api/auth/oauth2/session/oem-hosecloud?token=...&returnToken=1
|
||||
→ Bearer JWT(缓存到 ~/.config/ekb-cli/sealai_tokens.json)
|
||||
→ SealAiClient(corp_id, bearer_token)
|
||||
|
||||
缓存格式:
|
||||
{ "ID01Jdq2yIDnMr": { "token": "...", "fetched_at": 1712345678 } }
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
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
|
||||
|
||||
|
||||
_TOKEN_CACHE_PATH = Path.home() / ".config" / "ekb-cli" / "sealai_tokens.json"
|
||||
_TOKEN_TTL = 3600 # 保守 1 小时,到期前强制刷新
|
||||
|
||||
|
||||
def _load_cache() -> dict:
|
||||
if _TOKEN_CACHE_PATH.exists():
|
||||
try:
|
||||
return json.loads(_TOKEN_CACHE_PATH.read_text())
|
||||
except (json.JSONDecodeError, OSError):
|
||||
pass
|
||||
return {}
|
||||
|
||||
|
||||
def _save_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(优先读缓存,过期自动刷新)。"""
|
||||
cache = _load_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_cache(cache)
|
||||
return token
|
||||
|
||||
|
||||
def invalidate_token(corp_id: str) -> None:
|
||||
"""清除指定企业的缓存 token(用于 401 后强制重新获取)。"""
|
||||
cache = _load_cache()
|
||||
cache.pop(corp_id, None)
|
||||
_save_cache(cache)
|
||||
|
||||
|
||||
def get_sealai_client(corp_id: str | None = None, force_refresh: bool = False) -> SealAiClient:
|
||||
"""获取当前企业的 SealAiClient,自动处理 token 获取和缓存。
|
||||
|
||||
Args:
|
||||
corp_id: 企业 ID,None 时使用当前配置企业
|
||||
force_refresh: 强制重新换取 token(快报 token 更换后使用)
|
||||
"""
|
||||
if corp_id is None:
|
||||
corp_id = ekb_config.get_current_corp_id()
|
||||
if not corp_id:
|
||||
raise NotLoggedInError()
|
||||
|
||||
token = get_bearer_token(corp_id, force_refresh=force_refresh)
|
||||
return SealAiClient(corp_id=corp_id, bearer_token=token)
|
||||
@@ -0,0 +1,24 @@
|
||||
"""SealAI 计费 / 订阅业务逻辑层。"""
|
||||
|
||||
from ekb_cli.api.sealai import get_billing_status
|
||||
from ekb_cli.api.sealai.client import SealAiClient
|
||||
from ekb_cli.api.sealai.schemas import BillingStatusData, Feature
|
||||
|
||||
|
||||
def query_billing_status(client: SealAiClient) -> BillingStatusData:
|
||||
"""查询当前企业订阅状态及各功能配额。"""
|
||||
return get_billing_status(client)
|
||||
|
||||
|
||||
def get_feature_usage(client: SealAiClient, code: str) -> Feature | None:
|
||||
"""查询单个功能项使用情况。
|
||||
|
||||
常用 code:
|
||||
ai-approval AI 审批余额
|
||||
approval-rules 审核规则配额
|
||||
ai-fill AI 填单开关
|
||||
financial-policies 财务制度配额
|
||||
knowledge-documents 知识文档配额
|
||||
"""
|
||||
status = get_billing_status(client)
|
||||
return status.get_feature(code)
|
||||
Reference in new issue
Block a user