Merge pull request #135 from yunyingk/fix/v0.8.17-review-fixes
CI / validate (push) Has been cancelled

Fix v0.8.17 assist and workflow review issues
This commit is contained in:
yunyingk authored and GitHub committed 2026-10-21 16:17:32 +08:00
commit 36a4d3b27b
19 files changed
+1275 -572

No files matched your search

+460 -459
View File
File diff suppressed because it is too large. Load diff
+260
View File
@@ -0,0 +1,260 @@
import { afterEach, beforeEach, describe, expect, it, spyOn } from "bun:test";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import ky from "ky";
import { saveAssistPlatformSession } from "../core/auth/assist-platform-store.js";
import { saveCorpConfig } from "../core/config/loader.js";
import { CorpContext } from "../core/config/manager.js";
import { BusinessError } from "../core/errors.js";
import { importAssistSessionToLocal, inspectAssistIdentity } from "../domains/assist-platform/services.js";
import { runCli } from "./runner.js";
const envKeys = ["HOSE_STATE_DIR", "HOSE_ASSIST_PLATFORM_FILE", "HOSE_CONFIG_FILE", "HOSE_ENTERPRISES_DIR"] as const;
const token = "fixture-session-token";
const loginUrl = `https://session.example/web/thirdparty.html?accessToken=${token}&ekbCorpId=NEW`;
const baseUrl = "https://session.example";
describe("assist session lifecycle regressions", () => {
let root: string;
let corps: string;
let originalEnv: Array<string | undefined>;
let originalFetch: typeof fetch;
let requests: string[];
let handleRequest: (req: Request) => Response | Promise<Response>;
let staffAvailable: boolean;
let rolesAvailable: boolean;
let jwtAdmin: boolean | undefined;
let keysResponse: () => Response;
let logCredentials: boolean;
beforeEach(() => {
root = mkdtempSync(join(tmpdir(), "hose-assist-session-"));
corps = join(root, "corps");
mkdirSync(corps);
originalEnv = envKeys.map((key) => process.env[key]);
process.env.HOSE_STATE_DIR = root;
process.env.HOSE_ASSIST_PLATFORM_FILE = join(root, "assist.json");
process.env.HOSE_CONFIG_FILE = join(root, "config.json");
process.env.HOSE_ENTERPRISES_DIR = corps;
saveAssistPlatformSession({ token: "fixture-platform-token", baseUrl: "https://assist.example/api", updatedAt: Date.now() });
requests = [];
staffAvailable = true;
rolesAvailable = true;
jwtAdmin = false;
logCredentials = false;
keysResponse = () => Response.json({ items: [] });
handleRequest = async (req) => {
const url = req.url;
if (url.includes("assistPlatform/getToken")) {
if (logCredentials) {
console.log(`diagnostic ${loginUrl}`);
console.error(`diagnostic ${loginUrl}`);
}
return Response.json({ value: { token, loginUrl, baseUrl } });
}
if (url.includes("organization/staffs/me")) {
return staffAvailable
? Response.json({ value: { staff: { id: "NEW:staff", name: "员工", admin: false }, permissions: [] } })
: new Response("Forbidden", { status: 403 });
}
if (url.includes("/roles")) {
return rolesAvailable ? Response.json({ items: [] }) : new Response("Forbidden", { status: 403 });
}
if (url.includes("actions/jwt")) {
const payload = Buffer.from(JSON.stringify({ staffId: "NEW:staff", staffName: "JWT员工", isAdmin: jwtAdmin, corporationName: "新企业" })).toString("base64url");
return Response.json({ id: `fixture.${payload}.signature` });
}
if (url.includes("/account/v2/session")) {
return Response.json({ value: { id: "session", corporationId: "NEW", loginStaffId: "NEW:staff", platform: "ASSIST" } });
}
if (url.includes("/innerapi/v1/key")) return keysResponse();
throw new Error(`Unexpected mocked request: ${url}`);
};
originalFetch = globalThis.fetch;
globalThis.fetch = (async (input: string | Request | URL, init?: RequestInit) => {
const req = input instanceof Request ? input : new Request(input.toString(), init);
requests.push(req.url);
return handleRequest(req);
}) as typeof fetch;
});
afterEach(() => {
globalThis.fetch = originalFetch;
envKeys.forEach((key, index) => {
if (originalEnv[index] === undefined) delete process.env[key];
else process.env[key] = originalEnv[index];
});
rmSync(root, { recursive: true, force: true });
});
const enterArgs = ["assist-platform", "enter", "NEW", "--ticket", "T"];
const importSession = (options: { elevate?: boolean } = {}) => importAssistSessionToLocal(
ky.create({ prefix: "https://assist.example/api" }),
{ corpId: "NEW", ticketId: "T", enterprisesDir: corps, ...options }
);
it("dry-run previews every enter branch without authentication, requests or persistence", async () => {
rmSync(process.env.HOSE_ASSIST_PLATFORM_FILE!);
for (const extra of [[], ["--save"], ["--switch"], ["--save", "--switch", "--yes"]]) {
for (const json of [[], ["--json"]]) {
const result = await runCli([...enterArgs, ...extra, "--dry-run", ...json]);
expect(result.exitCode).toBe(0);
expect(json.length ? JSON.parse(result.stdout).dryRun : result.stdout.includes("[DRY-RUN]")).toBe(true);
}
}
expect(requests).toHaveLength(0);
expect(existsSync(join(corps, "NEW.json"))).toBe(false);
expect(existsSync(process.env.HOSE_CONFIG_FILE!)).toBe(false);
});
it("runCli preserves delivered login URLs in text and JSON while redacting captured diagnostics", async () => {
logCredentials = true;
for (const extra of [[], ["--json"]]) {
const result = await runCli([...enterArgs, ...extra]);
expect(result.exitCode).toBe(0);
expect(result.preserveSensitiveStdout).toBe(true);
expect(result.stdout).toContain(loginUrl);
expect(result.stderr).not.toContain(token);
expect(result.stderr).toContain("accessToken=<redacted>");
if (extra.length) expect(JSON.parse(result.stdout).loginUrl).toBe(loginUrl);
else expect(result.stdout).toContain("diagnostic https://session.example/web/thirdparty.html?accessToken=<redacted>");
}
});
it("registers a newly imported enterprise before switching and persists its default", async () => {
const result = await runCli([...enterArgs, "--save", "--switch", "--yes", "--json"]);
expect(result.exitCode).toBe(0);
expect(JSON.parse(result.stdout).enterprise.switched).toBe(true);
expect(JSON.parse(result.stdout).sessionResult.loginUrl).toBe(loginUrl);
expect(JSON.parse(readFileSync(process.env.HOSE_CONFIG_FILE!, "utf8")).defaultCorpId).toBe("NEW");
expect(existsSync(join(corps, "NEW.json"))).toBe(true);
});
it("reports a failed switch without claiming success after saving the enterprise", async () => {
const switchMock = spyOn(CorpContext.prototype, "switchCorp").mockReturnValue(false);
try {
const result = await runCli([...enterArgs, "--save", "--switch", "--yes", "--json"]);
expect(result.exitCode).not.toBe(0);
expect(JSON.parse(result.stdout).message).toContain("配置已保存,但切换当前工作企业失败");
expect(result.stdout).not.toContain('"switched": true');
expect(existsSync(join(corps, "NEW.json"))).toBe(true);
} finally { switchMock.mockRestore(); }
});
it("keeps error output redacted in text and JSON", async () => {
handleRequest = () => { throw new BusinessError(`换票失败 ${loginUrl}`); };
for (const extra of [[], ["--json"]]) {
const result = await runCli([...enterArgs, ...extra]);
expect(result.exitCode).not.toBe(0);
expect(result.preserveSensitiveStdout).not.toBe(true);
expect(result.stdout + result.stderr).not.toContain(token);
expect(result.stdout + result.stderr).toContain("accessToken=<redacted>");
}
});
it("saves a valid temporary session without keys or key permission and tolerates multiple keys", async () => {
for (const response of [
() => Response.json({ items: [] }),
() => new Response("Forbidden", { status: 403 }),
() => Response.json({ items: [{ appKey: "a", appSecurity: "fixture-a" }, { appKey: "b", appSecurity: "fixture-b" }] }),
]) {
keysResponse = response;
const { corpConfig } = await importSession();
expect(corpConfig.credentials.accessToken).toBe(token);
expect(existsSync(join(corps, "NEW.json"))).toBe(true);
}
requests = [];
await importSession({ elevate: false });
expect(requests.some((url) => url.includes("/innerapi/v1/key"))).toBe(false);
});
it("marks failed or partial identity probes unknown instead of falsely reporting normal risk", async () => {
staffAvailable = false;
let identity = await inspectAssistIdentity(token, "NEW", baseUrl);
expect(identity.isAdmin).toBeNull();
expect(identity.isSeniorExecutive).toBeNull();
expect(identity.riskLevel).toBe("UNKNOWN");
expect(identity.profileComplete).toBe(false);
expect(identity.unavailableFields).toContain("staff");
staffAvailable = true;
rolesAvailable = false;
identity = await inspectAssistIdentity(token, "NEW", baseUrl);
expect(identity.isAdmin).toBe(false);
expect(identity.riskLevel).toBe("UNKNOWN");
expect(identity.unavailableFields).toContain("roles");
rolesAvailable = true;
identity = await inspectAssistIdentity(token, "NEW", baseUrl);
expect(identity.riskLevel).toBe("NORMAL");
expect(identity.profileComplete).toBe(true);
});
it("preserves a known JWT admin and records incomplete profile metadata on disk", async () => {
staffAvailable = false;
jwtAdmin = true;
const { corpConfig, sessionResult } = await importSession();
expect(corpConfig.session?.isAdmin).toBe(true);
expect(corpConfig.session?.riskLevel).toBe("HIGH");
expect(corpConfig.session?.staffName).toBe("JWT员工");
expect(sessionResult.identity?.riskLevel).toBe("HIGH");
const persisted = JSON.parse(readFileSync(join(corps, "NEW.json"), "utf8"));
expect(persisted.session.identityComplete).toBe(false);
expect(persisted.session.identityUnavailableFields).toContain("staff");
expect(persisted.session.isAdmin).toBe(true);
});
it("does not reuse a different employee's administrator or risk profile", async () => {
saveCorpConfig({ id: "NEW", name: "旧企业", baseUrl, source: "assist", credentials: { corpId: "NEW", staffId: "NEW:other", accessToken: "old-fixture" }, session: { permissions: ["SYS_ADMIN"], isAdmin: true, riskLevel: "HIGH" } }, corps);
staffAvailable = false;
jwtAdmin = undefined;
const { corpConfig } = await importSession();
expect(corpConfig.session?.isAdmin).toBeUndefined();
expect(corpConfig.session?.permissions).toEqual([]);
expect(corpConfig.session?.riskLevel).toBe("UNKNOWN");
});
it("does not treat malformed permissions or roles as an empty complete profile", async () => {
handleRequest = (req) => req.url.includes("/staffs/me")
? Response.json({ value: { staff: { id: "NEW:staff", admin: false }, permissions: [{}] } })
: Response.json({ items: [{}] });
const identity = await inspectAssistIdentity(token, "NEW", baseUrl);
expect(identity.profileComplete).toBe(false);
expect(identity.unavailableFields).toContain("permissions");
expect(identity.unavailableFields).toContain("roles");
expect(identity.riskLevel).toBe("UNKNOWN");
});
it("retains known permissions for the same staff when a later probe is incomplete", async () => {
saveCorpConfig({ id: "NEW", name: "旧企业", baseUrl, source: "assist", credentials: { corpId: "NEW", staffId: "NEW:staff", accessToken: "old-fixture" }, session: { permissions: ["SYS_ADMIN"], isAdmin: true, riskLevel: "HIGH" } }, corps);
staffAvailable = false;
jwtAdmin = undefined;
const { corpConfig } = await importSession();
expect(corpConfig.session?.isAdmin).toBe(true);
expect(corpConfig.session?.permissions).toContain("SYS_ADMIN");
expect(corpConfig.session?.riskLevel).toBe("HIGH");
});
it("merges known partial roles with the same staff's previous roles before risk analysis", async () => {
saveCorpConfig({
id: "NEW",
name: "旧企业",
baseUrl,
source: "assist",
credentials: { corpId: "NEW", staffId: "NEW:staff", accessToken: "old-fixture" },
session: { roles: ["普通员工"], riskLevel: "NORMAL" },
}, corps);
const originalHandler = handleRequest;
handleRequest = (req) => req.url.includes("/roles")
? Response.json({ items: [{ roleDefName: "财务总监" }, {}] })
: originalHandler(req);
const { corpConfig, sessionResult } = await importSession();
expect(sessionResult.identity?.roleNames).toEqual(["财务总监", "普通员工"]);
expect(sessionResult.identity?.seniorTitles).toContain("财务总监");
expect(sessionResult.identity?.riskLevel).toBe("HIGH");
expect(corpConfig.session?.roles).toEqual(["财务总监", "普通员工"]);
expect(corpConfig.session?.roleTitles).toContain("财务总监");
expect(corpConfig.session?.riskLevel).toBe("HIGH");
});
});
+16 -4
View File
@@ -255,9 +255,21 @@ describe("CLI Commands - assist-platform (合思协助平台)", () => {
raw: ["assist-platform", "transfer", "ID01ofWoOC1wiX", "ID01Xenwiu9w0D", "--to", "陈龙", "--dry-run"],
};
const res = await handleAssistPlatformCommand(parsed, runtime);
expect(res.stdout).toContain("[DRY-RUN]");
expect(res.stdout).toContain("ID01Xenwiu9w0D");
expect(res.stdout).toContain("陈龙");
const originalFetch = globalThis.fetch;
globalThis.fetch = (async () => Response.json({
items: [{
id: "role-chenlong",
userId: { id: "chenlong3016", name: "陈龙", code: "3016" },
}],
})) as unknown as typeof globalThis.fetch;
try {
const res = await handleAssistPlatformCommand(parsed, runtime);
expect(res.stdout).toContain("[DRY-RUN]");
expect(res.stdout).toContain("ID01Xenwiu9w0D");
expect(res.stdout).toContain("陈龙");
expect(res.stdout).toContain("chenlong3016");
} finally {
globalThis.fetch = originalFetch;
}
});
});
+26 -12
View File
@@ -13,10 +13,8 @@ export async function handleApprove(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const explicitCorpId =
stringOption(parsed.options, ["corp", "corpid", "id"]) ||
parsed.args[0] ||
runtime.selectedCorp?.id;
const corpOption = stringOption(parsed.options, ["corp", "corpid", "id"]);
const explicitCorpId = corpOption || parsed.args[0] || runtime.selectedCorp?.id;
if (!explicitCorpId) {
return {
@@ -31,22 +29,38 @@ export async function handleApprove(
// 1. 识别 corpId 与 ticketId
const allCorps = runtime.corpContext?.getAllCorps?.() || [];
let targetCorp =
allCorps.find((c) => c.id === explicitCorpId || c.corpId === explicitCorpId) ||
(runtime.selectedCorp?.id === explicitCorpId || runtime.selectedCorp?.corpId === explicitCorpId
const findCorp = (id: string) =>
allCorps.find((c) => c.id === id || c.corpId === id) ||
(runtime.selectedCorp?.id === id || runtime.selectedCorp?.corpId === id
? runtime.selectedCorp
: undefined);
let ticketId = stringOption(parsed.options, ["ticket", "ticket-id"]);
let targetCorp = findCorp(explicitCorpId);
const ticketOption = stringOption(parsed.options, ["ticket", "ticket-id"]);
let positionalTicketId: string | undefined;
// 如果第 0 个参数不是企业,可能是工单编号
if (!targetCorp && parsed.args[0]) {
ticketId = parsed.args[0];
if (corpOption) {
// 显式企业选项下,唯一位置参数始终是工单,不能被本地企业命中结果覆盖。
positionalTicketId = parsed.args[0];
} else if (!targetCorp && parsed.args[0]) {
positionalTicketId = parsed.args[0];
targetCorp = runtime.selectedCorp ?? undefined;
} else if (targetCorp && parsed.args[1]) {
ticketId = parsed.args[1];
positionalTicketId = parsed.args[1];
}
const maxArgs = !corpOption && parsed.args[0] && findCorp(parsed.args[0]) ? 2 : 1;
if (parsed.args.length > maxArgs ||
(ticketOption && positionalTicketId && ticketOption !== positionalTicketId)) {
return {
stdout: "",
stderr: "[ERROR] 企业或工单参数存在歧义或冲突。请使用 approve <工单ID> --corp <企业ID>,且 --ticket 必须与位置工单一致。\n",
exitCode: 1,
};
}
let ticketId = ticketOption || positionalTicketId;
if (!targetCorp) {
return {
stdout: "",
+38 -22
View File
@@ -1,3 +1,4 @@
import { BusinessError } from "../../../core/errors.js";
import {
generateAssistSession,
importAssistSessionToLocal,
@@ -29,6 +30,10 @@ function formatIdentityLines(ident?: AssistIdentityProfile): {
profilePairs["核心系统权限"] = `${permSummary}${ident.readablePermissions.length > 5 ? ` 等共 ${ident.readablePermissions.length} 项` : ""}`;
}
if (ident.profileComplete === false) {
profilePairs["身份画像状态"] = "信息不完整,无法排除更高权限风险";
}
if (ident.isSeniorExecutive && ident.riskWarning) {
const titles = ident.seniorTitles.length > 0 ? ident.seniorTitles.join(" / ") : "高级管理人员";
warningText =
@@ -47,7 +52,6 @@ export async function handleEnter(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const client = resolveAssistClient(parsed, runtime);
const corpId =
parsed.args[0] ||
stringOption(parsed.options, ["corp", "corpid", "id"]) ||
@@ -72,6 +76,28 @@ export async function handleEnter(
const overwrite = booleanOption(parsed.options, ["overwrite"]);
const saveName = stringOption(parsed.options, ["alias", "corp-name"]);
if (isDryRun(parsed, runtime)) {
return mutationPreview(
parsed,
runtime,
shouldSave || shouldSwitch
? "从协助平台换取免密凭证并落盘为本地企业配置"
: "从协助平台换取免密凭证并生成直通链接",
saveName || `企业 [${corpId}]`,
{
corpId,
isAdmin,
staffName: staffName || null,
ticketId: ticketId || "自动选择最新有效工单",
save: shouldSave || shouldSwitch,
switchCurrent: shouldSwitch,
overwrite,
}
);
}
const client = resolveAssistClient(parsed, runtime);
// 1. 若不要求保存落盘,仅生成直通免密链接输出
if (!shouldSave && !shouldSwitch) {
const sessionRes = await generateAssistSession(client, {
@@ -84,6 +110,7 @@ export async function handleEnter(
if (runtime.jsonMode) {
return {
stdout: printJson(sessionRes, runtime.outputOptions),
preserveSensitiveStdout: true,
stderr: "",
exitCode: 0,
};
@@ -101,6 +128,7 @@ export async function handleEnter(
Object.assign(pairs, profilePairs);
return {
preserveSensitiveStdout: true,
stdout:
`====== 协助平台免密会话生成成功 ======\n${printKeyValue(pairs)}\n` +
`${warningText}\n操作提示:\n` +
@@ -112,23 +140,6 @@ export async function handleEnter(
}
// 2. 要求持久化落盘 / 切换为工作企业
if (isDryRun(parsed, runtime)) {
return mutationPreview(
parsed,
runtime,
"从协助平台换取免密凭证并落盘为本地企业配置",
saveName || `企业 [${corpId}]`,
{
corpId,
isAdmin,
staffName: staffName || null,
ticketId: ticketId || "自动选择最新有效工单",
switchCurrent: shouldSwitch,
overwrite,
}
);
}
const nextConfirmCmd = `hose-use assist-platform enter ${corpId} ${isAdmin ? "--admin" : `--staff "${staffName}"`} --save ${shouldSwitch ? "--switch " : ""}--yes`;
requireMutationConfirmation(
parsed,
@@ -146,13 +157,18 @@ export async function handleEnter(
overwrite: overwrite ?? true,
});
// 导入文件后同步注册到当前运行态,确保新企业可立即切换
runtime.corpContext.upsertCorp(corpConfig);
// 若指定了 --switch,切换当前激活企业
if (shouldSwitch) {
runtime.corpContext.switchCorp(corpConfig.id, true);
const switched = shouldSwitch && runtime.corpContext.switchCorp(corpConfig.id, true);
if (shouldSwitch && !switched) {
throw new BusinessError(`企业 [${corpConfig.id}] 配置已保存,但切换当前工作企业失败,请运行 hose-use corps switch ${corpConfig.id} 重试`);
}
if (runtime.jsonMode) {
return {
preserveSensitiveStdout: true,
stdout: printJson({
success: true,
sessionResult,
@@ -161,7 +177,7 @@ export async function handleEnter(
name: corpConfig.name,
staffId: corpConfig.credentials.staffId,
hasOpenApi: Boolean(corpConfig.credentials.appKey),
switched: shouldSwitch,
switched,
},
}, runtime.outputOptions),
stderr: "",
@@ -176,7 +192,7 @@ export async function handleEnter(
授权工单: sessionResult.ticketId,
凭证状态: corpConfig.credentials.appKey ? `✅ 已提取 OpenAPI 持久化密钥 (${corpConfig.credentials.appKey})` : "⚪ 临时协助会话",
配置文件: `enterprises/${corpConfig.id}.json`,
激活状态: shouldSwitch ? "🎯 已设为当前激活工作企业" : "可随时运行 hose-use corps switch 进行切换",
激活状态: switched ? "🎯 已设为当前激活工作企业" : "可随时运行 hose-use corps switch 进行切换",
};
const { profilePairs, warningText } = formatIdentityLines(sessionResult.identity);
+6 -15
View File
@@ -86,20 +86,11 @@ export async function handleTransfer(
try {
resolvedRecipient = await resolveTransferRecipient(client, targetRecipient);
} catch (err) {
if (isDryRun(parsed, runtime)) {
resolvedRecipient = {
id: targetRecipient,
name: targetRecipient,
userRoleId: "",
roles: [],
};
} else {
return {
stdout: "",
stderr: `[ERROR] ${err instanceof Error ? err.message : String(err)}\n`,
exitCode: 1,
};
}
return {
stdout: "",
stderr: `[ERROR] ${err instanceof Error ? err.message : String(err)}\n`,
exitCode: 1,
};
}
if (!ticketId) {
@@ -136,7 +127,7 @@ export async function handleTransfer(
parsed,
runtime,
operation,
`hose-use assist-platform transfer ${targetCorpId} ${ticketId} --to "${resolvedRecipient.name}" --yes`
`hose-use assist-platform transfer ${targetCorpId} ${ticketId} --to "${resolvedRecipient.id}" --yes`
);
const result = await transferAssistTicket(client, {
+161
View File
@@ -0,0 +1,161 @@
import { afterEach, beforeEach, describe, expect, it } from "bun:test";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { CorpConfig } from "../../core/config/types.js";
import { parseArgs } from "../parser.js";
import type { CliRuntime } from "../types.js";
import { handleApprove } from "./assist-platform/approve.js";
import { handleTransfer } from "./assist-platform/transfer.js";
const corp: CorpConfig = {
id: "CORP", corpId: "CORP", name: "测试企业", source: "manual",
baseUrl: "https://corp.invalid",
credentials: { accessToken: "mock-token", corpId: "CORP", staffId: "ADMIN" },
};
const otherCorp: CorpConfig = { ...corp, id: "OTHER-CORP", corpId: "OTHER-CORP" };
const sameNameUsers = [
{ id: "ROLE1", userId: { id: "user3016", name: "张三", code: "3016" } },
{ id: "ROLE2", userId: { id: "user3020", name: "张三", code: "3020" } },
];
function runtime(selectedCorp: CorpConfig | null = corp): CliRuntime {
return {
jsonMode: true, selectedCorp,
corpContext: { getAllCorps: () => [corp, otherCorp] } as CliRuntime["corpContext"],
};
}
let originalFetch: typeof globalThis.fetch;
let originalStore: string | undefined;
let stateDir: string;
let requests: Request[];
let responses: (request: Request) => Response | Promise<Response>;
beforeEach(() => {
originalFetch = globalThis.fetch;
originalStore = process.env.HOSE_ASSIST_PLATFORM_FILE;
stateDir = mkdtempSync(join(tmpdir(), "hose-assist-targets-"));
process.env.HOSE_ASSIST_PLATFORM_FILE = join(stateDir, "session.json");
requests = [];
responses = () => Response.json({ items: [{ ticketId: "OTHER-TICKET", state: "0" }] });
globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
const request = input instanceof Request ? input : new Request(input.toString(), init);
// Bun 的 Request.clone 声明采用 undici Headers;运行态仍是同一个 Request 类型。
requests.push(request.clone() as unknown as Request);
return responses(request);
}) as typeof globalThis.fetch;
});
afterEach(() => {
globalThis.fetch = originalFetch;
if (originalStore === undefined) delete process.env.HOSE_ASSIST_PLATFORM_FILE;
else process.env.HOSE_ASSIST_PLATFORM_FILE = originalStore;
rmSync(stateDir, { recursive: true, force: true });
});
describe("assist-platform approve 的明确工单目标", () => {
it.each([
["REQUESTED", "--corp", "CORP"],
["CORP", "REQUESTED"],
["CORP", "--ticket", "REQUESTED"],
["--corp", "CORP", "--ticket", "REQUESTED"],
["REQUESTED"],
["--ticket", "REQUESTED"],
["REQUESTED", "--corp", "CORP", "--ticket", "REQUESTED"],
].map((args) => ({ args })))("预览保留工单参数 %j,不自动查询其他工单", async ({ args }) => {
const result = await handleApprove(parseArgs(["assist-platform", "approve", ...args, "--dry-run"]), runtime());
expect(result.exitCode).toBe(0);
expect(JSON.parse(result.stdout).changes["工单编号"]).toBe("REQUESTED");
expect(requests).toHaveLength(0);
});
it("显式 --corp 下首参即使也是已知企业 ID,仍作为工单", async () => {
const parsed = parseArgs(["assist-platform", "approve", "OTHER-CORP", "--corp", "CORP", "--dry-run"]);
const result = await handleApprove(parsed, runtime());
expect(JSON.parse(result.stdout).changes["工单编号"]).toBe("OTHER-CORP");
expect(requests).toHaveLength(0);
});
it("--yes 真实提交路径只审批显式工单,不能自动替换为列表首项", async () => {
responses = (request) => request.method === "PUT"
? Response.json({ value: { id: "REQUESTED", corporationId: "CORP" } })
: Response.json({ items: [{ ticketId: "OTHER-TICKET", state: "0" }] });
const result = await handleApprove(
parseArgs(["assist-platform", "approve", "REQUESTED", "--corp", "CORP", "--yes"]), runtime()
);
expect(result.exitCode).toBe(0);
expect(requests).toHaveLength(1);
expect(requests[0].method).toBe("PUT");
expect(requests[0].url).toContain("/$REQUESTED/updateStatus?corpId=CORP");
expect(await requests[0].json()).toEqual({ id: "REQUESTED", status: 1 });
});
it.each([
["REQUESTED", "--corp", "CORP", "--ticket", "OTHER-TICKET"],
["CORP", "REQUESTED", "--ticket", "OTHER-TICKET"],
["UNKNOWN-CORP", "REQUESTED"],
["CORP", "REQUESTED", "--corp", "OTHER-CORP"],
["CORP", "REQUESTED", "EXTRA"],
].map((args) => ({ args })))("拒绝歧义或冲突参数 %j,且不查询或提交", async ({ args }) => {
const result = await handleApprove(parseArgs(["assist-platform", "approve", ...args, "--yes"]), runtime());
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain("歧义或冲突");
expect(requests).toHaveLength(0);
});
it("显式企业未知时不能回退当前企业", async () => {
const result = await handleApprove(
parseArgs(["assist-platform", "approve", "REQUESTED", "--corp", "UNKNOWN", "--yes"]), runtime()
);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain("UNKNOWN");
expect(requests).toHaveLength(0);
});
it("只有未指定工单时才自动查询待授权工单", async () => {
const result = await handleApprove(parseArgs([
"assist-platform", "approve", "--corp", "CORP", "--token", "mock-token", "--dry-run",
]), runtime());
expect(result.exitCode).toBe(0);
expect(JSON.parse(result.stdout).changes["工单编号"]).toBe("OTHER-TICKET");
expect(requests).toHaveLength(1);
expect(requests[0].url).toContain("assistPlatform/$CORP/search");
});
});
describe("assist-platform transfer 预览与执行的收件人解析", () => {
it.each(["--dry-run", "--yes"])("%s 遇到同名用户都拒绝且不提交", async (mode) => {
responses = () => Response.json({ items: sameNameUsers });
const result = await handleTransfer(parseArgs([
"assist-platform", "transfer", "CORP", "TICKET", "--to", "张三", "--token", "mock-token", mode,
]), runtime());
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain("唯一工号或账号");
expect(requests).toHaveLength(1);
expect(requests[0].url).toContain("userRole/search");
});
it("查询失败的 dry-run 也不能显示成功解析的预览", async () => {
responses = () => new Response("unauthorized", { status: 401 });
const result = await handleTransfer(parseArgs([
"assist-platform", "transfer", "CORP", "TICKET", "--to", "user3016", "--token", "mock-token", "--dry-run",
]), runtime());
expect(result.exitCode).toBe(1);
expect(result.stdout).toBe("");
});
it("唯一工号的 dry-run 显示实际账号,与 --yes 的请求一致", async () => {
responses = (request) => request.url.includes("userRole/search")
? Response.json({ items: sameNameUsers })
: Response.json({ value: true });
const args = ["assist-platform", "transfer", "CORP", "TICKET", "--to", "3016", "--token", "mock-token"];
const preview = await handleTransfer(parseArgs([...args, "--dry-run"]), runtime());
expect(JSON.parse(preview.stdout).changes.recipientId).toBe("user3016");
const result = await handleTransfer(parseArgs([...args, "--yes"]), runtime());
expect(result.exitCode).toBe(0);
const writes = requests.filter((request) => request.url.includes("assistPlatform/transfer"));
expect(writes).toHaveLength(1);
expect(await writes[0].json()).toEqual({ assistId: "TICKET", recipient: "user3016" });
});
});
+10
View File
@@ -0,0 +1,10 @@
import { describe, expect, it } from "bun:test";
import { isClientGoodOpened } from "./analyze.js";
describe("workflow analyze enterprise application status", () => {
it("uses the enterprise opening status and ignores marketplace online status", () => {
expect(isClientGoodOpened({ status: "OPENED", onLineStatus: "OFFLINE" })).toBe(true);
expect(isClientGoodOpened({ status: "EXPIRE", onLineStatus: "ONLINE" })).toBe(false);
expect(isClientGoodOpened({ status: "CLOSED", onLineStatus: "ONLINE" })).toBe(false);
});
});
+5 -1
View File
@@ -10,6 +10,10 @@ import { printJson, printTable, printKeyValue } from "../../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { createWorkflowDetailClient } from "./shared.js";
export function isClientGoodOpened(item: { status?: string | null; onLineStatus?: string | null }): boolean {
return item.status?.toUpperCase() === "OPENED";
}
export async function handleAnalyze(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow analyze <pipelineId>\n", exitCode: 1 };
@@ -44,7 +48,7 @@ export async function handleAnalyze(parsed: CliParsedArgs, runtime: CliRuntime):
const goods = await fetchClientGoods(runtime.selectedCorp!, { isAll: true });
const codes = new Set<string>();
for (const item of goods) {
const isOpened = item.status?.toUpperCase() === "OPENED" || item.onLineStatus?.toUpperCase() === "ONLINE";
const isOpened = isClientGoodOpened(item);
if (isOpened && Array.isArray(item.powers)) {
for (const power of item.powers) {
if (typeof power === "string") {
+3 -1
View File
@@ -50,7 +50,9 @@ export const CorpSessionInfoSchema = z.object({
roles: z.array(z.string()).nullable().optional().describe("员工角色清单"),
roleTitles: z.string().nullable().optional().describe("高管/高级角色头衔"),
isSeniorExecutive: z.boolean().nullable().optional().describe("是否包含高管/高级审批角色"),
riskLevel: z.string().nullable().optional().describe("身份风控等级 (HIGH/MEDIUM/NORMAL)"),
identityComplete: z.boolean().optional().describe("身份画像查询是否完整"),
identityUnavailableFields: z.array(z.string()).optional().describe("身份画像未能确认的信息"),
riskLevel: z.string().nullable().optional().describe("身份风控等级 (HIGH/MEDIUM/NORMAL/UNKNOWN)"),
permissions: z.array(z.string()).nullable().optional().describe("员工功能权限清单"),
});
export type CorpSessionInfo = z.infer<typeof CorpSessionInfoSchema>;
@@ -24,3 +24,20 @@
- `listAssistTickets`: 查询企业生效中的协助工单(包含 ticketId、原因、有效期、申请人)
- `searchStaffList`: 查询企业内部员工名单(用于指定代客身份时的 staffId 定位)
- `getAssistToken`: 换取免密代客登录链接与临时 JWT凭证
## 会话生成、导入与身份完整度
- `assist-platform enter <corpId> --dry-run` 在换票、身份查询和落盘前返回预览;无论是否带 `--save` / `--switch`,均不需要协助平台登录,也不会发出网络请求。
- `--save --yes` 导入后同步注册当前企业上下文;`--switch` 仅在实际切换成功后输出 `switched: true`。失败时说明配置已保存并提示重试切换。
- 生成成功的文本与 JSON 明确交付会话 Token 和可用免密链接,使用 CLI 受控凭证输出机制;捕获的诊断日志和错误继续统一脱敏。
- 导入默认沿用底层最佳努力 OpenAPI 密钥提取:无密钥、无读取权限或存在多个密钥均不阻止有效临时会话保存。SDK 显式 `elevate: true` 仍要求成功提取密钥,`elevate: false` 跳过提取。
- 身份画像输出可选的 `profileComplete` / `unavailableFields`,配置 `session` 对应保存可选的 `identityComplete` / `identityUnavailableFields`;旧配置仍可读取。员工、管理员标记、角色、权限或部门查询缺失时,完整度为 false;未知的 `isAdmin` / `isSeniorExecutive` 为 null,缺乏已知高风险证据时 `riskLevel` 为 `UNKNOWN`,不会假装 `NORMAL`。
- 已知管理员、角色或高权限证据仍显示 HIGH/MEDIUM;导入时补用 JWT 已确认的身份。同一员工的历史权限及高风险状态不会因本次探测不完整而被降级,其他员工的画像不会被沿用。
SDK 消费者应处理画像布尔值的 null 和新增的 UNKNOWN 风险枚举;会话结果顶层 `isAdmin` 仍表示请求的授权模式,其 boolean 类型不变。
## 审批与转交目标解析
- `approve <工单ID> --corp <企业ID>`:显式 `--corp` 下,唯一位置参数始终为工单 ID;也支持 `approve <企业ID> <工单ID>`、`approve <企业ID> --ticket <工单ID>`,以及使用当前企业的 `approve <工单ID>` / `approve --ticket <工单ID>`。位置工单与 `--ticket` 不一致或位置参数多余时拒绝执行;只有完全未指定工单时才自动查询待授权工单。
- 转交收件人依次按账号 ID、工号、姓名精确匹配,再尝试模糊匹配。同一账号的多条角色记录按用户 ID 去重;同一匹配级别命中多个用户时拒绝选择,须改用唯一工号或账号。
- 转交的 dry-run 与执行使用相同的收件人解析规则。歧义、未找到人员或查询失败都会终止,不会将未解析的输入直接提交给转交接口。
+14 -2
View File
@@ -6,6 +6,7 @@ import type {
AssistPlatformTicket,
CorporationDetail,
StaffRoleItem,
AssistIdentityUnavailableField,
TransferCandidate,
TransferTicketParams,
} from "./types.js";
@@ -392,9 +393,11 @@ export async function getStaffMeAndRolesApi(
permissions: string[];
roles: StaffRoleItem[];
departmentName?: string;
unavailableFields: AssistIdentityUnavailableField[];
}> {
let staff: Record<string, unknown> = {};
let permissions: string[] = [];
const unavailableFields = new Set<AssistIdentityUnavailableField>(["staff", "admin", "permissions", "roles"]);
try {
const meRes = await client
@@ -409,9 +412,12 @@ export async function getStaffMeAndRolesApi(
}>();
if (meRes.value?.staff) {
staff = meRes.value.staff;
if (staff.id) unavailableFields.delete("staff");
if (typeof staff.admin === "boolean") unavailableFields.delete("admin");
}
if (Array.isArray(meRes.value?.permissions)) {
if (Array.isArray(meRes.value?.permissions) && meRes.value.permissions.every((permission) => typeof permission === "string")) {
permissions = meRes.value.permissions.map(String);
unavailableFields.delete("permissions");
}
} catch {
// 允许容错降级
@@ -436,8 +442,11 @@ export async function getStaffMeAndRolesApi(
}>();
if (Array.isArray(rolesRes.items)) {
if (rolesRes.items.every((item) => item && typeof item.roleDefName === "string")) {
unavailableFields.delete("roles");
}
for (const item of rolesRes.items) {
if (item.roleDefName) {
if (item?.roleDefName) {
roles.push({
id: String(item.roleDefId || ""),
name: String(item.roleDefName),
@@ -456,6 +465,7 @@ export async function getStaffMeAndRolesApi(
staff.defaultDepartment || (Array.isArray(staff.departments) ? staff.departments[0] : "") || ""
);
if (deptId) {
unavailableFields.add("department");
try {
const cleanDeptId = deptId.startsWith("$") ? deptId : `$${deptId}`;
const deptRes = await client
@@ -465,6 +475,7 @@ export async function getStaffMeAndRolesApi(
.json<{ value?: { name?: string } }>();
if (deptRes.value?.name) {
departmentName = deptRes.value.name;
unavailableFields.delete("department");
}
} catch {
// 允许容错降级
@@ -476,6 +487,7 @@ export async function getStaffMeAndRolesApi(
permissions,
roles,
departmentName,
unavailableFields: [...unavailableFields],
};
}
@@ -1,4 +1,4 @@
import { describe, expect, it } from "bun:test";
import { afterEach, beforeEach, describe, expect, it } from "bun:test";
import ky from "ky";
import {
analyzeStaffRoleRisk,
@@ -26,6 +26,13 @@ function createMockClient(handler: (req: Request) => Response | Promise<Response
}
describe("domains/assist-platform - 协助平台业务编排", () => {
let originalFetch: typeof fetch;
beforeEach(() => {
originalFetch = globalThis.fetch;
// 身份穿透创建独立客户端;禁止这些 mock 编排测试访问真实企业接口。
globalThis.fetch = (async () => new Response("Mock identity unavailable", { status: 403 })) as unknown as typeof fetch;
});
afterEach(() => { globalThis.fetch = originalFetch; });
it("searchCorporations 能够正确分页并返回企业列表", async () => {
const client = createMockClient(async (req) => {
expect(req.url).toContain("corporation/search");
+78 -34
View File
@@ -1,7 +1,7 @@
import ky, { type KyInstance } from "ky";
import { BusinessError, NotFoundError } from "../../core/errors.js";
import { importFromLink, type ImportFromLinkOptions } from "../../core/auth/link-import.js";
import { saveCorpConfig } from "../../core/config/loader.js";
import { loadCorpConfigs, saveCorpConfig } from "../../core/config/loader.js";
import type { CorpConfig } from "../../core/config/types.js";
import {
approveAssistTicketApi,
@@ -73,13 +73,14 @@ export const SENIOR_ROLE_KEYWORDS = [
export function analyzeStaffRoleRisk(profile: {
staffName: string;
isAdmin: boolean;
isAdmin: boolean | null;
profileComplete?: boolean;
roleNames: string[];
permissions: string[];
}): {
isSeniorExecutive: boolean;
isSeniorExecutive: boolean | null;
seniorTitles: string[];
riskLevel: "HIGH" | "MEDIUM" | "NORMAL";
riskLevel: "HIGH" | "MEDIUM" | "NORMAL" | "UNKNOWN";
riskWarning?: string;
} {
const seniorTitles: string[] = [];
@@ -100,17 +101,23 @@ export function analyzeStaffRoleRisk(profile: {
["SYS_ADMIN", "ROLE_ADMIN", "CORP_PAYMENT_MANAGE", "FLOW_ADMIN"].includes(p)
);
const isSeniorExecutive = seniorTitles.length > 0 || hasHighRiskPerms;
const riskLevel = seniorTitles.length > 0 ? "HIGH" : hasHighRiskPerms ? "MEDIUM" : "NORMAL";
const hasKnownRisk = seniorTitles.length > 0 || hasHighRiskPerms;
const incomplete = profile.profileComplete === false;
const isSeniorExecutive = hasKnownRisk ? true : incomplete ? null : false;
const riskLevel = seniorTitles.length > 0 ? "HIGH" : hasHighRiskPerms ? "MEDIUM" : incomplete ? "UNKNOWN" : "NORMAL";
let riskWarning: string | undefined;
if (isSeniorExecutive) {
if (hasKnownRisk) {
const titleSummary = seniorTitles.length > 0 ? seniorTitles.join(" / ") : "高级系统管理员";
riskWarning =
`当前协助会话获取的是高阶管理人员身份 [${titleSummary}](${profile.staffName})。` +
`该身份拥有高级审批、财务权限或全系统管理权限。经理与实施人员严禁借用该身份发起或通过非授权审批,防范越权误操作!`;
}
if (incomplete) {
riskWarning = `${riskWarning || ""}身份或角色权限信息不完整,无法排除更高权限风险,请先核验当前身份。`;
}
return {
isSeniorExecutive,
seniorTitles,
@@ -145,7 +152,8 @@ export async function inspectAssistIdentity(
const cellphone = staff.cellphone ? String(staff.cellphone) : undefined;
const email = staff.email ? String(staff.email) : undefined;
const code = staff.code ? String(staff.code) : undefined;
const isAdmin = Boolean(staff.admin || false);
const isAdmin = typeof staff.admin === "boolean" ? staff.admin : null;
const profileComplete = res.unavailableFields.length === 0;
const roleNames = res.roles.map((r) => r.name);
const readablePermissions = res.permissions.map(
@@ -153,6 +161,7 @@ export async function inspectAssistIdentity(
);
const riskAnalysis = analyzeStaffRoleRisk({
profileComplete,
staffName,
isAdmin,
roleNames,
@@ -160,6 +169,8 @@ export async function inspectAssistIdentity(
});
return {
profileComplete,
unavailableFields: res.unavailableFields,
staffId,
staffName,
cellphone,
@@ -338,20 +349,52 @@ export async function importAssistSessionToLocal(
overwrite: params.overwrite ?? true,
enterprisesDir: params.enterprisesDir,
ttl: params.ttl,
elevate: params.elevate ?? true,
elevate: params.elevate,
};
const linkToImport = sessionResult.loginUrl.includes("accessToken=")
? sessionResult.loginUrl
: `https://app.ekuaibao.com/web/thirdparty.html?accessToken=${encodeURIComponent(sessionResult.token)}&ekbCorpId=${encodeURIComponent(sessionResult.corporationId)}${sessionResult.staffId ? `&staffId=${encodeURIComponent(sessionResult.staffId)}` : ""}`;
const previousCorp = loadCorpConfigs(params.enterprisesDir ? [params.enterprisesDir] : undefined)
.find((corp) => corp.id === sessionResult.corporationId);
const corpConfig = await importFromLink(linkToImport, importOptions);
// 注入完整身份画像与角色权限风控元数据并保存落盘
if (sessionResult.identity) {
const ident = sessionResult.identity;
// 画像接口失败时保留 JWT 已确认的身份,不能将未知值降为非管理员或低风险
const previousSession = previousCorp?.credentials.staffId === corpConfig.credentials.staffId
? previousCorp.session
: undefined;
ident.isAdmin ??= corpConfig.session?.isAdmin ?? previousSession?.isAdmin ?? null;
const unavailable = ident.unavailableFields || [];
if (unavailable.includes("roles") && previousSession?.roles) {
ident.roleNames = [...new Set([...ident.roleNames, ...previousSession.roles])];
}
if (unavailable.includes("permissions") && previousSession?.permissions) {
ident.permissions = [...new Set([...ident.permissions, ...previousSession.permissions])];
ident.readablePermissions = ident.permissions.map((p) => `${PERMISSION_LABEL_MAP[p] || p} (${p})`);
}
if (unavailable.includes("staff")) {
ident.staffId = corpConfig.credentials.staffId || ident.staffId;
ident.staffName = corpConfig.session?.staffName || ident.staffName;
}
Object.assign(ident, analyzeStaffRoleRisk(ident));
// 同一员工的历史高风险证据不能因本次探测不完整而被降级。
if (ident.profileComplete === false && previousSession?.riskLevel) {
const riskRank: Record<string, number> = { UNKNOWN: 0, NORMAL: 0, MEDIUM: 1, HIGH: 2 };
if ((riskRank[previousSession.riskLevel] || 0) > riskRank[ident.riskLevel]!) {
ident.riskLevel = previousSession.riskLevel as "HIGH" | "MEDIUM";
ident.isSeniorExecutive = true;
}
}
sessionResult.staffId = ident.staffId || sessionResult.staffId;
sessionResult.staffName = ident.staffName || sessionResult.staffName;
corpConfig.session = {
...corpConfig.session,
identityComplete: ident.profileComplete,
identityUnavailableFields: ident.unavailableFields,
staffName: ident.staffName || corpConfig.session?.staffName,
cellphone: ident.cellphone || corpConfig.session?.cellphone,
isAdmin: ident.isAdmin ?? corpConfig.session?.isAdmin,
@@ -388,31 +431,39 @@ export async function resolveTransferRecipient(
}
const candidates = await listTransferCandidates(client);
const exactMatches = candidates.filter(
(c) => c.name === cleanTarget || c.code === cleanTarget || c.id === cleanTarget
);
if (exactMatches.length === 1) {
return exactMatches[0];
}
if (exactMatches.length > 1) {
return exactMatches[0];
// 一个用户可能有多条角色记录;先匹配,再按稳定账号 ID 去重。
const uniqueUsers = (matches: TransferCandidate[]) =>
[...new Map(matches.map((candidate) => [candidate.id, candidate])).values()];
const rejectAmbiguous = (matches: TransferCandidate[]): never => {
const names = matches
.slice(0, 5)
.map((m) => `${m.name}(${m.id}${m.code ? `, 工号: ${m.code}` : ""})`)
.join("、");
throw new BusinessError(`匹配到多个可转交人员 [${names}],请指定唯一工号或账号`);
};
// 账号 ID 优先于工号、姓名,避免一个人的姓名覆盖另一个人的明确账号。
for (const matches of [
candidates.filter((c) => c.id === cleanTarget),
candidates.filter((c) => c.code === cleanTarget),
candidates.filter((c) => c.name === cleanTarget),
]) {
const users = uniqueUsers(matches);
if (users.length === 1) return users[0];
if (users.length > 1) rejectAmbiguous(users);
}
const fuzzyMatches = candidates.filter(
const fuzzyMatches = uniqueUsers(candidates.filter(
(c) =>
c.name.includes(cleanTarget) ||
(c.code && c.code.includes(cleanTarget)) ||
c.id.includes(cleanTarget)
);
));
if (fuzzyMatches.length === 1) {
return fuzzyMatches[0];
}
if (fuzzyMatches.length > 1) {
const names = fuzzyMatches
.slice(0, 5)
.map((m) => `${m.name}(${m.code || m.id})`)
.join("、");
throw new BusinessError(`匹配到多个可转交人员 [${names}],请指定具体工号或全名`);
rejectAmbiguous(fuzzyMatches);
}
throw new NotFoundError(`未在具备协助权限的人员库中找到匹配的人员: "${cleanTarget}"`);
@@ -426,16 +477,9 @@ export async function transferAssistTicket(
remarks?: string;
}
): Promise<TransferTicketResult> {
let resolvedRecipientId = params.recipient;
let recipientName: string | undefined;
try {
const candidate = await resolveTransferRecipient(client, params.recipient);
resolvedRecipientId = candidate.id;
recipientName = candidate.name;
} catch {
// 若解析不到,仍尝试直接以原值请求
}
const candidate = await resolveTransferRecipient(client, params.recipient);
const resolvedRecipientId = candidate.id;
const recipientName = candidate.name;
await transferAssistTicketApi(client, {
ticketId: params.ticketId,
@@ -0,0 +1,98 @@
import { describe, expect, it } from "bun:test";
import ky from "ky";
import { BusinessError, EkbApiError, NotFoundError } from "../../core/errors.js";
import { resolveTransferRecipient, transferAssistTicket } from "./services.js";
type User = { id: string; name: string; code?: string };
const first: User = { id: "zhang3016", name: "张三", code: "3016" };
const second: User = { id: "zhang3020", name: "张三", code: "3020" };
function mockClient(users: User[], failSearch = false) {
const writes: unknown[] = [];
const client = ky.create({
prefix: "https://assist.invalid/api",
retry: 0,
fetch: async (input, init) => {
const request = input instanceof Request ? input : new Request(input.toString(), init);
if (request.url.endsWith("userRole/search")) {
if (failSearch) return new Response("unavailable", { status: 503 });
return Response.json({ items: users.map((userId, i) => ({
id: `role-row-${i}`,
userId,
roleIds: [{ id: `role-${i}`, name: `角色${i}` }],
})) });
}
if (request.url.endsWith("assistPlatform/transfer")) {
writes.push(await request.json());
return Response.json({ value: true });
}
throw new Error(`Unexpected request: ${request.url}`);
},
});
return { client, writes };
}
describe("assist-platform 转交目标解析", () => {
it("同名不同账号拒绝精确匹配,错误提示唯一工号或账号", async () => {
const { client } = mockClient([first, second]);
await expect(resolveTransferRecipient(client, "张三")).rejects.toBeInstanceOf(BusinessError);
await expect(resolveTransferRecipient(client, "张三")).rejects.toThrow("唯一工号或账号");
});
it("相同工号的不同用户也拒绝选择第一人", async () => {
const { client } = mockClient([first, { ...second, code: first.code }]);
await expect(resolveTransferRecipient(client, "3016")).rejects.toThrow("多个可转交人员");
});
it("账号精确匹配优先于其他人的工号和姓名", async () => {
const { client } = mockClient([
{ ...second, code: first.id },
{ id: "other", name: first.id },
first,
]);
expect((await resolveTransferRecipient(client, first.id)).id).toBe(first.id);
});
it("工号精确匹配优先于其他人的姓名", async () => {
const { client } = mockClient([{ ...second, name: "3016" }, first]);
expect((await resolveTransferRecipient(client, "3016")).id).toBe(first.id);
});
it.each(["张三", "3016", "zhang3016", "zhang", " 3016 "])(
"同一稳定账号的多条角色记录不会令 %s 产生歧义",
async (target) => {
const { client } = mockClient([first, first]);
expect((await resolveTransferRecipient(client, target)).id).toBe(first.id);
}
);
it("模糊匹配存在多个用户时拒绝", async () => {
const { client } = mockClient([first, second]);
await expect(resolveTransferRecipient(client, "zhang")).rejects.toThrow("多个可转交人员");
});
it.each(["张三", "不存在的账号"])("执行转交时 %s 解析失败不提交原始值", async (recipient) => {
const { client, writes } = mockClient([first, second]);
const ErrorClass = recipient === "张三" ? BusinessError : NotFoundError;
await expect(transferAssistTicket(client, { ticketId: "TICKET", recipient }))
.rejects.toBeInstanceOf(ErrorClass);
expect(writes).toEqual([]);
});
it("查询候选人失败时不以原始账号继续写入", async () => {
const { client, writes } = mockClient([], true);
await expect(transferAssistTicket(client, { ticketId: "TICKET", recipient: first.id }))
.rejects.toBeInstanceOf(EkbApiError);
expect(writes).toEqual([]);
});
it("使用唯一工号时写入稳定账号 ID", async () => {
const { client, writes } = mockClient([first, first, second]);
const result = await transferAssistTicket(client, {
ticketId: "TICKET", recipient: "3016", remarks: "交接",
});
expect(result.recipient).toBe(first.id);
expect(result.recipientName).toBe(first.name);
expect(writes).toEqual([{ assistId: "TICKET", recipient: first.id, remarks: "交接" }]);
});
});
+7 -3
View File
@@ -54,22 +54,26 @@ export interface StaffRoleItem {
code?: string;
}
export type AssistIdentityUnavailableField = "staff" | "admin" | "permissions" | "roles" | "department";
export interface AssistIdentityProfile {
profileComplete?: boolean;
unavailableFields?: AssistIdentityUnavailableField[];
staffId: string;
staffName: string;
cellphone?: string;
email?: string;
code?: string;
isAdmin: boolean;
isAdmin: boolean | null;
departmentId?: string;
departmentName?: string;
roles: StaffRoleItem[];
roleNames: string[];
permissions: string[];
readablePermissions: string[];
isSeniorExecutive: boolean;
isSeniorExecutive: boolean | null;
seniorTitles: string[];
riskLevel: "HIGH" | "MEDIUM" | "NORMAL";
riskLevel: "HIGH" | "MEDIUM" | "NORMAL" | "UNKNOWN";
riskWarning?: string;
}
@@ -156,6 +156,6 @@ hose-use workflow eval-script --code="return a + b;" --input='{"a":1,"b":2}'
## 工具链静态门禁与防御性保障 (Toolchain Defense & Linting)
1. **文档站点域名拦截 (`DOCS_DOMAIN_USED`)**:静态分析会阻断在 HTTP 任务节点配置 `docs.ekuaibao.com` 的行为(错误复制开放平台文档地址),指导修正为 `app.ekuaibao.com`;
2. **应用权限代码交叉核验 (`UNLICENSED_POWER_CODE`)**:扫描 HTTP 任务 URL 中的 `powerCode` 参数(如 `TICKET_AUDIT_switch`),与当前企业已开通应用交叉核验,未开通时产生硬门禁阻断,防止运行时直接返回 403 Forbidden;
2. **应用权限代码交叉核验 (`UNLICENSED_POWER_CODE`)**:扫描 HTTP 任务 URL 中的 `powerCode` 参数(如 `TICKET_AUDIT_switch`),与当前企业已开通应用交叉核验,未开通时产生硬门禁阻断;参数包含无效 URL 百分号转义时产生 `INVALID_POWER_CODE_ENCODING` 硬门禁诊断,避免权限探测异常中断其他节点分析;
3. **前端富文本 `$snapshot` 自动清洗**:在 SDK `updateWorkflow` 时,自动递归遍历 `$snapshot` 字典并将陈旧的 `docs.ekuaibao.com` 替换为 `app.ekuaibao.com`,避免 Web 控制台用户重新点开节点保存时产生配置倒退;
4. **Webhook 样本注入 (`workflow webhook send`)**:支持向工作流专属 Webhook 地址直接模拟打桩发送 JSON 报文或关联单据真实载荷,彻底解决新建/复制工作流后 Web 界面“获取更多数据样本”等待卡死的问题。
@@ -617,28 +617,42 @@ export function analyzeWorkflow(
// 6.3 权限代码 (powerCode) 开通状态校验 (UNLICENSED_POWER_CODE / POWER_CODE_DEPENDENCY)
const powerCodeMatch = url.match(/[?&]powerCode=([^&#]+)/);
if (powerCodeMatch) {
const powerCode = decodeURIComponent(powerCodeMatch[1]);
const powerCodeKey = powerCode.trim().toLowerCase();
const appName = WELL_KNOWN_POWER_CODES[powerCodeKey] || `权限代码 [${powerCode}] 对应的应用`;
let powerCode: string | undefined;
try {
powerCode = decodeURIComponent(powerCodeMatch[1]);
} catch {
addDiagnostic(diagnostics, {
severity: "error",
category: "hard_block",
code: "INVALID_POWER_CODE_ENCODING",
path,
message: `HTTP 任务 [${task.label || task.name}] (${task.name}) 的 URL 中 powerCode 参数包含无效的百分号转义 [${powerCodeMatch[1]}],无法校验功能权限。请修正为有效的 URL 编码。`,
});
}
if (openedPowerCodeSet !== undefined) {
if (!openedPowerCodeSet.has(powerCodeKey)) {
if (powerCode !== undefined) {
const powerCodeKey = powerCode.trim().toLowerCase();
const appName = WELL_KNOWN_POWER_CODES[powerCodeKey] || `权限代码 [${powerCode}] 对应的应用`;
if (openedPowerCodeSet !== undefined) {
if (!openedPowerCodeSet.has(powerCodeKey)) {
addDiagnostic(diagnostics, {
severity: "error",
category: "hard_block",
code: "UNLICENSED_POWER_CODE",
path,
message: `HTTP 任务 [${task.label || task.name}] (${task.name}) 携带了权限代码 'powerCode=${powerCode}',但当前企业尚未开通对应功能/应用(如 ${appName})。运行时合思开放平台网关将直接返回 403 Forbidden(未开通功能,无权访问)。请先在开放平台/应用商城中开通该应用,或更换为已开通的等价接口。`,
});
}
} else {
addDiagnostic(diagnostics, {
severity: "error",
category: "hard_block",
code: "UNLICENSED_POWER_CODE",
severity: "warning",
category: "soft_advice",
code: "POWER_CODE_DEPENDENCY",
path,
message: `HTTP 任务 [${task.label || task.name}] (${task.name}) 携带了权限代码 'powerCode=${powerCode}',但当前企业尚未开通对应功能/应用(如 ${appName})。运行时合思开放平台网关将直接返回 403 Forbidden(未开通功能,无权访问)。请先在开放平台/应用商城中开通该应用,或更换为已开通的等价接口。`,
message: `HTTP 任务 [${task.label || task.name}] (${task.name}) 携带了权限代码 'powerCode=${powerCode}'。调用此接口要求企业已开通 [${appName}],否则运行时将返回 403 Forbidden。`,
});
}
} else {
addDiagnostic(diagnostics, {
severity: "warning",
category: "soft_advice",
code: "POWER_CODE_DEPENDENCY",
path,
message: `HTTP 任务 [${task.label || task.name}] (${task.name}) 携带了权限代码 'powerCode=${powerCode}'。调用此接口要求企业已开通 [${appName}],否则运行时将返回 403 Forbidden。`,
});
}
}
}
@@ -361,5 +361,41 @@ describe("Workflow static analysis", () => {
expect(diag?.category).toBe("soft_advice");
expect(diag?.severity).toBe("warning");
});
it("diagnoses malformed powerCode encoding and continues checking later nodes", () => {
const wf = {
id: "wf-invalid-power-code-encoding",
label: "权限代码编码异常",
state: 1,
version: "1",
tasks: [
{
name: "action_invalid",
type: "http",
label: "无效权限代码",
url: "https://app.ekuaibao.com/api/openapi/v1/backlog/data/[{flowId}]?powerCode=bad%value",
},
{
name: "action_encoded",
type: "http",
label: "编码权限代码",
url: "https://app.ekuaibao.com/api/openapi/v1/backlog/data/[{flowId}]?powerCode=custom%20power",
},
],
};
const result = analyzeWorkflow(wf as any);
const invalidEncoding = result.diagnostics.find((d) => d.code === "INVALID_POWER_CODE_ENCODING");
const dependency = result.diagnostics.find((d) => d.code === "POWER_CODE_DEPENDENCY");
expect(invalidEncoding?.severity).toBe("error");
expect(invalidEncoding?.category).toBe("hard_block");
expect(invalidEncoding?.path).toBe("0");
expect(invalidEncoding?.message).toContain("无效的百分号转义");
expect(dependency?.path).toBe("1");
expect(dependency?.message).toContain("custom power");
expect(result.summary.hardBlocks).toBe(1);
expect(result.summary.softAdvices).toBe(1);
});
});