替换灰度节点开通第三方网关
- 使用本地企业凭证换取 EASO JWT 并直连 Piper - 校验 Piper 业务码并映射节点开通结果 - 更新节点 Skill 和接口目录
This commit is contained in:
1 parent
07a8a792af
commit
e562ae9227
10 files changed
+211
-182
No files matched your search
@@ -13,39 +13,29 @@ description: |
|
||||
|
||||
## 参数提取
|
||||
|
||||
用户通常会贴浏览器请求(curl),从请求中自动提取参数:
|
||||
使用本机已配置的企业和认证信息,不需要浏览器 curl、手工提取 token 或调用第三方网关:
|
||||
|
||||
| 参数 | 提取位置 | 说明 |
|
||||
|------|----------|------|
|
||||
| token | Header `accesstoken` 或 Cookie `ekb-access-token` | accessToken |
|
||||
| corpId | Header `corpid` 或 URL query `corpId` | 企业 ID |
|
||||
| baseUrl | URL 协议+域名部分(如 `https://dd2.hosecloud.com`) | 自定义合思地址 |
|
||||
| nodes | 向用户确认 | 节点名,逗号分隔 |
|
||||
| 参数 | 来源 | 说明 |
|
||||
|------|------|------|
|
||||
| 企业 | `hose-use corps list` | 用 `--corp=<id>` 指定目标企业;遵循企业环境标记 |
|
||||
| 节点类型 | 本文件中的灰度节点清单 | 传 `type` 值,不传中文显示名 |
|
||||
|
||||
**域名判断**:URL 不是 `*.hosecloud.com` 而是 `dd2.hosecloud.com` 这类就是自定义域名,必须提取为 `baseUrl`。
|
||||
CLI 使用本地企业配置中的 `accessToken`、员工 ID 和 `baseUrl` 完成 EASO 换票与 Piper 请求;凭证不需要复制到 shell 命令或聊天中。
|
||||
|
||||
## 执行
|
||||
|
||||
```bash
|
||||
# 网关地址优先取环境变量 HOSE_GRAY_GATEWAY_URL(尾部斜杠会自动忽略),未配置时用内置默认地址
|
||||
GATEWAY="${HOSE_GRAY_GATEWAY_URL:-https://d9jxeccs5j.sealosgzg.site}"
|
||||
curl -s -X POST "${GATEWAY%/}/hose-workflow-node" \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"token":"TOKEN","corpId":"CORPID","nodes":"NODES"}'
|
||||
hose-use workflow nodes grant code risk --corp=<corpId> --dry-run
|
||||
hose-use workflow nodes grant code risk --corp=<corpId> --yes
|
||||
```
|
||||
|
||||
> 网关托管在第三方域,实例可能被回收或迁移。CLI 侧同样支持 `HOSE_GRAY_GATEWAY_URL` 覆盖;
|
||||
> 网关不可用时不要自行改用其他地址,先确认变量指向的实例仍然有效。
|
||||
|
||||
可选参数:
|
||||
- `baseUrl: "https://..."` — **重要:用户使用了自定义域名时(如 `dd2.hosecloud.com`),必须加上此参数。** 不传则默认走正式环境认证地址。
|
||||
- `isTest: true` — 仅用于切换内部标记,不能替代 `baseUrl`
|
||||
工作流节点开通的 CLI 命令保持不变。先用 `--dry-run` 预览目标和节点,再对同一命令使用 `--yes` 执行。
|
||||
|
||||
## 结果处理
|
||||
|
||||
**成功**:`{"success":true,"data":{"msg":"新开通的节点:xxx"}}`
|
||||
**成功**:CLI 根据 Piper 业务响应中的 `code` 确认开通结果,并显示新开通或已开通的节点。
|
||||
|
||||
**失败排查**:
|
||||
- `认证失败` + `缺少或传错了 baseUrl` — 检查用户请求是否走自定义域名,加上 `baseUrl`
|
||||
- `认证失败` + 其他 — token 过期,让用户重新获取
|
||||
- 认证失败 — 检查本地企业凭证是否有效,并按 CLI 提示重新登录或刷新认证
|
||||
- Piper 业务码失败 — 依据 CLI 返回的业务错误信息排查企业或节点配置
|
||||
- 节点名错误 — 核对名称拼写
|
||||
@@ -58,7 +58,6 @@ specs/hose-close-api/
|
||||
| `EASO` | `https://unity.ekuaibao.com` | EASO 平台、协助平台网关 |
|
||||
| `PIPER` | `https://piper.ekuaibao.com` | 工作流(pipeline)与 Job 执行 |
|
||||
| `ASSIST` | `https://unity.ekuaibao.com/api` | 协助平台客户端前缀 |
|
||||
| `GW` | `https://d9jxeccs5j.sealosgzg.site` | 灰度节点开通网关(非合思域名) |
|
||||
|
||||
## 响应包装约定
|
||||
|
||||
|
||||
@@ -74,7 +74,7 @@ staffId, userId, sourceChannel?, baseUrl?, external?, needAuth?
|
||||
| P27 | POST | `PIPER /api/easo/pipelines/{id}/debugSource` | `{number,pageSize,keywords?}` | `{code,msg,data:{type,total,items:[{id,title,flowState}],fields:[{key,label}],label}}` | `src/domains/platform/workflow/transport/debug/api.ts:28` | 否 |
|
||||
| P28 | POST | `PIPER /api/easo/jobs` | `{pipelineId,inputs:{id,data?,$autoPublish},dataLimit}` | `{code,msg,data:<jobId>|{id}|{jobId}}` | `src/domains/platform/workflow/transport/debug/api.ts:43` | 否 |
|
||||
| P29 | POST | `PIPER /api/easo/dsl/condition/select/EKB_ENUM` | Query `{thirdId}`;body `{}` 或 `{$platformId}` | `{code,msg,data:[{label,code,name?}]}` | `src/domains/platform/workflow/transport/catalog/api.ts:57` | 否 |
|
||||
| P30 | POST | `GW /hose-workflow-node` | `{token,corpId,nodes:"a,b,c",baseUrl?}` | `{success,saved:[],skipped:[],msg?}` | `src/domains/platform/workflow/transport/catalog/api.ts:74` | 否 |
|
||||
| P30 | POST | `PIPER /api/easo/dsl/corporation` | `{corporationId,dslTypes:[type],"recalculate-the-approval-flow":true,"ui-notification":true,start:0}`;Authorization: Bearer EASO JWT | `{code,msg,data?}`;成功必须 `code:200` | `src/domains/platform/workflow/transport/catalog/api.ts:130` | 否 |
|
||||
|
||||
`Platform` 代码字段(`src/domains/platform/workflow/models/nodes.ts:5`):
|
||||
|
||||
|
||||
@@ -169,9 +169,9 @@ MVEL 本地仿真支持的是转译子集:零参 `HashMap` / `ArrayList` 及 `
|
||||
|
||||
快照 Diff 对比节点的全部配置字段(脚本和过滤器沿用专用输出),覆盖 `mapping/inputs/fields` 及自定义配置。节点顺序或父容器变化通过 `configChanges` 中的 `$path` 表达,不依赖服务端是否重算索引。
|
||||
|
||||
灰度开通网关明确返回失败时,CLI 保留失败详情并返回非零退出码;文本输出不再宣称权限生效,JSON 中的 `success` 与退出码保持一致。网关既没有返回 `success`、也没有返回可识别的 `code` 时,同样判为失败而非成功——谎报开通会让下游继续报 `PERMISSION_MISSING_NODE`,比如实报错更难排查。
|
||||
灰度节点开通以 Piper 响应中的业务 `code` 判定结果;非 200 业务码时 CLI 保留失败详情并返回非零退出码,HTTP 200 本身不会被视为成功。这样可以避免开通未生效却误报成功、下游仍报 `PERMISSION_MISSING_NODE` 的情况。
|
||||
|
||||
网关地址不再硬编码:可用环境变量 `HOSE_GRAY_GATEWAY_URL` 覆盖内置默认地址(原本固定的第三方托管域曾出现实例回收风险),请求路径统一为 `/hose-workflow-node`,详见 [transport/README.transport.md](./transport/README.transport.md)。传入的 `baseUrl` 只是目标租户地址,不是网关地址。
|
||||
灰度节点开通不再依赖第三方网关:CLI 使用企业 `baseUrl` 换取 EASO JWT,再直连项目现有的标准 Piper 地址请求 `/api/easo/dsl/corporation`。当前统一使用 `SCRIPT_ENGINE_BASE_URL`,不会仅因 `env=test` 自动切换到 `piper-test`;详见 [transport/README.transport.md](./transport/README.transport.md)。
|
||||
|
||||
监听结果区分完成、超时、快照和取消:只有到达终态才发送 `job_completed`;超时发送 `timeout` 并设置 `timedOut`,取消设置 `cancelled`。CLI 超时或取消返回非零退出码;`--once` 的运行中快照仍可成功返回,且不冒充完成。持续监听的总超时预算覆盖正在跟踪的 Job。
|
||||
|
||||
|
||||
@@ -107,6 +107,7 @@ export async function grantWorkflowNodes(
|
||||
|
||||
const token = corp.credentials?.accessToken;
|
||||
const corpId = corp.corpId || corp.credentials?.corpId || corp.id;
|
||||
const staffId = corp.staffId || corp.credentials?.staffId || "";
|
||||
const baseUrl = corp.baseUrl;
|
||||
|
||||
if (!token) {
|
||||
@@ -117,9 +118,9 @@ export async function grantWorkflowNodes(
|
||||
const result = await api.grantWorkflowNodesApi({
|
||||
token,
|
||||
corpId,
|
||||
staffId,
|
||||
nodes: normalizedNodes,
|
||||
baseUrl,
|
||||
gatewayUrl: options.gatewayUrl,
|
||||
});
|
||||
|
||||
return result;
|
||||
|
||||
@@ -46,8 +46,6 @@ export interface AvailableWorkflowNodes {
|
||||
export interface GrantWorkflowNodesOptions {
|
||||
nodes: string[];
|
||||
password?: string;
|
||||
/** 覆盖灰度开通网关地址;缺省使用环境变量 HOSE_GRAY_GATEWAY_URL。 */
|
||||
gatewayUrl?: string;
|
||||
}
|
||||
|
||||
export interface GrantWorkflowNodesResult {
|
||||
|
||||
@@ -13,12 +13,12 @@
|
||||
所有写操作(保存、刷新 chooses、删除、启停)统一走 `readEasoWriteResponse`:先按 HTTP 状态,再解析 body 中的业务码 `code`。
|
||||
**HTTP 200 不等于业务成功**,只看状态码会把未生效的写操作报成成功。
|
||||
|
||||
## 灰度开通网关 (grantWorkflowNodesApi)
|
||||
## 灰度节点开通 (grantWorkflowNodesApi)
|
||||
|
||||
| 项目 | 说明 |
|
||||
|---|---|
|
||||
| 请求地址 | `resolveGrayGatewayUrl()`:显式 `gatewayUrl` 参数 > 环境变量 `HOSE_GRAY_GATEWAY_URL` > 内置默认 `DEFAULT_GRAY_GATEWAY_URL` |
|
||||
| 环境变量用途 | 网关托管在第三方域,实例可能被回收或迁移;配置环境变量可在不改代码的情况下切换网关 |
|
||||
| `baseUrl` 参数 | 目标合思租户地址,作为 body 字段交给网关定位企业,与网关自身地址无关 |
|
||||
| 成功判定 | 优先取显式 `success` 布尔值,其次取 `code === 200`;**两者都缺失时判为失败**,不默认成功 |
|
||||
| 失败信息 | 传输异常抛 `EkbApiError`(`GATEWAY_ERROR`),消息带上实际请求的网关地址 |
|
||||
| 换票 | 通过企业 `baseUrl` 的 `/api/engine/realm/$EASO/actions/jwt` 获取 EASO JWT;复用 `fetchEasoJwt`,去除 `baseUrl` 末尾斜线 |
|
||||
| 开通请求 | 携带 EASO JWT 直接 POST 到 `SCRIPT_ENGINE_BASE_URL/api/easo/dsl/corporation`,目标与其他 Piper 工作流接口一致 |
|
||||
| 成功判定 | 检查 Piper 响应业务码 `code === 200`;HTTP 200 本身不作为成功依据 |
|
||||
| 结果 | 保留服务端消息,并将新开通节点映射到 `saved`、已开通节点映射到 `skipped` |
|
||||
| 凭证 | access token 与 EASO JWT 只用于本机直连请求,不写入日志或返回结果 |
|
||||
@@ -1,6 +1,7 @@
|
||||
import { z } from "zod";
|
||||
import ky, { type KyInstance } from "ky";
|
||||
import { EkbApiError } from "../../../../../core/errors.js";
|
||||
import { EkbApiError, EkbError } from "../../../../../core/errors.js";
|
||||
import { fetchEasoJwt, SCRIPT_ENGINE_BASE_URL } from "../../../../../core/http/script-engine-client.js";
|
||||
import { WorkflowDslSchema, WorkflowDslCatalogSchema, StaffSchema, WorkflowEnumItemSchema, type WorkflowEnumItem } from "../../types.js";
|
||||
import { unwrap } from "../response.js";
|
||||
|
||||
@@ -69,71 +70,86 @@ export async function getWorkflowEnumOptions(
|
||||
return unwrap(response, z.array(WorkflowEnumItemSchema));
|
||||
}
|
||||
|
||||
// ── 灰度节点开通网关 ──────────────────────────────────────────────────────────
|
||||
// ── 灰度节点开通 (EASO -> Piper) ─────────────────────────────────────────────
|
||||
|
||||
/** 网关地址环境变量。网关托管在第三方域,实例可能被回收或迁移,必须允许覆盖。 */
|
||||
export const GRAY_GATEWAY_URL_ENV = "HOSE_GRAY_GATEWAY_URL";
|
||||
export const DEFAULT_GRAY_GATEWAY_URL = "https://d9jxeccs5j.sealosgzg.site";
|
||||
export const GRAY_GATEWAY_PATH = "/hose-workflow-node";
|
||||
const WorkflowNodeGrantResponseSchema = z.object({
|
||||
code: z.union([z.number(), z.string()]).optional(),
|
||||
msg: z.string().optional(),
|
||||
data: z.object({
|
||||
saved: z.array(z.string()).optional(),
|
||||
skipped: z.array(z.string()).optional(),
|
||||
}).passthrough().nullable().optional(),
|
||||
}).passthrough();
|
||||
|
||||
/**
|
||||
* 解析网关请求地址:显式参数 > 环境变量 > 内置默认。
|
||||
* 网关默认地址指向第三方托管实例(`.sealosgzg.site`),同类实例曾被回收;
|
||||
* 硬编码且无逃生口会导致 `workflow nodes grant` 全线瘫痪且无从切换。
|
||||
*/
|
||||
export function resolveGrayGatewayUrl(explicit?: string): string {
|
||||
const candidate = (
|
||||
explicit ??
|
||||
process.env[GRAY_GATEWAY_URL_ENV] ??
|
||||
DEFAULT_GRAY_GATEWAY_URL
|
||||
).trim();
|
||||
return `${candidate.replace(/\/+$/, "")}${GRAY_GATEWAY_PATH}`;
|
||||
function normalizeEkbBaseUrl(baseUrl?: string): string {
|
||||
return (baseUrl || "https://app.ekuaibao.com").trim().replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* 判定网关是否真的开通成功。缺字段不默认为成功:开通未生效会让下游
|
||||
* `analyze` 依旧报 PERMISSION_MISSING_NODE,谎报成功比如实报错更难排查。
|
||||
*/
|
||||
export function interpretGatewayOutcome(json: any): boolean {
|
||||
if (typeof json?.success === "boolean") return json.success;
|
||||
if (json?.code !== undefined && json?.code !== null) return Number(json.code) === 200;
|
||||
// 缺少明确成功/失败标记时不默认成功:开通未生效会让下游 analyze 依旧报
|
||||
// PERMISSION_MISSING_NODE,谎报成功比如实报错更难排查。
|
||||
return false;
|
||||
function parseNodeNames(message: string): string[] {
|
||||
const match = message.match(/(?:新开通的节点|以下节点已开通[^::]*|已开通[^::]*节点)[::]\s*(.+)$/);
|
||||
return match?.[1]
|
||||
.split(/[,,、\s]+/)
|
||||
.map((node) => node.trim())
|
||||
.filter(Boolean) ?? [];
|
||||
}
|
||||
|
||||
export async function grantWorkflowNodesApi(options: {
|
||||
token: string;
|
||||
corpId: string;
|
||||
staffId: string;
|
||||
nodes: string[];
|
||||
/** 目标合思租户地址,网关据此定位要开通的企业。 */
|
||||
/** 目标企业合思地址,用于 EASO JWT 换票。 */
|
||||
baseUrl?: string;
|
||||
/** 网关自身地址;缺省依次使用环境变量 HOSE_GRAY_GATEWAY_URL 与内置默认地址。 */
|
||||
gatewayUrl?: string;
|
||||
}): Promise<import("../../types.js").GrantWorkflowNodesResult> {
|
||||
const baseUrl = normalizeEkbBaseUrl(options.baseUrl);
|
||||
let easoJwt: string;
|
||||
try {
|
||||
easoJwt = await fetchEasoJwt(
|
||||
options.token,
|
||||
options.corpId,
|
||||
options.staffId,
|
||||
baseUrl,
|
||||
);
|
||||
} catch (err: any) {
|
||||
if (err instanceof EkbError) throw err;
|
||||
throw new EkbApiError(
|
||||
`灰度节点开通 EASO 换票失败: ${err?.message || String(err)}`,
|
||||
"EASO_ERROR",
|
||||
502,
|
||||
);
|
||||
}
|
||||
const payload = {
|
||||
token: options.token,
|
||||
corpId: options.corpId,
|
||||
nodes: options.nodes.join(","),
|
||||
...(options.baseUrl ? { baseUrl: options.baseUrl } : {}),
|
||||
corporationId: options.corpId,
|
||||
dslTypes: options.nodes,
|
||||
"recalculate-the-approval-flow": true,
|
||||
"ui-notification": true,
|
||||
start: 0,
|
||||
};
|
||||
const gatewayUrl = resolveGrayGatewayUrl(options.gatewayUrl);
|
||||
|
||||
try {
|
||||
const response = await ky.post(gatewayUrl, {
|
||||
const response = await ky.post(`${SCRIPT_ENGINE_BASE_URL}/api/easo/dsl/corporation`, {
|
||||
json: payload,
|
||||
timeout: 30000,
|
||||
headers: { Authorization: `Bearer ${easoJwt}` },
|
||||
timeout: 15000,
|
||||
});
|
||||
const json = (await response.json()) as any;
|
||||
const innerData = json?.data?.data ?? json?.data ?? {};
|
||||
const json = WorkflowNodeGrantResponseSchema.parse(await response.json());
|
||||
const rawMessage = json.msg || "";
|
||||
const saved = json.data?.saved ?? (Number(json.code) === 200 && rawMessage.includes("新开通")
|
||||
? parseNodeNames(rawMessage)
|
||||
: []);
|
||||
const skipped = json.data?.skipped ?? (Number(json.code) === 200 && rawMessage.includes("已开通") && !rawMessage.includes("新开通")
|
||||
? parseNodeNames(rawMessage)
|
||||
: []);
|
||||
|
||||
return {
|
||||
success: interpretGatewayOutcome(json),
|
||||
saved: Array.isArray(innerData.saved) ? innerData.saved : [],
|
||||
skipped: Array.isArray(innerData.skipped) ? innerData.skipped : [],
|
||||
rawMessage: json?.data?.msg || json?.msg || json?.message || "",
|
||||
success: Number(json.code) === 200,
|
||||
saved,
|
||||
skipped,
|
||||
rawMessage,
|
||||
};
|
||||
} catch (err: any) {
|
||||
const message = err?.message || String(err);
|
||||
throw new EkbApiError(`灰度节点开通网关调用失败 (${gatewayUrl}): ${message}`, "GATEWAY_ERROR", 502);
|
||||
if (err instanceof EkbError) throw err;
|
||||
throw new EkbApiError(`灰度节点开通 Piper 请求失败: ${message}`, "PIPER_ERROR", 502);
|
||||
}
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
import { afterEach, describe, expect, it, spyOn } from "bun:test";
|
||||
import ky from "ky";
|
||||
|
||||
/**
|
||||
* 灰度开通网关的行为测试。网关地址托管在第三方域,且历史实例曾被回收,
|
||||
* 必须保证「地址可覆盖」与「成功判定不默认为真」这两件事被固化下来。
|
||||
*
|
||||
* 这里刻意只用纯函数断言 + 对 ky.post 的可恢复 spy:
|
||||
* `mock.module("ky")` 会污染同进程其他用例的 ky 引用。
|
||||
*/
|
||||
const {
|
||||
grantWorkflowNodesApi,
|
||||
resolveGrayGatewayUrl,
|
||||
interpretGatewayOutcome,
|
||||
GRAY_GATEWAY_URL_ENV,
|
||||
DEFAULT_GRAY_GATEWAY_URL,
|
||||
GRAY_GATEWAY_PATH,
|
||||
} = await import("./catalog/api.js");
|
||||
|
||||
const ORIGINAL_ENV = process.env[GRAY_GATEWAY_URL_ENV];
|
||||
|
||||
function restoreEnv(): void {
|
||||
if (ORIGINAL_ENV === undefined) delete process.env[GRAY_GATEWAY_URL_ENV];
|
||||
else process.env[GRAY_GATEWAY_URL_ENV] = ORIGINAL_ENV;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
restoreEnv();
|
||||
});
|
||||
|
||||
describe("gray gateway address resolution", () => {
|
||||
it("falls back to the built-in default host", () => {
|
||||
delete process.env[GRAY_GATEWAY_URL_ENV];
|
||||
expect(resolveGrayGatewayUrl()).toBe(`${DEFAULT_GRAY_GATEWAY_URL}${GRAY_GATEWAY_PATH}`);
|
||||
});
|
||||
|
||||
it("prefers the environment override and normalizes trailing slashes", () => {
|
||||
process.env[GRAY_GATEWAY_URL_ENV] = "https://gw.example.com///";
|
||||
expect(resolveGrayGatewayUrl()).toBe(`https://gw.example.com${GRAY_GATEWAY_PATH}`);
|
||||
});
|
||||
|
||||
it("lets the explicit argument win over the environment", () => {
|
||||
process.env[GRAY_GATEWAY_URL_ENV] = "https://ignored.example.com";
|
||||
expect(resolveGrayGatewayUrl("https://explicit.example.com")).toBe(
|
||||
`https://explicit.example.com${GRAY_GATEWAY_PATH}`
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("gray gateway outcome interpretation", () => {
|
||||
it("honours an explicit success flag", () => {
|
||||
expect(interpretGatewayOutcome({ success: true })).toBe(true);
|
||||
expect(interpretGatewayOutcome({ success: false })).toBe(false);
|
||||
});
|
||||
|
||||
it("treats a non-200 business code as failure", () => {
|
||||
expect(interpretGatewayOutcome({ code: 200 })).toBe(true);
|
||||
expect(interpretGatewayOutcome({ code: 500 })).toBe(false);
|
||||
});
|
||||
|
||||
it("does not assume success when the gateway omits any verdict", () => {
|
||||
expect(interpretGatewayOutcome({ msg: "ok" })).toBe(false);
|
||||
expect(interpretGatewayOutcome({})).toBe(false);
|
||||
expect(interpretGatewayOutcome(null)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("grantWorkflowNodesApi request contract", () => {
|
||||
it("posts to the resolved gateway and keeps tenant baseUrl in the payload", async () => {
|
||||
let requestedUrl = "";
|
||||
let payload: Record<string, unknown> = {};
|
||||
spyOn(ky, "post").mockImplementation((async (url: string, options: any) => {
|
||||
requestedUrl = String(url);
|
||||
payload = options?.json ?? {};
|
||||
return { ok: true, status: 200, json: async () => ({ success: true, data: { saved: ["code-js2"], skipped: [] } }) };
|
||||
}) as never);
|
||||
|
||||
const result = await grantWorkflowNodesApi({
|
||||
token: "tok",
|
||||
corpId: "corp-1",
|
||||
nodes: ["code-js2"],
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
});
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.saved).toEqual(["code-js2"]);
|
||||
expect(requestedUrl).toContain("/hose-workflow-node");
|
||||
expect(payload.corpId).toBe("corp-1");
|
||||
expect(payload.baseUrl).toBe("https://app.ekuaibao.com");
|
||||
});
|
||||
|
||||
it("includes the gateway url in transport failures", async () => {
|
||||
process.env[GRAY_GATEWAY_URL_ENV] = "https://gw.example.com";
|
||||
spyOn(ky, "post").mockImplementation((async () => {
|
||||
throw new Error("connect ETIMEDOUT");
|
||||
}) as never);
|
||||
|
||||
await expect(
|
||||
grantWorkflowNodesApi({ token: "tok", corpId: "corp-1", nodes: ["code-js2"] })
|
||||
).rejects.toThrow(/https:\/\/gw\.example\.com\/hose-workflow-node/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,127 @@
|
||||
import { afterEach, describe, expect, it, spyOn } from "bun:test";
|
||||
import ky from "ky";
|
||||
import { grantWorkflowNodesApi } from "./catalog/api.js";
|
||||
|
||||
describe("grantWorkflowNodesApi direct Piper request", () => {
|
||||
let spies: ReturnType<typeof spyOn>[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const spy of spies) spy.mockRestore();
|
||||
spies = [];
|
||||
});
|
||||
|
||||
function mockJwt(): void {
|
||||
spies.push(spyOn(ky, "get").mockImplementation((() => ({
|
||||
json: async () => ({ id: "business-jwt" }),
|
||||
})) as never));
|
||||
}
|
||||
|
||||
it("exchanges EASO JWT and posts the requested node types to Piper", async () => {
|
||||
mockJwt();
|
||||
let requestedUrl = "";
|
||||
let requestOptions: any;
|
||||
spies.push(spyOn(ky, "post").mockImplementation((async (url: string, options: any) => {
|
||||
requestedUrl = url;
|
||||
requestOptions = options;
|
||||
return {
|
||||
json: async () => ({ code: 200, msg: "新开通的节点:recalculate-the-approval-flow" }),
|
||||
};
|
||||
}) as never));
|
||||
|
||||
const result = await grantWorkflowNodesApi({
|
||||
token: "access-token",
|
||||
corpId: "corp-1",
|
||||
staffId: "corp-1:staff-1",
|
||||
nodes: ["recalculate-the-approval-flow"],
|
||||
baseUrl: "https://app.ekuaibao.com///",
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
success: true,
|
||||
saved: ["recalculate-the-approval-flow"],
|
||||
skipped: [],
|
||||
rawMessage: "新开通的节点:recalculate-the-approval-flow",
|
||||
});
|
||||
expect(ky.get).toHaveBeenCalledWith(
|
||||
"https://app.ekuaibao.com/api/engine/realm/$EASO/actions/jwt",
|
||||
expect.objectContaining({
|
||||
searchParams: { corpId: "corp-1" },
|
||||
headers: expect.objectContaining({
|
||||
accesstoken: "access-token",
|
||||
corpid: "corp-1",
|
||||
staffid: "corp-1:staff-1",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(requestedUrl).toBe("https://piper.ekuaibao.com/api/easo/dsl/corporation");
|
||||
expect(requestOptions.headers).toEqual({ Authorization: "Bearer business-jwt" });
|
||||
expect(requestOptions.json).toEqual({
|
||||
corporationId: "corp-1",
|
||||
dslTypes: ["recalculate-the-approval-flow"],
|
||||
"recalculate-the-approval-flow": true,
|
||||
"ui-notification": true,
|
||||
start: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("reports already-open nodes as skipped", async () => {
|
||||
mockJwt();
|
||||
spies.push(spyOn(ky, "post").mockImplementation((async () => ({
|
||||
json: async () => ({ code: 200, msg: "以下节点已开通,不再重复开通:code" }),
|
||||
})) as never));
|
||||
|
||||
const result = await grantWorkflowNodesApi({
|
||||
token: "access-token",
|
||||
corpId: "corp-1",
|
||||
staffId: "corp-1:staff-1",
|
||||
nodes: ["code"],
|
||||
});
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.saved).toEqual([]);
|
||||
expect(result.skipped).toEqual(["code"]);
|
||||
});
|
||||
|
||||
it("does not treat an HTTP 200 with a failing business code as success", async () => {
|
||||
mockJwt();
|
||||
spies.push(spyOn(ky, "post").mockImplementation((async () => ({
|
||||
json: async () => ({ code: 500, msg: "JWT 签名无效" }),
|
||||
})) as never));
|
||||
|
||||
const result = await grantWorkflowNodesApi({
|
||||
token: "access-token",
|
||||
corpId: "corp-1",
|
||||
staffId: "corp-1:staff-1",
|
||||
nodes: ["code"],
|
||||
});
|
||||
|
||||
expect(result).toEqual({ success: false, saved: [], skipped: [], rawMessage: "JWT 签名无效" });
|
||||
});
|
||||
|
||||
it("maps EASO exchange transport failures to a domain API error", async () => {
|
||||
spies.push(spyOn(ky, "get").mockImplementation((() => {
|
||||
throw new Error("Request failed with status code 404");
|
||||
}) as never));
|
||||
|
||||
await expect(grantWorkflowNodesApi({
|
||||
token: "access-token",
|
||||
corpId: "corp-1",
|
||||
staffId: "corp-1:staff-1",
|
||||
nodes: ["code"],
|
||||
})).rejects.toThrow("灰度节点开通 EASO 换票失败: Request failed with status code 404");
|
||||
});
|
||||
|
||||
it("surfaces Piper transport failures without exposing credentials", async () => {
|
||||
mockJwt();
|
||||
spies.push(spyOn(ky, "post").mockImplementation((async () => {
|
||||
throw new Error("connect ETIMEDOUT");
|
||||
}) as never));
|
||||
|
||||
await expect(grantWorkflowNodesApi({
|
||||
token: "secret-access-token",
|
||||
corpId: "corp-1",
|
||||
staffId: "corp-1:staff-1",
|
||||
nodes: ["code"],
|
||||
})).rejects.toThrow("灰度节点开通 Piper 请求失败: connect ETIMEDOUT");
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user