refactor(core/http): 7大通信底座客户端语义化全量重构与合思开放文档客户端纳管

- 彻底移除旧内部狭隘命名与垫片包袱,一步到位全仓整体重命名:
  * session-client.ts ➔ hose-web-session-client.ts (合思 Web 主站会话客户端)
  * script-engine-client.ts ➔ piper-workflow-client.ts (Piper 工作流引擎客户端)
  * unity-client.ts ➔ unity-easo-client.ts (Unity / EASO 运营中台与动态集群客户端)
  * sso-client.ts ➔ sso-auth-client.ts (SSO 与扫码鉴权客户端)
- 新增 hose-docs-client.ts 纳为第 7 大通信底座客户端,收口 docs.ekuaibao.com 文档站点通信
- 端正 Piper 工作流引擎定位,完整覆盖工作流创建、保存、发布、108 类节点编排与 Job 流转
- 彻底整体替换全仓 import 引用与测试套件,新增 clients-semantics.test.ts 自动化校验
- 全量自动化测试 150 files 1155 tests 全部通过,类型检查零错误
This commit is contained in:
gitea committed 2026-11-16 17:15:29 +08:00
1 parent 62b47f5ad7
commit 42bf0bfb0b
44 files changed
+400 -171

No files matched your search

+1 -1
View File
@@ -28,7 +28,7 @@
## 已知基础设施
- New API(LLM 代理)端点为 `api.ying-qing.cn`;原 Sealos 实例 `sealosgzg.site` 已回收,属用户本地基础设施,与本仓库代码无关。
- workflow 灰度节点开通曾用的 `*.sealosgzg.site` 第三方网关已在 commit `e562ae9` 移除,改为本地 EASO 换票后直连 Piper。**当前源码/产物中已无任何 `sealosgzg.site` 残留,也不存在「迁移到 api.ying-qing.cn」这个端点**(`api.ying-qing.cn` 是 LLM 代理,不是工作流网关)。不要再派后续 Agent 做这项无效清理。Piper 域名常量见 `src/core/http/script-engine-client.ts:19` 与 `transport/catalog/api.ts:84,87`,均为硬编码且无环境变量覆盖口(旧 `HOSE_GRAY_GATEWAY_URL` 逃生口随 e562ae9 一并删除)。
- workflow 灰度节点开通曾用的 `*.sealosgzg.site` 第三方网关已在 commit `e562ae9` 移除,改为本地 EASO 换票后直连 Piper。**当前源码/产物中已无任何 `sealosgzg.site` 残留,也不存在「迁移到 api.ying-qing.cn」这个端点**(`api.ying-qing.cn` 是 LLM 代理,不是工作流网关)。不要再派后续 Agent 做这项无效清理。Piper 域名常量见 `src/core/http/piper-workflow-client.ts`(收口于 `piper-endpoints.ts`)与 `transport/catalog/api.ts:84,87`,均为硬编码且无环境变量覆盖口(旧 `HOSE_GRAY_GATEWAY_URL` 逃生口随 e562ae9 一并删除)。
## 工作流与 Piper 核心契约(2026-11-02 固化)
+1 -1
View File
@@ -23,7 +23,7 @@ src/http/ # HTTP -> runCli
| `EasoClient` | `unity.ekuaibao.com` | 统一认证与 EASO 资源 |
| `PiperClient` | `piper.ekuaibao.com` | 工作流列表、详情、配置保存与 Job 执行 |
客户端装配统一位于 `src/core/http/`:主站使用 `session-client.ts`,Unity/EASO 使用 `unity-client.ts`,Piper 使用 `script-engine-client.ts`。工作流 CLI 按应用 ID 创建 Piper 客户端;不在 MCP Server 内单独分派业务。
客户端装配统一位于 `src/core/http/`:主站使用 `hose-web-session-client.ts`,Unity/EASO 使用 `unity-easo-client.ts`,Piper 使用 `piper-workflow-client.ts`。工作流 CLI 按应用 ID 创建 Piper 客户端;不在 MCP Server 内单独分派业务。
## 认证链路
+1 -1
View File
@@ -45,7 +45,7 @@ specs/hose-close-api/
- `src/domains/feetype/api.ts`
- `src/domains/assist-platform/api.ts`
- `src/core/auth/login.ts`、`src/core/auth/openapi-v1.ts`、`src/core/auth/link-import.ts`
- `src/core/http/openapi-client.ts`、`unity-client.ts`、`script-engine-client.ts`、`assist-platform-client.ts`、`session-client.ts`
- `src/core/http/hose-web-session-client.ts`、`openapi-client.ts`、`piper-workflow-client.ts`、`hose-docs-client.ts`、`unity-easo-client.ts`、`assist-platform-client.ts`、`sso-auth-client.ts`
- 历史参考:`specs/openapi.raw.json`
## 域名约定
+5 -5
View File
@@ -17,10 +17,10 @@
| A05 | GET | `BC /cloud-auth/public/auth/list-corporations` | Header `cloud-auth-token` | `{data:{items:[CorporationItem],externalItems:[]},errorCode?,errorMessage?}`;Item 字段见下 | `src/core/auth/login.ts:242` | 否 |
| A06 | POST | `BC /cloud-auth/public/auth/switch-corporation` | Header `cloud-auth-token`;body `{corporationId,userId,cluster}` | `{data:{accessToken:<authCode>},errorCode?,errorMessage?}` | `src/core/auth/login.ts:269` | 否 |
| A07 | POST | `IDP /api/idp/public/oauth2/token` | `{clientId:"whispered-app",grantType:"authorization_code",code:<authCode>,withIdToken:false}` | `{access_token,token_type,expires_in,refresh_token?,id_token?}` | `src/core/auth/login.ts:288` | 否 |
| A08 | GET | `BC /auth/oauth2/grant/ekb/accessToken` | Query `{corpId,ekbAccessToken,environment}` | `{data:<hose-access-token>}` | `src/core/http/unity-client.ts:70` | 否 |
| A09 | GET | `EKB /api/engine/realm/$UNITY/actions/jwt` | Query `{corpId}`;Headers `accesstoken`、`corpid`、`staffid` | `{id?,value?}`,取 `id` 或 `value` 作为 UNITY JWT | `src/core/http/unity-client.ts:91`、`src/core/auth/link-import.ts:262` | 否 |
| A10 | GET | `EKB /api/engine/realm/$EASO/actions/jwt` | 同 A09 | `{id?,value?}`,取 `id` 或 `value` 作为 EASO JWT | `src/core/http/script-engine-client.ts:68` | 否 |
| A11 | GET | `EASO /api/realms/EASO` | Query `{corpId}`;Headers `Authorization: Bearer <unityJwt>`、可选 `hoseaccesstoken` | `{value:{accessToken}}` | `src/core/http/unity-client.ts:119` | 否 |
| A08 | GET | `BC /auth/oauth2/grant/ekb/accessToken` | Query `{corpId,ekbAccessToken,environment}` | `{data:<hose-access-token>}` | `src/core/http/unity-easo-client.ts:70` | 否 |
| A09 | GET | `EKB /api/engine/realm/$UNITY/actions/jwt` | Query `{corpId}`;Headers `accesstoken`、`corpid`、`staffid` | `{id?,value?}`,取 `id` 或 `value` 作为 UNITY JWT | `src/core/http/unity-easo-client.ts:91`、`src/core/auth/link-import.ts:262` | 否 |
| A10 | GET | `EKB /api/engine/realm/$EASO/actions/jwt` | 同 A09 | `{id?,value?}`,取 `id` 或 `value` 作为 EASO JWT | `src/core/http/piper-workflow-client.ts:68` | 否 |
| A11 | GET | `EASO /api/realms/EASO` | Query `{corpId}`;Headers `Authorization: Bearer <unityJwt>`、可选 `hoseaccesstoken` | `{value:{accessToken}}` | `src/core/http/unity-easo-client.ts:119` | 否 |
| A12 | GET | `EKB /api/account/v2/session` | Headers `accesstoken`、`corpid`、可选 `staffid` | `{value:{id,userId,loginStaffId,corporationId,platform,isAssistPlatform,isShortTermToken,assistId,operationUserId,operationUserName,privilege,deviceType,loginAccountType,loginTime,expTime}}` | `src/core/auth/link-import.ts:329` | 否 |
| A13 | POST | `EKB /api/openapi/v1/auth/getAccessToken` | `{appKey,appSecurity}` | `{value:{accessToken,corporationId,expireTime,errorCode?,errorMessage?}}`;也兼容顶层 `accessToken`/`token` | `src/core/auth/openapi-v1.ts:133` | 否 |
| A14 | POST | `EKB /api/openapi/v1.1/provisional/getProvisionalAuth` | Query `{accessToken}`;body `{uid,pageType:"home",expireDate}` | `{value:{message:<loginUrl>}}`,从 URL 的 `accessToken` 参数取临时会话 token | `src/core/auth/openapi-v1.ts:199` | 否 |
@@ -39,7 +39,7 @@ staffId, userId, sourceChannel?, baseUrl?, external?, needAuth?
## 2. platform / workflow(30)
工作流接口通过 Piper 客户端调用(`src/core/http/script-engine-client.ts`):
工作流接口通过 Piper 客户端调用(`src/core/http/piper-workflow-client.ts`):
`Authorization: Bearer <EASO JWT>`、`platformid: <platformId>`、可选 `hoseaccesstoken`。
`listPlatforms` 例外,它走主站 `ekbClient`。
+1 -1
View File
@@ -1,4 +1,4 @@
import { createSessionClient } from "../../../core/http/session-client.js";
import { createSessionClient } from "../../../core/http/hose-web-session-client.js";
import {
approveAssistTicket,
listAssistTickets,
+1 -1
View File
@@ -17,7 +17,7 @@ import {
getActiveAccount,
setActiveAccount,
} from "../../core/auth/account-store.js";
import { createSessionClient } from "../../core/http/session-client.js";
import { createSessionClient } from "../../core/http/hose-web-session-client.js";
import { stringOption, booleanOption } from "../parser.js";
import { printJson, printKeyValue, printTable, formatSourceLabel, formatExpiresAt } from "../printer.js";
import { prompt } from "../helpers.js";
+1 -1
View File
@@ -1,4 +1,4 @@
import { createSessionClient } from "../../../core/http/session-client.js";
import { createSessionClient } from "../../../core/http/hose-web-session-client.js";
import { resolveBillStaffIds } from "../../../domains/bill/tools.js";
import { booleanOption, stringOption } from "../../parser.js";
import { isDryRun, requireMutationConfirmation } from "../../mutation.js";
+2 -2
View File
@@ -1,6 +1,6 @@
import { describe, it, expect } from "bun:test";
import { parseHeadersOrCurl } from "../../core/auth/login.js";
import { resolveCorpCluster } from "../../core/http/unity-client.js";
import { resolveCorpCluster } from "../../core/http/unity-easo-client.js";
import { handleCorpsCommand } from "./corps/index.js";
import type { CliRuntime } from "../types.js";
import type { CorpConfig } from "../../core/config/types.js";
@@ -35,7 +35,7 @@ describe("core/auth/login > parseHeadersOrCurl & URL link parsing", () => {
});
});
describe("core/http/unity-client > resolveCorpCluster", () => {
describe("core/http/unity-easo-client > resolveCorpCluster", () => {
it("prioritizes explicit cluster config", () => {
expect(resolveCorpCluster({ cluster: "wx2", baseUrl: "https://app.ekuaibao.com" })).toBe("wx2");
});
+1 -1
View File
@@ -1,5 +1,5 @@
import { loadCorpConfigs } from "../../../core/config/loader.js";
import { createSessionClient } from "../../../core/http/session-client.js";
import { createSessionClient } from "../../../core/http/hose-web-session-client.js";
import { booleanOption, stringOption } from "../../parser.js";
import { NotFoundError } from "../../../core/errors.js";
import { formatSourceLabel, printJson, printTable } from "../../printer.js";
+1 -1
View File
@@ -1,7 +1,7 @@
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { printJson, printTable } from "../printer.js";
import { numberOption, stringOption } from "../parser.js";
import { createSessionClient } from "../../core/http/session-client.js";
import { createSessionClient } from "../../core/http/hose-web-session-client.js";
import { searchDimensions, resolveDimension } from "../../domains/dimension/tools.js";
export async function handleDimensionCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
+1 -1
View File
@@ -1,7 +1,7 @@
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { printJson, printTable } from "../printer.js";
import { booleanOption, stringOption } from "../parser.js";
import { createSessionClient } from "../../core/http/session-client.js";
import { createSessionClient } from "../../core/http/hose-web-session-client.js";
import {
createFeeType,
disableFeeTypeItem,
+1 -1
View File
@@ -2,7 +2,7 @@ import { describe, expect, it, spyOn, afterEach } from "bun:test";
import { handleFlowCommand } from "./flow.js";
import { handleBillCommand } from "./bill/index.js";
import { findCommandByArea } from "../registry.js";
import * as sessionModule from "../../core/http/session-client.js";
import * as sessionModule from "../../core/http/hose-web-session-client.js";
import type { CliRuntime } from "../types.js";
import type { CorpConfig } from "../../core/config/types.js";
+1 -1
View File
@@ -1,7 +1,7 @@
import { booleanOption, numberOption, stringOption } from "../parser.js";
import { printJson, printTable } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { createSessionClient } from "../../core/http/session-client.js";
import { createSessionClient } from "../../core/http/hose-web-session-client.js";
import { filterMessages, listMessages, mergeMessages, readMessage } from "../../domains/message/tools.js";
import type { MessageItem } from "../../domains/message/types.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
+1 -1
View File
@@ -1,6 +1,6 @@
import { printJson, printTable } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { createSessionClient } from "../../core/http/session-client.js";
import { createSessionClient } from "../../core/http/hose-web-session-client.js";
import { getPermissions } from "../../domains/permission/tools.js";
export async function handlePermissionCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
@@ -5,7 +5,7 @@ import { join } from "node:path";
import * as services from "../../domains/platform/workflow/services.js";
import * as billApi from "../../domains/bill/api.js";
import * as cache from "../../core/cache/index.js";
import * as session from "../../core/http/session-client.js";
import * as session from "../../core/http/hose-web-session-client.js";
import * as helpers from "../helpers.js";
import * as workflowShared from "./workflow/shared.js";
import * as platformShared from "./platform/shared.js";
+1 -1
View File
@@ -1,7 +1,7 @@
import { numberOption, stringOption } from "../parser.js";
import { printJson, printTable } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { createSessionClient } from "../../core/http/session-client.js";
import { createSessionClient } from "../../core/http/hose-web-session-client.js";
import { getRoleGroups, getRoleMembers, searchRoles } from "../../domains/role/tools.js";
export async function handleRoleCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
+1 -1
View File
@@ -12,7 +12,7 @@ import {
import { printJson, printKeyValue } from "../printer.js";
import { numberOption, stringOption } from "../parser.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { createSessionClient } from "../../core/http/session-client.js";
import { createSessionClient } from "../../core/http/hose-web-session-client.js";
import { EventStore } from "../../domains/events/store.js";
import { pollEvents } from "../../domains/events/poller.js";
+1 -1
View File
@@ -1,7 +1,7 @@
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { booleanOption, numberOption, stringOption } from "../parser.js";
import { printJson, printTable } from "../printer.js";
import { createSessionClient } from "../../core/http/session-client.js";
import { createSessionClient } from "../../core/http/hose-web-session-client.js";
import { listTasks } from "../../domains/task/tools.js";
import type { TaskView } from "../../domains/task/types.js";
+1 -1
View File
@@ -1,7 +1,7 @@
import { stringOption, numberOption } from "../../parser.js";
import { printJson, printTable } from "../../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { createSessionClient } from "../../../core/http/session-client.js";
import { createSessionClient } from "../../../core/http/hose-web-session-client.js";
import { getOutboundMessages, queryOutboundMessageLogs } from "../../../domains/platform/workflow/services.js";
function formatTime(timestamp: number | undefined): string {
+4
View File
@@ -89,6 +89,7 @@ export async function createScriptEngineClientForCorp(corp: CorpConfig, platform
}
export const createPiperClientForCorp = createScriptEngineClientForCorp;
export const createPiperWorkflowClientForCorp = createPiperClientForCorp;
export function requireSelectedCorp(
runtime: CliRuntime,
@@ -107,6 +108,9 @@ export async function getSessionClientForRuntime(runtime: CliRuntime) {
return { corp, corpId, client };
}
export const getHoseWebSessionClientForRuntime = getSessionClientForRuntime;
export function prompt(question: string): Promise<string> {
const rl = readline.createInterface({
input: process.stdin,
+12 -9
View File
@@ -14,14 +14,17 @@ src/core/
│ ├── account-store.ts # 多账号持久化存储 (~/.config/hose-use/accounts.json, 0o600 权限保护)
│ ├── token-store.ts # 子域动态 Token 跨进程 L2 持久化缓存 (~/.config/hose-use/tokens.json, 0o600)
│ └── types.ts
├── http/ # 统一 HTTP 客户端装配与网络传输(语义化客户端)
│ ├── factory.ts # Ky 底层客户端工厂(超时、重试、错误钩子)
│ ├── fingerprint.ts # 统一浏览器指纹、User-Agent、Cookie 与 WAF 策略头
│ ├── session-client.ts # 闭合用户会话客户端(三 Header + 指纹 + 账号/OpenAPI 双通道自动续杯)
│ ├── openapi-client.ts # 开放平台应用客户端(appKey 换票与签名机制)
│ ├── unity-client.ts # 应用中心与动态集群寻址客户端(L1 内存 + L2 token-store 跨进程复用)
│ ├── script-engine-client.ts # 工作流 MVEL/Python 脚本调试引擎客户端(L1 + L2 token-store 缓存)
│ └── index.ts # 统一导出入口
├── http/ # 统一 HTTP 客户端装配与网络传输(7 大语义化标准客户端)
│ ├── factory.ts # Ky 底层客户端工厂(超时、重试、错误钩子)
│ ├── fingerprint.ts # 统一浏览器指纹、User-Agent、Cookie 与 WAF 策略头
│ ├── hose-web-session-client.ts # 合思 Web 主站会话客户端(三 Header + 指纹 + 账号/OpenAPI 双通道自动续杯)
│ ├── openapi-client.ts # 开放平台应用客户端(appKey 换票与签名机制)
│ ├── piper-workflow-client.ts # Piper 工作流引擎客户端(工作流生命周期、108 类节点编排与 Job 流转)
│ ├── hose-docs-client.ts # 合思开放文档客户端(docs.ekuaibao.com 8.4MB 索引与 270+ OpenAPI 自省)
│ ├── unity-easo-client.ts # Unity / EASO 运营中台与动态集群寻址客户端(L1 + L2 跨进程复用)
│ ├── assist-platform-client.ts # 合思协助运维平台客户端(代客工单无密直通)
│ ├── sso-auth-client.ts # SSO 与扫码鉴权客户端(单点登录与二维码轮询)
│ └── index.ts # 统一导出入口
├── cache/ # 统一多级协同缓存
│ ├── memory.ts # L1 内存缓存(严格 LRU、TTL、容量限制、按命名空间清理)
│ ├── sqlite.ts # L2 SQLite 持久化缓存(跨 CLI 进程复用)
@@ -47,7 +50,7 @@ src/core/
## 分层约束
- `domains/*` 优先通过 `core/http/` 获取语义化客户端(`createSessionClient`, `createOpenApiClient`, `getUnityClient`, `getScriptEngineClient`),保持底层网络与指纹统一
- `domains/*` 优先通过 `core/http/` 获取语义化客户端(`createHoseWebSessionClient`, `createOpenApiClient`, `getPiperWorkflowClient`, `createHoseDocsClient`, `getUnityEasoClient` 等),保持底层网络与指纹统一
- `domains/*` 层只抛 `EkbError` 子类(由 `cli/errors.ts` 统一按结构化 `code` / `status` 映射退出码)
- `server.ts` 作为极简 MCP 单工具网关(`hose_cli`)直接委托 `cli/runner.ts` 执行
- 业务域如果需要缓存,统一使用 `core/cache/` 提供的多级缓存门面
+2 -2
View File
@@ -4,8 +4,8 @@ import { join } from "node:path";
import { AuthenticationError } from "../errors.js";
import { CorpConfig, CredentialSource } from "../config/types.js";
import { saveCorpConfig, resolveWritableEnterprisesDir } from "../config/loader.js";
import { resolveCorpCluster, clearUnityClientCache } from "../http/unity-client.js";
import { clearScriptEngineClientCache } from "../http/script-engine-client.js";
import { resolveCorpCluster, clearUnityClientCache } from "../http/unity-easo-client.js";
import { clearScriptEngineClientCache } from "../http/piper-workflow-client.js";
import { clearCorpTokens } from "./token-store.js";
import {
DEFAULT_EKB_BASE_URL,
+1 -1
View File
@@ -4,7 +4,7 @@ import { join } from "node:path";
import { AuthenticationError } from "../errors.js";
import { CorpConfig, CorpConfigSchema } from "../config/types.js";
import { saveCorpConfig, resolveWritableEnterprisesDir } from "../config/loader.js";
import { resolveCorpCluster } from "../http/unity-client.js";
import { resolveCorpCluster } from "../http/unity-easo-client.js";
import {
DEFAULT_EKB_BASE_URL,
HoseOpenApiKeyItem,
+25 -18
View File
@@ -1,25 +1,32 @@
# HTTP 客户端与认证衔接(http)
# HTTP 客户端与通信底座(core/http)
本目录封装语义化 HTTP 客户端、指纹、换票和鉴权续期,是 [Core](../README.core.md) 的传输基础设施。业务 URL、响应模型与业务错误校验由各域 `api.ts` 管理,不放进通用工厂。
本目录封装语义化 HTTP 客户端、浏览器指纹伪装、多协议动态换票和自动续期重放,是 [Core](../README.core.md) 的底层网络通信基础设施。业务 URL、响应校验与领域模型由各业务域 `api.ts` 管理,不混入底层通用工厂。
## 客户端选择
## 7 大核心通信客户端矩阵
| 文件 | 使用场景 |
全仓统一收敛为对齐外部网络拓扑与独立服务协议的 **7 大标准客户端**(全部规范使用 `-client.ts` 命名):
| 标准文件名 | 导出的标准工厂 / 方法 | 核心域名端点 | 业务场景与控制范围 |
|---|---|---|---|
| [hose-web-session-client.ts](./hose-web-session-client.ts) | `createHoseWebSessionClient` | `app.ekuaibao.com` | **合思 Web 主站会话客户端**:承载单据台账、报销审批流、费用科目、员工通讯录等闭环操作,带 Cookie / Token 双通道自动无感续杯与 401 防抖重试。 |
| [openapi-client.ts](./openapi-client.ts) | `createOpenApiClient` | `app.ekuaibao.com/api/openapi` | **开放平台官方 OpenAPI 客户端**:基于企业自建应用凭据(`appKey` + `appSecurity`)换取 `accessToken`,调用官方开放标准接口。 |
| [piper-workflow-client.ts](./piper-workflow-client.ts) | `getPiperWorkflowClient` | `piper.ekuaibao.com` | **Piper 工作流引擎客户端**:**自建应用工作流完整控制面与执行引擎**。全面管理工作流创建/命名/全量节点保存/发布/快照历史,编排 108 类节点能力与灰度开通,以及流转实例(Job/Tasks)跟踪排查与代码沙箱调试。 |
| [hose-docs-client.ts](./hose-docs-client.ts) | `createHoseDocsClient` | `docs.ekuaibao.com` | **合思开放文档客户端**:直连官方文档中心,在线拉取 8.4MB 全量富文本索引,自省 330 篇文档与 270+ OpenAPI 规范与参数定义。 |
| [unity-easo-client.ts](./unity-easo-client.ts) | `getUnityEasoClient` / `getEasoClient` | `unity.ekuaibao.com` | **Unity / EASO 运营中台客户端**:负责合思企业部署集群动态寻址(如北京、上海、专有集群)与跨租户全局 JWT / HoseToken 换票。 |
| [assist-platform-client.ts](./assist-platform-client.ts) | `createAssistPlatformClient` | 协助运营平台各集群 | **合思协助平台客户端**:技术支持人员的代客运维工单匹配、无密直通换票与租户提权。 |
| [sso-auth-client.ts](./sso-auth-client.ts) | `createSsoAuthClient` | `sso.hosecloud.com` | **SSO 与扫码鉴权客户端**:企业单点登录、微信/钉钉二维码轮询状态与会话建立。 |
## 辅助基础设施
| 文件 | 说明 |
|---|---|
| [factory.ts](./factory.ts) | Ky 底层客户端和带鉴权恢复的工厂 |
| [session-client.ts](./session-client.ts) | 合思用户 Session 请求与续期 |
| [openapi-client.ts](./openapi-client.ts) | 应用凭证换取 OpenAPI Token 并构造请求 |
| [unity-client.ts](./unity-client.ts) | 应用中心、Unity/EASO 换票及企业集群寻址 |
| [script-engine-client.ts](./script-engine-client.ts) | Piper 脚本引擎客户端与认证缓存 |
| [assist-platform-client.ts](./assist-platform-client.ts) | 协助平台客户端 |
| [sso-client.ts](./sso-client.ts) | SSO 登录请求与二维码状态查询 |
| [fingerprint.ts](./fingerprint.ts) | 统一浏览器指纹和请求头配置 |
| [index.ts](./index.ts) | 对外导出入口 |
| [factory.ts](./factory.ts) | Ky 底层客户端工厂与 401 自动鉴权恢复机制 |
| [fingerprint.ts](./fingerprint.ts) | 统一浏览器指纹(User-Agent、sec-ch-ua、Origin、Referer)伪装 |
| [piper-endpoints.ts](./piper-endpoints.ts) | Piper / ScriptEngine 生产与测试集群域名动态解析收口 |
| [index.ts](./index.ts) | HTTP 客户端基础设施全量规范导出入口 |
## 重放与错误边界
鉴权失效时按工厂配置续期并重放一次,重放响应仍检查 HTTP 状态与鉴权错误头,包括 HTTP 200 携带鉴权错误标记的情况。持续鉴权失败应抛认证异常,不递归换票;普通 HTTP 失败保留客户端原有错误语义。
客户端依据目标企业与协议创建,不能跨企业复用带身份的实例或 Token。缓存失效与凭证存储衔接见 [auth/](../auth/README.auth.md)。日志不得输出认证头或完整会话链接。
[replay-contract.test.ts](./replay-contract.test.ts)、[clients.test.ts](./clients.test.ts)、Session 与续期测试共同验证客户端协议。变更恢复逻辑时同时检查重放次数、请求体保留和最终响应,避免把传输成功误当作业务成功。
1. **自动续期与单次重放**:当鉴权失效时(HTTP 401),客户端按工厂配置续期并最多重放一次。重放响应仍严格检查 HTTP 状态与业务鉴权错误标记(包括 HTTP 200 返回体中带有鉴权失败 code 的情况);
2. **凭据隔离**:客户端依据目标企业与业务协议创建,禁止跨企业复用带身份的客户端实例或 Token;
3. **安全日志**:请求日志严禁输出用户 Token、Cookie、Authorization 头或完整私密会话参数。
+3
View File
@@ -10,6 +10,9 @@ export interface AssistPlatformClientOptions {
timeout?: number;
}
export type CreateAssistPlatformClientOptions = AssistPlatformClientOptions;
export function createAssistPlatformClient(options: AssistPlatformClientOptions): KyInstance {
if (!options.token || !options.token.trim()) {
throw new AuthenticationError("缺少协助平台凭证 Token,请先登录协助平台");
+87
View File
@@ -0,0 +1,87 @@
import { describe, expect, it } from "bun:test";
import {
// 1. hose-web-session-client
createHoseWebSessionClient,
createSessionClient,
getHoseWebSessionHeaders,
getSessionHeaders,
// 2. openapi-client
createOpenApiClient,
getOpenApiHeaders,
// 3. piper-workflow-client
getPiperWorkflowClient,
getScriptEngineClient,
clearPiperWorkflowClientCache,
clearScriptEngineClientCache,
PIPER_BASE_URL,
SCRIPT_ENGINE_BASE_URL,
// 4. hose-docs-client
createHoseDocsClient,
DEFAULT_HOSE_DOCS_BASE_URL,
// 5. unity-easo-client
getUnityEasoClient,
getUnityClient,
getEasoClient,
clearUnityEasoClientCache,
clearUnityClientCache,
resolveCorpCluster,
// 6. assist-platform-client
createAssistPlatformClient,
// 7. sso-auth-client
createSsoAuthClient,
createSsoClient,
DEFAULT_SSO_BASE_URL,
} from "./index.js";
describe("core/http/clients-semantics - 7 大标准通信客户端语义规范验证", () => {
it("1. hose-web-session-client: 正确导出标准客户端工厂与请求头提取器", () => {
expect(createHoseWebSessionClient).toBeDefined();
expect(createSessionClient).toBe(createHoseWebSessionClient);
expect(getHoseWebSessionHeaders).toBeDefined();
expect(getSessionHeaders).toBe(getHoseWebSessionHeaders);
});
it("2. openapi-client: 正确导出官方 OpenAPI 客户端工厂与请求头工具", () => {
expect(createOpenApiClient).toBeDefined();
expect(getOpenApiHeaders).toBeDefined();
});
it("3. piper-workflow-client: 正确导出工作流控制面与执行引擎客户端及缓存工具", () => {
expect(getPiperWorkflowClient).toBeDefined();
expect(getScriptEngineClient).toBe(getPiperWorkflowClient);
expect(clearPiperWorkflowClientCache).toBeDefined();
expect(clearScriptEngineClientCache).toBe(clearPiperWorkflowClientCache);
expect(PIPER_BASE_URL).toBe(SCRIPT_ENGINE_BASE_URL);
});
it("4. hose-docs-client: 正确导出合思开放文档客户端", () => {
expect(createHoseDocsClient).toBeDefined();
expect(DEFAULT_HOSE_DOCS_BASE_URL).toBe("https://docs.ekuaibao.com");
const docsClient = createHoseDocsClient();
expect(docsClient).toBeDefined();
});
it("5. unity-easo-client: 正确导出运营中台与企业集群客户端", () => {
expect(getUnityEasoClient).toBeDefined();
expect(getUnityEasoClient).toBe(getUnityClient);
expect(getEasoClient).toBeDefined();
expect(clearUnityEasoClientCache).toBe(clearUnityClientCache);
expect(resolveCorpCluster).toBeDefined();
});
it("6. assist-platform-client: 正确导出协助运维平台客户端", () => {
expect(createAssistPlatformClient).toBeDefined();
});
it("7. sso-auth-client: 正确导出 SSO 与扫码鉴权客户端", () => {
expect(createSsoAuthClient).toBeDefined();
expect(createSsoAuthClient).toBe(createSsoClient);
expect(DEFAULT_SSO_BASE_URL).toBe("https://sso.hosecloud.com");
});
});
+62 -42
View File
@@ -8,14 +8,33 @@ import {
import {
getSessionHeaders,
createSessionClient,
} from "./session-client.js";
getHoseWebSessionHeaders,
createHoseWebSessionClient,
} from "./hose-web-session-client.js";
import {
createOpenApiClient,
getOpenApiHeaders,
} from "./openapi-client.js";
import { resolveCorpCluster, getEasoClient, getUnityClient, clearUnityClientCache } from "./unity-client.js";
import {
resolveCorpCluster,
getEasoClient,
getUnityClient,
getUnityEasoClient,
clearUnityClientCache,
} from "./unity-easo-client.js";
import { createAssistPlatformClient } from "./assist-platform-client.js";
import { getScriptEngineClient } from "./script-engine-client.js";
import {
getScriptEngineClient,
getPiperWorkflowClient,
} from "./piper-workflow-client.js";
import {
createHoseDocsClient,
DEFAULT_HOSE_DOCS_BASE_URL,
} from "./hose-docs-client.js";
import {
createSsoAuthClient,
createSsoClient,
} from "./sso-auth-client.js";
import { setCorpTokens, resetTokenStoreMemory } from "../auth/token-store.js";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
@@ -47,63 +66,44 @@ describe("core/http/fingerprint", () => {
expect(headers["sec-ch-ua"]).toContain("Chrome");
expect(headers["Cookie"]).toBeUndefined();
});
it("supports custom cookie and referer", () => {
const headers = getBrowserFingerprintHeaders({
cookie: "SESSION=abc123xyz; cloud_waf=token456",
referer: "https://custom.ekuaibao.com/flow",
});
expect(headers["Cookie"]).toBe("SESSION=abc123xyz; cloud_waf=token456");
expect(headers["Referer"]).toBe("https://custom.ekuaibao.com/flow");
});
});
describe("core/http/session-client", () => {
it("merges closed session headers with browser fingerprint", () => {
describe("core/http/hose-web-session-client", () => {
it("injects valid session headers and preserves caller custom options", () => {
const corp = mockCorp();
const headers = getSessionHeaders(corp);
const headers = getHoseWebSessionHeaders(corp, {
referer: "https://custom.ekuaibao.com",
});
// 核心三 Header 校验
expect(headers.accesstoken).toBe("mock-access-token");
expect(headers.corpid).toBe("mock-corp-id");
expect(headers.staffid).toBe("mock-staff-id");
// 统一防爬指纹校验
expect(headers["User-Agent"]).toBe(DEFAULT_USER_AGENT);
expect(headers["Origin"]).toBe(DEFAULT_ORIGIN);
expect(headers["accesstoken"]).toBe("mock-access-token");
expect(headers["corpid"]).toBe("mock-corp-id");
expect(headers["staffid"]).toBe("mock-staff-id");
expect(headers["Referer"]).toBe("https://custom.ekuaibao.com");
});
it("createSessionClient produces valid client", async () => {
it("createHoseWebSessionClient is callable and aliased to createSessionClient", async () => {
const corp = mockCorp();
const client = await createSessionClient(corp);
const client = await createHoseWebSessionClient(corp);
expect(client).toBeDefined();
expect(createSessionClient).toBe(createHoseWebSessionClient);
});
});
describe("core/http/openapi-client", () => {
it("builds correct OpenAPI request headers", () => {
const headers = getOpenApiHeaders("test-app-token-123");
expect(headers["app-token"]).toBe("test-app-token-123");
expect(headers["Authorization"]).toBe("Bearer test-app-token-123");
expect(headers["User-Agent"]).toBe(DEFAULT_USER_AGENT);
it("formats standard Bearer authorization header", () => {
const headers = getOpenApiHeaders("valid-mock-token");
expect(headers["Authorization"]).toBe("Bearer valid-mock-token");
expect(headers["app-token"]).toBe("valid-mock-token");
});
it("creates OpenAPI client with static appToken", async () => {
const client = await createOpenApiClient({
appToken: "static-token",
baseUrl: "https://app.ekuaibao.com",
});
expect(client).toBeDefined();
});
it("fails to create OpenAPI client when neither auth nor appToken is provided", async () => {
it("throws ValidationError when both auth and appToken are missing", async () => {
await expect(createOpenApiClient({})).rejects.toThrow(
"创建 OpenAPI 客户端失败: 必须提供 auth 凭据或 appToken"
);
});
});
describe("core/http/unity-client & script-engine-client", () => {
describe("core/http/unity-easo-client & piper-workflow-client", () => {
it("resolves corp cluster from cluster property or baseUrl", () => {
expect(resolveCorpCluster({ cluster: "shanghai" })).toBe("shanghai");
expect(resolveCorpCluster({ baseUrl: "https://wx2.ekuaibao.com" })).toBe("wx2");
@@ -111,8 +111,14 @@ describe("core/http/unity-client & script-engine-client", () => {
expect(resolveCorpCluster({})).toBe("app");
});
it("getScriptEngineClient is defined and callable", () => {
expect(getScriptEngineClient).toBeDefined();
it("getPiperWorkflowClient is defined and callable (aliased to getScriptEngineClient)", () => {
expect(getPiperWorkflowClient).toBeDefined();
expect(getScriptEngineClient).toBe(getPiperWorkflowClient);
});
it("getUnityEasoClient is defined and aliased to getUnityClient", () => {
expect(getUnityEasoClient).toBeDefined();
expect(getUnityEasoClient).toBe(getUnityClient);
});
it("reuses persisted EASO and Unity tokens from token-store across CLI runs without network calls", async () => {
@@ -171,3 +177,17 @@ describe("core/http/unity-client & script-engine-client", () => {
}).toThrow("协助平台凭证已过期或无效,请运行: hose-use assist-platform login 重新扫码登录");
});
});
describe("core/http/hose-docs-client & sso-auth-client", () => {
it("createHoseDocsClient constructs with default base URL and docs user-agent", () => {
const client = createHoseDocsClient();
expect(client).toBeDefined();
expect(DEFAULT_HOSE_DOCS_BASE_URL).toBe("https://docs.ekuaibao.com");
});
it("createSsoAuthClient is aliased to createSsoClient and instantiates correctly", () => {
expect(createSsoAuthClient).toBe(createSsoClient);
const ssoClient = createSsoAuthClient();
expect(ssoClient).toBeDefined();
});
});
+29
View File
@@ -0,0 +1,29 @@
import ky, { type KyInstance } from "ky";
export const DEFAULT_HOSE_DOCS_BASE_URL = "https://docs.ekuaibao.com";
export interface CreateHoseDocsClientOptions {
/** 文档站点基础地址 (默认 https://docs.ekuaibao.com) */
baseUrl?: string;
/** 超时毫秒数 (默认 15000) */
timeout?: number;
}
/**
* 创建合思开放文档客户端 (Hose Open Docs Client)
* 直连合思官方开放平台接口文档中心 (docs.ekuaibao.com),
* 负责在线检索与拉取全量 8.4MB 接口索引,自省 330 篇文档与 270+ HTTP OpenAPI 规范。
*/
export function createHoseDocsClient(
options: CreateHoseDocsClientOptions = {}
): KyInstance {
const baseUrl = options.baseUrl || DEFAULT_HOSE_DOCS_BASE_URL;
return ky.create({
prefix: baseUrl.replace(/\/+$/, ""),
timeout: options.timeout ?? 15000,
headers: {
Accept: "application/json",
"User-Agent": "hose-use/docs-client",
},
});
}
@@ -10,7 +10,7 @@ import {
resolveLinkExpiresAt,
selectOpenApiKey,
} from "../auth/login.js";
import { createSessionClient } from "./session-client.js";
import { createSessionClient } from "./hose-web-session-client.js";
import type { CorpConfig } from "../config/types.js";
function corp(overrides: Partial<CorpConfig> = {}): CorpConfig {
@@ -24,7 +24,7 @@ function corp(overrides: Partial<CorpConfig> = {}): CorpConfig {
};
}
describe("core/http/session-client refresh policy", () => {
describe("core/http/hose-web-session-client refresh policy", () => {
it("allows refresh for account credentials or OpenAPI persistent credentials", () => {
expect(canRefreshCorpAccessToken(corp())).toBe(false);
expect(canRefreshCorpAccessToken(corp({ source: "browser", accountId: "86-1" }))).toBe(false);
@@ -10,17 +10,19 @@ import {
refreshSingleCorpAccessToken,
} from "../auth/login.js";
export interface CreateSessionClientOptions {
export interface CreateHoseWebSessionClientOptions {
/** 额外的指纹或请求头配置 */
fingerprint?: BrowserFingerprintOptions;
/** 超时毫秒数 (默认 30000) */
timeout?: number | false;
}
export type CreateSessionClientOptions = CreateHoseWebSessionClientOptions;
/**
* 获取闭合用户会话所必需的认证请求头与浏览器指纹
* 获取合思 Web 主站会话所必需的认证请求头与浏览器指纹
*/
export function getSessionHeaders(
export function getHoseWebSessionHeaders(
corp: CorpConfig,
fingerprintOptions?: BrowserFingerprintOptions
): Record<string, string> {
@@ -34,13 +36,16 @@ export function getSessionHeaders(
};
}
export const getSessionHeaders = getHoseWebSessionHeaders;
/**
* 创建合思闭合用户会话客户端 (Session Client)
* 适用于内部单据台账、审批流、员工角色、配置等闭环操作
* 创建合思 Web 主站用户会话客户端 (Hose Web Session Client)
* 直连合思主站 (app.ekuaibao.com),承载单据台账、报销审批流、
* 费用类型科目、员工通讯录等闭环操作,带 Cookie/Token 双通道自动续期与 401 重试。
*/
export async function createSessionClient(
export async function createHoseWebSessionClient(
corp: CorpConfig,
options: CreateSessionClientOptions = {}
options: CreateHoseWebSessionClientOptions = {}
) {
const canRefresh = canRefreshCorpAccessToken(corp);
@@ -56,7 +61,7 @@ export async function createSessionClient(
// 2. 具备续期能力(主账号或 OpenAPI 持久化密钥)时启用 401 自动重试与换票;临时凭证直接给出可操作错误
return createAuthClient({
prefixUrl: corp.baseUrl || "https://app.ekuaibao.com",
getHeaders: () => getSessionHeaders(corp, options.fingerprint),
getHeaders: () => getHoseWebSessionHeaders(corp, options.fingerprint),
timeout: options.timeout,
retryUnauthorized: canRefresh,
...(canRefresh
@@ -71,3 +76,5 @@ export async function createSessionClient(
}),
});
}
export const createSessionClient = createHoseWebSessionClient;
+62 -12
View File
@@ -1,9 +1,16 @@
/**
* HTTP 客户端基础设施总入口
* 包含基础 Ky 客户端工厂、浏览器指纹伪装、闭合用户会话客户端、开放平台客户端、集群客户端及脚本流引擎客户端。
* 统一管理 7 大核心通信客户端:
* 1. hose-web-session-client (合思 Web 主站会话客户端,打 app.ekuaibao.com)
* 2. openapi-client (开放平台官方 OpenAPI 客户端,打开放标准接口)
* 3. piper-workflow-client (Piper 工作流引擎客户端,打 piper.ekuaibao.com 工作流全生命周期)
* 4. hose-docs-client (合思开放文档客户端,打 docs.ekuaibao.com 接口自省与同步)
* 5. unity-easo-client (Unity / EASO 运营中台客户端,企业集群寻址与全局换票)
* 6. assist-platform-client (合思协助平台客户端,代客工单免密直通)
* 7. sso-auth-client (SSO 与扫码鉴权客户端,单点登录与扫码认证)
*/
// 1. 底层 Ky 基础工厂
// ── 基础工厂与指纹 ─────────────────────────────────────────────────────────────
export {
createClient,
createAuthClient,
@@ -11,7 +18,6 @@ export {
type CreateAuthClientOptions,
} from "./factory.js";
// 2. 统一浏览器指纹与防爬请求头
export {
getBrowserFingerprintHeaders,
DEFAULT_USER_AGENT,
@@ -20,14 +26,17 @@ export {
type BrowserFingerprintOptions,
} from "./fingerprint.js";
// 3. 闭合用户会话客户端 (Session Client)
// ── 1. 合思 Web 主站会话客户端 (hose-web-session-client) ──────────────────────
export {
createHoseWebSessionClient,
createSessionClient,
getHoseWebSessionHeaders,
getSessionHeaders,
type CreateHoseWebSessionClientOptions,
type CreateSessionClientOptions,
} from "./session-client.js";
} from "./hose-web-session-client.js";
// 4. 开放平台 OpenAPI 客户端 (OpenAPI Client)
// ── 2. 开放平台官方 OpenAPI 客户端 (openapi-client) ───────────────────────────
export {
createOpenApiClient,
fetchOpenApiToken,
@@ -36,17 +45,58 @@ export {
type CreateOpenApiClientOptions,
} from "./openapi-client.js";
// 5. 应用中心与集群寻址客户端 (Unity Client)
// ── 3. Piper 工作流引擎客户端 (piper-workflow-client) ─────────────────────────
export {
getPiperWorkflowClient,
getScriptEngineClient,
clearPiperWorkflowClientCache,
clearScriptEngineClientCache,
fetchEasoJwt,
resolvePiperBaseUrl,
PIPER_BASE_URL,
SCRIPT_ENGINE_BASE_URL,
SCRIPT_ENGINE_TEST_BASE_URL,
} from "./piper-workflow-client.js";
// ── 4. 合思开放文档客户端 (hose-docs-client) ──────────────────────────────────
export {
createHoseDocsClient,
DEFAULT_HOSE_DOCS_BASE_URL,
type CreateHoseDocsClientOptions,
} from "./hose-docs-client.js";
// ── 5. Unity / EASO 运营中台客户端 (unity-easo-client) ────────────────────────
export {
getUnityEasoClient,
getUnityClient,
getEasoClient,
resolveCorpCluster,
fetchUnityJwt,
fetchHoseToken,
} from "./unity-client.js";
clearUnityEasoClientCache,
clearUnityClientCache,
EASO_BASE_URL,
BUSINESS_CENTER_URL,
EKB_BASE_URL,
} from "./unity-easo-client.js";
// 6. 工作流脚本调试引擎客户端 (Script Engine Client)
// ── 6. 合思协助平台客户端 (assist-platform-client) ────────────────────────────
export {
getScriptEngineClient,
fetchEasoJwt,
} from "./script-engine-client.js";
createAssistPlatformClient,
type AssistPlatformClientOptions,
type CreateAssistPlatformClientOptions,
} from "./assist-platform-client.js";
// ── 7. SSO 与扫码鉴权客户端 (sso-auth-client) ─────────────────────────────────
export {
createSsoAuthClient,
createSsoClient,
getSsoQrCode,
pollSsoQrCodeStatus,
verifySsoTokenOnUnity,
DEFAULT_SSO_BASE_URL,
type SsoAuthClientOptions,
type SsoClientOptions,
type SsoQrCodeResult,
type QrCodeStatusResponse,
} from "./sso-auth-client.js";
@@ -6,7 +6,7 @@ import {
resolveCorpCluster,
fetchHoseToken,
EKB_BASE_URL,
} from "./unity-client.js";
} from "./unity-easo-client.js";
import {
canRefreshCorpAccessToken,
refreshSingleCorpAccessToken,
@@ -32,19 +32,19 @@ export {
export const PIPER_BASE_URL = SCRIPT_ENGINE_BASE_URL;
// 内存缓存
const scriptEngineMemoryCache = new Map<
const piperWorkflowMemoryCache = new Map<
string,
{ jwt: string; hoseToken: string; expiresAt: number; sourceAccessToken?: string }
>();
function invalidateScriptEngineCache(corpId: string, cacheKey?: string): void {
function invalidatePiperWorkflowCache(corpId: string, cacheKey?: string): void {
if (cacheKey) {
scriptEngineMemoryCache.delete(cacheKey);
piperWorkflowMemoryCache.delete(cacheKey);
} else {
const prefix = `${corpId}:`;
for (const key of scriptEngineMemoryCache.keys()) {
for (const key of piperWorkflowMemoryCache.keys()) {
if (key.startsWith(prefix)) {
scriptEngineMemoryCache.delete(key);
piperWorkflowMemoryCache.delete(key);
}
}
}
@@ -56,14 +56,16 @@ function invalidateScriptEngineCache(corpId: string, cacheKey?: string): void {
}
}
export function clearScriptEngineClientCache(corpId?: string): void {
export function clearPiperWorkflowClientCache(corpId?: string): void {
if (!corpId) {
scriptEngineMemoryCache.clear();
piperWorkflowMemoryCache.clear();
return;
}
invalidateScriptEngineCache(corpId);
invalidatePiperWorkflowCache(corpId);
}
export const clearScriptEngineClientCache = clearPiperWorkflowClientCache;
function isExpired(entry: { expiresAt: number }, refreshTtl: number): boolean {
return Date.now() >= entry.expiresAt - refreshTtl * 1000;
}
@@ -92,18 +94,22 @@ export async function fetchEasoJwt(
}
/**
* 获取工作流脚本执行引擎客户端 (Workflow Script Engine Client / Piper Client)
* 适用于 MVEL、Python 等工作流代码节点的在线执行与调试
* 获取 Piper 工作流引擎客户端 (Piper Workflow Engine Client)
* 直连 piper.ekuaibao.com,作为合思自建应用工作流的核心控制面与执行引擎:
* - 工作流全生命周期:创建、重命名、全量节点草稿保存、自动生成 chooses 元数据、复制与快照版本历史;
* - 全量节点编排调度:触发器、HTTP 出向请求、分支判断、审批流重算、通知与代码节点;
* - 节点能力字典与灰度:108 个底层工作流节点能力的声明探查与灰度开通;
* - 流转实例与执行监控:Job 运行实例排查、Tasks 任务流链路跟踪与 MVEL/Python 代码沙箱单步调试。
*/
export async function getScriptEngineClient(
export async function getPiperWorkflowClient(
corp: CorpConfig,
platformId: string
): Promise<ReturnType<typeof createAuthClient>> {
const refreshTtl = corp.auth?.refreshTtl ?? 300;
const cacheKey = `${corp.id}:${platformId}:script-engine`;
const cacheKey = `${corp.id}:${platformId}:piper-workflow`;
// 1. 检查 L1 内存缓存
let mem = scriptEngineMemoryCache.get(cacheKey);
let mem = piperWorkflowMemoryCache.get(cacheKey);
// 2. 检查 L2 持久化 TokenStore
if (!mem) {
@@ -119,7 +125,7 @@ export async function getScriptEngineClient(
expiresAt: persisted.expiresAt,
sourceAccessToken: persisted.sourceAccessToken,
};
scriptEngineMemoryCache.set(cacheKey, mem);
piperWorkflowMemoryCache.set(cacheKey, mem);
}
}
@@ -130,19 +136,19 @@ export async function getScriptEngineClient(
prefixUrl: resolvePiperBaseUrl(),
getHeaders: () => {
const headers: Record<string, string> = {
Authorization: `Bearer ${scriptEngineMemoryCache.get(cacheKey)?.jwt ?? cachedJwt}`,
Authorization: `Bearer ${piperWorkflowMemoryCache.get(cacheKey)?.jwt ?? cachedJwt}`,
platformid: platformId,
};
const currentHoseToken = scriptEngineMemoryCache.get(cacheKey)?.hoseToken ?? cachedHoseToken;
const currentHoseToken = piperWorkflowMemoryCache.get(cacheKey)?.hoseToken ?? cachedHoseToken;
if (currentHoseToken) {
headers.hoseaccesstoken = currentHoseToken;
}
return headers;
},
onUnauthorized: async () => {
invalidateScriptEngineCache(corp.id, cacheKey);
invalidatePiperWorkflowCache(corp.id, cacheKey);
if (canRefreshCorpAccessToken(corp)) await refreshSingleCorpAccessToken(corp);
await getScriptEngineClient(corp, platformId);
await getPiperWorkflowClient(corp, platformId);
},
});
}
@@ -169,7 +175,7 @@ export async function getScriptEngineClient(
);
} catch {
// 独立私有化域名或部分仅持 OpenAPI 凭证的租户在 business-center 换取 hose-access-token 可能受限,
// 此处优雅降级避免阻塞 Piper / ScriptEngine 客户端构建
// 此处优雅降级避免阻塞 Piper / Workflow 客户端构建
}
const easoJwt = await fetchEasoJwt(
corp.credentials.accessToken,
@@ -186,7 +192,7 @@ export async function getScriptEngineClient(
sourceAccessToken: corp.credentials.accessToken,
};
scriptEngineMemoryCache.set(cacheKey, entry);
piperWorkflowMemoryCache.set(cacheKey, entry);
const existingTokens = getCorpTokens(corp.id) ?? {};
setCorpTokens(corp.id, {
@@ -203,19 +209,21 @@ export async function getScriptEngineClient(
prefixUrl: SCRIPT_ENGINE_BASE_URL,
getHeaders: () => {
const headers: Record<string, string> = {
Authorization: `Bearer ${scriptEngineMemoryCache.get(cacheKey)?.jwt ?? easoJwt}`,
Authorization: `Bearer ${piperWorkflowMemoryCache.get(cacheKey)?.jwt ?? easoJwt}`,
platformid: platformId,
};
const currentHoseToken = scriptEngineMemoryCache.get(cacheKey)?.hoseToken ?? hoseToken;
const currentHoseToken = piperWorkflowMemoryCache.get(cacheKey)?.hoseToken ?? hoseToken;
if (currentHoseToken) {
headers.hoseaccesstoken = currentHoseToken;
}
return headers;
},
onUnauthorized: async () => {
invalidateScriptEngineCache(corp.id, cacheKey);
invalidatePiperWorkflowCache(corp.id, cacheKey);
if (canRefreshCorpAccessToken(corp)) await refreshSingleCorpAccessToken(corp);
await getScriptEngineClient(corp, platformId);
await getPiperWorkflowClient(corp, platformId);
},
});
}
export const getScriptEngineClient = getPiperWorkflowClient;
@@ -4,10 +4,10 @@ import {
getSsoQrCode,
pollSsoQrCodeStatus,
verifySsoTokenOnUnity,
} from "./sso-client.js";
} from "./sso-auth-client.js";
import { AuthenticationError } from "../errors.js";
describe("core/http/sso-client", () => {
describe("core/http/sso-auth-client", () => {
it("getSsoQrCode 能够正常解析二维码链接与 Session Cookie", async () => {
const mockClient = {
post: async () => ({
@@ -8,6 +8,8 @@ export interface SsoClientOptions {
timeout?: number;
}
export type SsoAuthClientOptions = SsoClientOptions;
export function createSsoClient(options: SsoClientOptions = {}): KyInstance {
const baseUrl = options.baseUrl || DEFAULT_SSO_BASE_URL;
return ky.create({
@@ -15,12 +17,16 @@ export function createSsoClient(options: SsoClientOptions = {}): KyInstance {
timeout: options.timeout ?? 15000,
headers: {
accept: "application/json, text/plain, */*",
"user-agent": "hose-use/assist-platform-client",
"user-agent": "hose-use/sso-auth-client",
referer: `${baseUrl}/`,
},
});
}
/** 语义化标准别名 (SSO 与扫码鉴权客户端) */
export const createSsoAuthClient = createSsoClient;
export interface QrCodeStatusResponse {
code: number;
message: string;
+2 -2
View File
@@ -2,8 +2,8 @@ import { afterEach, expect, test } from "bun:test";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { getEasoClient, getUnityClient, clearUnityClientCache } from "./unity-client.js";
import { getScriptEngineClient, clearScriptEngineClientCache } from "./script-engine-client.js";
import { getEasoClient, getUnityClient, clearUnityClientCache } from "./unity-easo-client.js";
import { getScriptEngineClient, clearScriptEngineClientCache } from "./piper-workflow-client.js";
import { resetTokenStoreMemory, setCorpTokens } from "../auth/token-store.js";
const oldFetch = globalThis.fetch, oldFile = process.env.HOSE_TOKENS_FILE;
afterEach(() => { clearScriptEngineClientCache(); clearUnityClientCache(); resetTokenStoreMemory(); globalThis.fetch = oldFetch; if (oldFile === undefined) delete process.env.HOSE_TOKENS_FILE; else process.env.HOSE_TOKENS_FILE = oldFile; });
@@ -403,3 +403,8 @@ export async function getUnityClient(corp: CorpConfig): Promise<{
}),
};
}
/** 语义化标准别名 (Unity EASO 运营中台客户端) */
export const getUnityEasoClient = getUnityClient;
export const clearUnityEasoClientCache = clearUnityClientCache;
@@ -4,7 +4,7 @@
## 架构与分工
- **SSO 身份客户端 (`src/core/http/sso-client.ts`)**:
- **SSO 身份客户端 (`src/core/http/sso-auth-client.ts`)**:
负责与 `sso.hosecloud.com` 的登录二维码生成、扫码状态轮询以及凭证提取。
- **协助平台网关客户端 (`src/core/http/assist-platform-client.ts`)**:
负责与 `unity.ekuaibao.com/api` 网关通信,自动挂载 `token: <sessionToken>` 请求头与 Cookie。
+1 -1
View File
@@ -9,7 +9,7 @@ import {
getSsoQrCode,
pollSsoQrCodeStatus,
verifySsoTokenOnUnity,
} from "../../core/http/sso-client.js";
} from "../../core/http/sso-auth-client.js";
import type { CorpConfig } from "../../core/config/types.js";
import {
approveAssistTicketApi,
+1 -1
View File
@@ -1,4 +1,4 @@
import { getEasoClient } from "../../core/http/unity-client.js";
import { getEasoClient } from "../../core/http/unity-easo-client.js";
import type { CorpConfig } from "../../core/config/types.js";
import { fetchStaffs } from "./api.js";
import type { ContactListResult, ContactSearchOptions, Staff } from "./types.js";
+9 -11
View File
@@ -1,12 +1,15 @@
import ky from "ky";
import { EkbApiError } from "../../core/errors.js";
import {
createHoseDocsClient,
DEFAULT_HOSE_DOCS_BASE_URL,
} from "../../core/http/hose-docs-client.js";
import {
DocCatalogSchema,
type DocCatalog,
type OpenApiDocItem,
} from "./types.js";
export const DEFAULT_DOCS_BASE_URL = "https://docs.ekuaibao.com";
export const DEFAULT_DOCS_BASE_URL = DEFAULT_HOSE_DOCS_BASE_URL;
interface RawSearchDoc {
i: number;
@@ -142,16 +145,11 @@ export async function fetchLiveDocsCatalog(options?: {
}): Promise<DocCatalog> {
const baseUrl = options?.baseUrl || DEFAULT_DOCS_BASE_URL;
const timeoutMs = options?.timeoutMs ?? 15000;
const targetUrl = `${baseUrl.replace(/\/+$/, "")}/search-index.json`;
const client = createHoseDocsClient({ baseUrl, timeout: timeoutMs });
try {
const response = await ky.get(targetUrl, {
timeout: timeoutMs,
headers: {
Accept: "application/json",
"User-Agent": "hose-use/docs-client",
},
});
const response = await client.get("search-index.json");
if (!response.ok) {
throw new EkbApiError(
@@ -173,7 +171,7 @@ export async function fetchLiveDocsCatalog(options?: {
} catch (error: any) {
if (error instanceof EkbApiError) throw error;
throw new EkbApiError(
`请求开放平台文档站点 (${targetUrl}) 失败: ${error?.message || String(error)}`,
`请求开放平台文档站点 (${baseUrl}/search-index.json) 失败: ${error?.message || String(error)}`,
"DOCS_NETWORK_ERROR",
502
);
+1 -1
View File
@@ -17,7 +17,7 @@ domains/feetype/tools.ts (业务编排:树展开、路径计算、字段规
domains/feetype/api.ts (HTTP 传输层:直连 /api/v1/form/feeTypes 与 /api/form/v2/specifications)
│
▼
core/http/session-client.ts (企业会话客户端与凭证注入)
core/http/hose-web-session-client.ts (企业会话客户端与凭证注入)
```
## 接口路由映射
+1 -1
View File
@@ -1,4 +1,4 @@
import { createSessionClient } from "../../core/http/session-client.js";
import { createSessionClient } from "../../core/http/hose-web-session-client.js";
import type { CorpConfig } from "../../core/config/types.js";
import {
fetchDesktopMenuTree,
@@ -1,12 +1,14 @@
# 工作流 HTTP 传输
- [pipeline/api.ts](./pipeline/api.ts):工作流列表、配置、快照和日志。
- [execution/api.ts](./execution/api.ts):Job 和执行节点读取。
- [catalog/api.ts](./catalog/api.ts):DSL、员工、枚举和节点开通。
- [debug/api.ts](./debug/api.ts):Webhook、采样和调试。
本目录负责自建应用工作流与后端引擎(`piper.ekuaibao.com`)及运营网关的 HTTP 通信:
- [pipeline/api.ts](./pipeline/api.ts):工作流列表、详情、全量节点配置保存、发布、快照和日志。
- [execution/api.ts](./execution/api.ts):Job 流转实例和执行节点状态读取。
- [catalog/api.ts](./catalog/api.ts):DSL 元数据、员工、枚举和 108 类节点能力开通。
- [debug/api.ts](./debug/api.ts):Webhook、采样和 MVEL/Python 代码节点调试。
- [response.ts](./response.ts):EASO/Piper 响应和写入结果校验。
上级 [api.ts](../api.ts) 保留统一传输出口。入口层应使用 `services.ts`,不能直接依赖此目录的 API。
底层核心通信统一由 `core/http/piper-workflow-client.ts` 承载,上级 [api.ts](../api.ts) 保留统一传输出口。入口层应使用 `services.ts`,不能直接依赖此目录的 API。
## 写入结果判定
@@ -1,8 +1,8 @@
import { z } from "zod";
import ky, { type KyInstance } from "ky";
import { EkbApiError, EkbError } from "../../../../../core/errors.js";
import { fetchEasoJwt, resolvePiperBaseUrl } from "../../../../../core/http/script-engine-client.js";
import { EKB_BASE_URL } from "../../../../../core/http/unity-client.js";
import { fetchEasoJwt, resolvePiperBaseUrl } from "../../../../../core/http/piper-workflow-client.js";
import { EKB_BASE_URL } from "../../../../../core/http/unity-easo-client.js";
import { WorkflowDslSchema, WorkflowDslCatalogSchema, StaffSchema, WorkflowEnumItemSchema, type WorkflowEnumItem } from "../../types.js";
import { unwrap, assertNoAuthFailure } from "../response.js";