fix: preserve assist session lifecycle and identity certainty
This commit is contained in:
1 parent
4e53c88a51
commit
3597ec6694
8 files changed
+369
-38
No files matched your search
@@ -0,0 +1,236 @@
|
||||
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");
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
|
||||
@@ -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,14 @@
|
||||
- `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 类型不变。
|
||||
@@ -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");
|
||||
|
||||
@@ -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 = previousSession.roles;
|
||||
}
|
||||
if (unavailable.includes("permissions") && previousSession?.permissions) {
|
||||
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,
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user