feat(assist): 支持协助身份与角色权限穿透呈现及高管防误用警示
- 实测澄清协助平台时长限制: 服务端 POST /api/assistPlatform/create 硬性单次上限为 24 小时 (1 天),超过直接报错 400,支持 --days/--hours 并在超限时清晰提示 - 协助直通会话生成及落盘时实时穿透解析组织架构: 提取人员姓名、工号、手机、所属部门、所配角色清单及核心系统权限 - 建立高管身份与特权角色风控评级体系 (analyzeStaffRoleRisk): 自动识别总监、主管理员、财务负责人、总经理等高危身份并输出安全风控警示框 - 将完整人员身份画像与风控元数据注入持久化企业配置 (enterprises/<corpId>.json) - 在 SKILL.md 追加 Rule 13 及更新 assist-platform.md 说明文档
This commit is contained in:
1 parent
60d0b8ffc1
commit
2ace4e2378
12 files changed
+957
-466
No files matched your search
Vendored
+468
-454
File diff suppressed because it is too large.
Load diff
@@ -61,6 +61,11 @@ metadata:
|
||||
- **排障或改造的知情选择权**:客户现场常存在“原本有一个生产在跑的工作流,因出错或特殊情况被停用或直接处于草稿修改中”。Agent 介入排障或调整前,**必须向用户明确揭示实体归属与当前状态**,并提供两条明确路径供用户决策:
|
||||
1. **克隆独立副本(推荐稳健路径)**:使用 `hose-use workflow copy <pipelineId>` 创建真正的独立工作流副本(如 `<原名称> 副本`),在副本上修改与联调测试,原流程不受任何触碰;
|
||||
2. **直接就地修改当前停用/草稿流程(快速就地路径)**:若用户明确知情并授权直接修复当前草稿,则就地修改,但**严格禁止擅自点击发布(publish)**,必须完成全链路验证并获得用户明确指令后方可上线。
|
||||
13. **协助会话人员身份角色穿透与高管权限防误用守则 (Assist Identity Profile & Executive Privilege Guard)**:
|
||||
- **身份与角色权限第一时间穿透呈现**:通过协助链接进入企业(`hose-use assist-platform enter`)或生成免密会话时,系统自动穿透解析并输出当前获得的员工姓名、工号、所属部门、所配角色清单以及核心系统权限;并自动将该人员画像与风控等级持久化落盘至本地企业配置(`enterprises/<corpId>.json`);
|
||||
- **高阶管理人员权限风控识别**:合思协助平台具备直接借用企业任意员工身份(包含主管理员、企业法定代表人、财务负责人/总监、VP/总裁等高管身份)的高危能力。当获取的身份命中高管关键词(总监、主管、主管理员、总经理等)或具备 `SYS_ADMIN` / `CORP_PAYMENT_MANAGE` 权限时,系统会自动发出醒目的高管权限风控警示框;
|
||||
- **防范越权与误用硬约束**:一线实施、运维人员或 AI Agent 严禁借用高管特权身份在系统内代行审批通过、款项拨付或提交非授权配置!所有协助权限必须严格局限在系统排障、配置诊断、数据核验与接口联调,严禁进行越权业务审批;
|
||||
- **协助时长服务端硬性上限**:协助平台工单申请(`POST /api/assistPlatform/create`)受服务端硬性安全管控,单次最长有效时间为 24 小时(1天),超过 24 小时服务端直接返回 400 拒绝。如需持续维护,可在工单到期后再次发起或在端内续签。
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -84,12 +84,19 @@ hose-use assist-platform staff <企业ID> --mobile "13800000000"
|
||||
|
||||
当企业名下没有生效工单或工单已过期时,可向目标企业发起新的协助授权申请。**注意:写操作仅限在本地确认的 🧪 测试企业中进行,正式企业必须获得用户明确指示。**
|
||||
|
||||
> [!IMPORTANT] 协助时长服务端硬性上限与 24 小时限制
|
||||
> 合思协助平台服务端(`POST /api/assistPlatform/create`)实施了底层的硬性安全管控:
|
||||
> - 单次协助工单最长有效期限为 **24 小时 (1天)**;
|
||||
> - 超过 24 小时(如 48 小时或 7 天)服务端会直接报错 `{"errorCode":400,"errorMessage":"参数错误,申请时间不能超过24小时"}` 并拒绝受理;
|
||||
> - 命令行同时支持 `--hours <小时>` 与 `--days <天数>`,传入超过 24 小时(> 1 天)将即时给出阻断与友好提示。如需持续维护,可在工单到期后再次发起或在端内续签。
|
||||
|
||||
```bash
|
||||
# 查看变更预览(安全 Dry-Run)
|
||||
hose-use assist-platform apply ID01ofWoOC1wiX --dry-run
|
||||
|
||||
# 向测试企业发起 24 小时协助工单申请
|
||||
# 向测试企业发起 24 小时(1天)协助工单申请
|
||||
hose-use assist-platform apply ID01ofWoOC1wiX --message "测试环境接口联调" --hours 24 --yes
|
||||
hose-use assist-platform apply ID01ofWoOC1wiX --message "测试环境接口联调" --days 1 --yes
|
||||
```
|
||||
|
||||
提交后工单初始状态为 `🟡 待提供`,等待企业管理员登录合思 Web/桌面端确认开启授权即可激活。
|
||||
@@ -115,12 +122,20 @@ hose-use assist-platform approve ID01Xeno3GpoNV --corp ID01ofWoOC1wiX --yes
|
||||
|
||||
---
|
||||
|
||||
## 7. 免密代客进入与自动落盘 (`enter`)
|
||||
## 7. 免密代客进入、身份穿透与高管风控 (`enter`)
|
||||
|
||||
基于选定工单与身份(管理员或指定员工),向协助平台换取免密直通链接,并支持一键落盘到本地企业库和自动提权。
|
||||
|
||||
### 7.1 人员身份画像穿透与高管权限防误用守则
|
||||
|
||||
> [!WARNING] 高阶管理人员权限风控警示 (Executive Role Risk Warning)
|
||||
> 1. **人员身份全景穿透**:通过协助链接进入企业或生成免密会话时,CLI 会自动向合思组织架构服务下钻查询,第一时间提取当前获得的员工姓名、工号、绑定手机、所属部门、所配角色清单以及核心系统权限;
|
||||
> 2. **持久化落盘安全标记**:落盘至本地(`enterprises/<corpId>.json`)时,会将 `departmentName`, `roles`, `roleTitles`, `isSeniorExecutive`, `riskLevel`, `permissions` 完整写入 `session` 元数据中,确保后续执行可知;
|
||||
> 3. **高管身份命中与警示框**:当角色命中总监、主管理员、财务负责人、总经理、CEO/CFO 等高级头衔,或包含 `SYS_ADMIN` / `CORP_PAYMENT_MANAGE` 时,终端将输出醒目的高管权限风控警示框;
|
||||
> 4. **严禁越权业务审批**:一线实施、运维人员或 AI Agent 严禁代用高管身份进行业务审批通过、款项拨付或非授权单据提交,仅限用于排障与配置诊断。
|
||||
|
||||
```bash
|
||||
# 1. 仅获取免密直达 URL 与临时 Token(默认自动寻找最新有效工单)
|
||||
# 1. 仅获取免密直达 URL 与临时 Token(默认自动寻找最新有效工单,即时输出身份画像与风控警示)
|
||||
hose-use assist-platform enter <企业ID>
|
||||
|
||||
# 2. 以主管理员身份进入
|
||||
@@ -132,7 +147,7 @@ hose-use assist-platform enter <企业ID> --name "李志财"
|
||||
# 4. 指定工单 ID 与 staffId 进入
|
||||
hose-use assist-platform enter <企业ID> --ticket <ticketId> --staff <staffId>
|
||||
|
||||
# 5. 【推荐一键流】获取免密链接后,自动落盘至本地企业名录并切换为当前上下文
|
||||
# 5. 【推荐一键流】获取免密链接后,自动落盘至本地企业名录并切换为当前上下文(持久化保存身份与权限元数据)
|
||||
hose-use assist-platform enter <企业ID> --name "李志财" --save --switch
|
||||
|
||||
# 6. 【高阶全自动】落盘并自动提权(换取永久 OpenAPI 密钥,避免 2 小时临时 Token 过期中断业务)
|
||||
|
||||
@@ -814,7 +814,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"get-token": "enter"
|
||||
},
|
||||
flags: {
|
||||
...flagList("token t user name u hose-token jwt ticket ticket-id auth-code staff alias corp-name count limit n start offset state status corpid id keyword query q message msg reason matter hours hour duration", "value"),
|
||||
...flagList("token t user name u hose-token jwt ticket ticket-id auth-code staff alias corp-name count limit n start offset state status corpid id keyword query q message msg reason matter hours hour duration days day", "value"),
|
||||
...flagList("logout admin save import persist switch current overwrite", "boolean")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,4 +171,50 @@ describe("CLI Commands - assist-platform (合思协助平台)", () => {
|
||||
expect(res.stdout).toContain("ID01Xeno3GpoNV");
|
||||
expect(res.stdout).toContain("同意授权");
|
||||
});
|
||||
|
||||
it("assist-platform apply 传入超过 24 小时或多天时返回明确拒绝提示", async () => {
|
||||
saveAssistPlatformSession({
|
||||
token: "mock-token",
|
||||
userName: "测试人员",
|
||||
baseUrl: "https://unity.ekuaibao.com/api",
|
||||
updatedAt: Date.now(),
|
||||
});
|
||||
|
||||
const runtime = createMockRuntime(tempDir);
|
||||
const parsed: CliParsedArgs = {
|
||||
action: "apply",
|
||||
args: ["ID01KrLMQJWdMH"],
|
||||
options: { days: 2 },
|
||||
raw: ["assist-platform", "apply", "ID01KrLMQJWdMH", "--days", "2"],
|
||||
};
|
||||
|
||||
const res = await handleAssistPlatformCommand(parsed, runtime);
|
||||
expect(res.exitCode).toBe(1);
|
||||
expect(res.stderr).toContain("申请协助时长不能超过 24 小时 (1 天)");
|
||||
expect(res.stderr).toContain("2 天 (48 小时)");
|
||||
expect(res.stderr).toContain("POST /api/assistPlatform/create");
|
||||
expect(res.stderr).toContain("单次协助工单最长有效期限为 24 小时");
|
||||
});
|
||||
|
||||
it("assist-platform apply --days 1 --dry-run 成功换算为 24 小时并预览", async () => {
|
||||
saveAssistPlatformSession({
|
||||
token: "mock-token",
|
||||
userName: "测试人员",
|
||||
baseUrl: "https://unity.ekuaibao.com/api",
|
||||
updatedAt: Date.now(),
|
||||
});
|
||||
|
||||
const runtime = createMockRuntime(tempDir);
|
||||
const parsed: CliParsedArgs = {
|
||||
action: "apply",
|
||||
args: ["ID01KrLMQJWdMH"],
|
||||
options: { days: 1, dryRun: true },
|
||||
raw: ["assist-platform", "apply", "ID01KrLMQJWdMH", "--days", "1", "--dry-run"],
|
||||
};
|
||||
|
||||
const res = await handleAssistPlatformCommand(parsed, runtime);
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("[DRY-RUN]");
|
||||
expect(res.stdout).toContain("24 小时");
|
||||
});
|
||||
});
|
||||
@@ -23,11 +23,22 @@ export async function handleApply(
|
||||
};
|
||||
}
|
||||
|
||||
const hours = numberOption(parsed.options, ["hours", "hour", "duration"]) ?? 24;
|
||||
const days = numberOption(parsed.options, ["days", "day"]);
|
||||
let hours = numberOption(parsed.options, ["hours", "hour", "duration"]);
|
||||
if (days !== undefined) {
|
||||
hours = days * 24;
|
||||
}
|
||||
if (hours === undefined) {
|
||||
hours = 24;
|
||||
}
|
||||
|
||||
if (hours < 1 || hours > 24) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[ERROR] 申请协助时长必须介于 1 到 24 小时之间,当前传入: ${hours}\n`,
|
||||
stderr:
|
||||
`[ERROR] 申请协助时长不能超过 24 小时 (1 天),当前传入: ${days !== undefined ? `${days} 天 (${hours} 小时)` : `${hours} 小时`}。\n` +
|
||||
`提示: 合思协助平台服务端(POST /api/assistPlatform/create)实施了硬性安全限制:单次协助工单最长有效期限为 24 小时 (1天),超过 24 小时服务端将直接拒绝受理。\n` +
|
||||
`如需持续协助支持,可在工单到期后再次快速发起或在端内续签。\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2,12 +2,47 @@ import {
|
||||
generateAssistSession,
|
||||
importAssistSessionToLocal,
|
||||
} from "../../../domains/assist-platform/services.js";
|
||||
import type { AssistIdentityProfile } from "../../../domains/assist-platform/types.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
import { booleanOption, stringOption } from "../../parser.js";
|
||||
import { printJson, printKeyValue } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { resolveAssistClient } from "./common.js";
|
||||
|
||||
function formatIdentityLines(ident?: AssistIdentityProfile): {
|
||||
profilePairs: Record<string, string>;
|
||||
warningText: string;
|
||||
} {
|
||||
const profilePairs: Record<string, string> = {};
|
||||
let warningText = "";
|
||||
|
||||
if (!ident) {
|
||||
return { profilePairs, warningText };
|
||||
}
|
||||
|
||||
profilePairs["获取员工身份"] = `${ident.staffName} (${ident.staffId || "-"})`;
|
||||
if (ident.departmentName) profilePairs["所属部门"] = ident.departmentName;
|
||||
if (ident.cellphone) profilePairs["绑定手机"] = ident.cellphone;
|
||||
if (ident.roleNames.length > 0) profilePairs["所配角色清单"] = ident.roleNames.join("、");
|
||||
if (ident.readablePermissions.length > 0) {
|
||||
const permSummary = ident.readablePermissions.slice(0, 5).join("、");
|
||||
profilePairs["核心系统权限"] = `${permSummary}${ident.readablePermissions.length > 5 ? ` 等共 ${ident.readablePermissions.length} 项` : ""}`;
|
||||
}
|
||||
|
||||
if (ident.isSeniorExecutive && ident.riskWarning) {
|
||||
const titles = ident.seniorTitles.length > 0 ? ident.seniorTitles.join(" / ") : "高级管理人员";
|
||||
warningText =
|
||||
`\n⚠️ 【高阶管理人员权限风控警示 (Executive Role Risk Warning)】\n` +
|
||||
`当前协助会话获取的是企业【${titles}】身份(${ident.staffName})。\n` +
|
||||
`防范越权与误用守则:\n` +
|
||||
` 1. 该身份在企业内具备高级审批、财务支配与全系统管理权限;\n` +
|
||||
` 2. 经理与一线实施人员严禁代用高管身份进行业务审批通过或非授权表单提交;\n` +
|
||||
` 3. 请严格将此会话权限限定在必要的系统排障、配置诊断与接口联调中!\n`;
|
||||
}
|
||||
|
||||
return { profilePairs, warningText };
|
||||
}
|
||||
|
||||
export async function handleEnter(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
@@ -62,8 +97,15 @@ export async function handleEnter(
|
||||
免密直通链接: sessionRes.loginUrl,
|
||||
};
|
||||
|
||||
const { profilePairs, warningText } = formatIdentityLines(sessionRes.identity);
|
||||
Object.assign(pairs, profilePairs);
|
||||
|
||||
return {
|
||||
stdout: `====== 协助平台免密会话生成成功 ======\n${printKeyValue(pairs)}\n\n操作提示:\n - 在浏览器中打开以上链接可直接进入协助调试工作台\n - 若要一键落盘到本地企业配置: hose-use assist-platform enter ${corpId} ${sessionRes.isAdmin ? "--admin" : `--staff "${sessionRes.staffName}"`} --save --yes\n`,
|
||||
stdout:
|
||||
`====== 协助平台免密会话生成成功 ======\n${printKeyValue(pairs)}\n` +
|
||||
`${warningText}\n操作提示:\n` +
|
||||
` - 在浏览器中打开以上链接可直接进入协助调试工作台\n` +
|
||||
` - 若要一键落盘到本地企业配置: hose-use assist-platform enter ${corpId} ${sessionRes.isAdmin ? "--admin" : `--staff "${sessionRes.staffName}"`} --save --yes\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
@@ -137,8 +179,11 @@ export async function handleEnter(
|
||||
激活状态: shouldSwitch ? "🎯 已设为当前激活工作企业" : "可随时运行 hose-use corps switch 进行切换",
|
||||
};
|
||||
|
||||
const { profilePairs, warningText } = formatIdentityLines(sessionResult.identity);
|
||||
Object.assign(successPairs, profilePairs);
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 协助企业凭证获取并落盘成功!\n${printKeyValue(successPairs)}\n`,
|
||||
stdout: `[SUCCESS] 协助企业凭证获取并落盘成功!\n${printKeyValue(successPairs)}\n${warningText}`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
|
||||
@@ -46,6 +46,12 @@ export const CorpSessionInfoSchema = z.object({
|
||||
loginTime: z.number().nullable().optional().describe("登录时间戳 (ms)"),
|
||||
expTime: z.number().nullable().optional().describe("过期时间戳 (ms)"),
|
||||
sourceChannel: z.string().nullable().optional().describe("来源渠道 (如 APP, WEB)"),
|
||||
departmentName: z.string().nullable().optional().describe("所属部门名称"),
|
||||
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)"),
|
||||
permissions: z.array(z.string()).nullable().optional().describe("员工功能权限清单"),
|
||||
});
|
||||
export type CorpSessionInfo = z.infer<typeof CorpSessionInfoSchema>;
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import type {
|
||||
AssistPlatformStaff,
|
||||
AssistPlatformTicket,
|
||||
CorporationDetail,
|
||||
StaffRoleItem,
|
||||
} from "./types.js";
|
||||
|
||||
export interface SearchCorporationsApiParams {
|
||||
@@ -379,3 +380,99 @@ export async function approveAssistTicketApi(
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getStaffMeAndRolesApi(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
staffId?: string
|
||||
): Promise<{
|
||||
staff: Record<string, unknown>;
|
||||
permissions: string[];
|
||||
roles: StaffRoleItem[];
|
||||
departmentName?: string;
|
||||
}> {
|
||||
let staff: Record<string, unknown> = {};
|
||||
let permissions: string[] = [];
|
||||
|
||||
try {
|
||||
const meRes = await client
|
||||
.get("api/v1/organization/staffs/me", {
|
||||
searchParams: { corpId },
|
||||
})
|
||||
.json<{
|
||||
value?: {
|
||||
staff?: Record<string, unknown>;
|
||||
permissions?: string[];
|
||||
};
|
||||
}>();
|
||||
if (meRes.value?.staff) {
|
||||
staff = meRes.value.staff;
|
||||
}
|
||||
if (Array.isArray(meRes.value?.permissions)) {
|
||||
permissions = meRes.value.permissions.map(String);
|
||||
}
|
||||
} catch {
|
||||
// 允许容错降级
|
||||
}
|
||||
|
||||
const effectiveStaffId = String(staff.id || staffId || "");
|
||||
|
||||
const roles: StaffRoleItem[] = [];
|
||||
if (effectiveStaffId) {
|
||||
try {
|
||||
const cleanStaffId = effectiveStaffId.startsWith("$") ? effectiveStaffId : `$${effectiveStaffId}`;
|
||||
const rolesRes = await client
|
||||
.get(`api/v1/organization/staffs/${cleanStaffId}/roles`, {
|
||||
searchParams: { corpId },
|
||||
})
|
||||
.json<{
|
||||
items?: Array<{
|
||||
roleDefId?: string;
|
||||
roleDefName?: string;
|
||||
roleDefCode?: string;
|
||||
}>;
|
||||
}>();
|
||||
|
||||
if (Array.isArray(rolesRes.items)) {
|
||||
for (const item of rolesRes.items) {
|
||||
if (item.roleDefName) {
|
||||
roles.push({
|
||||
id: String(item.roleDefId || ""),
|
||||
name: String(item.roleDefName),
|
||||
code: item.roleDefCode ? String(item.roleDefCode) : undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 允许容错降级
|
||||
}
|
||||
}
|
||||
|
||||
let departmentName: string | undefined;
|
||||
const deptId = String(
|
||||
staff.defaultDepartment || (Array.isArray(staff.departments) ? staff.departments[0] : "") || ""
|
||||
);
|
||||
if (deptId) {
|
||||
try {
|
||||
const cleanDeptId = deptId.startsWith("$") ? deptId : `$${deptId}`;
|
||||
const deptRes = await client
|
||||
.get(`api/v1/organization/departments/${cleanDeptId}`, {
|
||||
searchParams: { corpId },
|
||||
})
|
||||
.json<{ value?: { name?: string } }>();
|
||||
if (deptRes.value?.name) {
|
||||
departmentName = deptRes.value.name;
|
||||
}
|
||||
} catch {
|
||||
// 允许容错降级
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
staff,
|
||||
permissions,
|
||||
roles,
|
||||
departmentName,
|
||||
};
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import ky from "ky";
|
||||
import {
|
||||
analyzeStaffRoleRisk,
|
||||
applyAssistTicket,
|
||||
approveAssistTicket,
|
||||
findStaff,
|
||||
generateAssistSession,
|
||||
getCorporationDetail,
|
||||
inspectAssistIdentity,
|
||||
listAssistTickets,
|
||||
searchCorporations,
|
||||
} from "./services.js";
|
||||
@@ -251,4 +253,49 @@ describe("domains/assist-platform - 协助平台业务编排", () => {
|
||||
expect(res.active).toBe(true);
|
||||
expect(res.userName).toBe("谢子豪");
|
||||
});
|
||||
|
||||
describe("analyzeStaffRoleRisk - 高管权限风控识别", () => {
|
||||
it("普通员工不触发高管警示", () => {
|
||||
const risk = analyzeStaffRoleRisk({
|
||||
staffName: "普通员工",
|
||||
isAdmin: false,
|
||||
roleNames: ["普通员工", "销售代表"],
|
||||
permissions: ["INVOICE_READ", "TRAVEL_SUBMIT"],
|
||||
});
|
||||
|
||||
expect(risk.isSeniorExecutive).toBe(false);
|
||||
expect(risk.riskLevel).toBe("NORMAL");
|
||||
expect(risk.seniorTitles).toEqual([]);
|
||||
expect(risk.riskWarning).toBeUndefined();
|
||||
});
|
||||
|
||||
it("命中主管理员角色触发 HIGH 级别风控", () => {
|
||||
const risk = analyzeStaffRoleRisk({
|
||||
staffName: "沈玥妍",
|
||||
isAdmin: true,
|
||||
roleNames: ["主管理员", "财务主管"],
|
||||
permissions: ["SYS_ADMIN", "CORP_PAYMENT_MANAGE"],
|
||||
});
|
||||
|
||||
expect(risk.isSeniorExecutive).toBe(true);
|
||||
expect(risk.riskLevel).toBe("HIGH");
|
||||
expect(risk.seniorTitles).toContain("主管理员");
|
||||
expect(risk.seniorTitles).toContain("财务主管");
|
||||
expect(risk.riskWarning).toContain("沈玥妍");
|
||||
expect(risk.riskWarning).toContain("经理与实施人员严禁借用该身份发起或通过非授权审批");
|
||||
});
|
||||
|
||||
it("具备全系统管理权限或对公付款权限即使无角色名也触发风控", () => {
|
||||
const risk = analyzeStaffRoleRisk({
|
||||
staffName: "特权人员",
|
||||
isAdmin: false,
|
||||
roleNames: [],
|
||||
permissions: ["SYS_ADMIN"],
|
||||
});
|
||||
|
||||
expect(risk.isSeniorExecutive).toBe(true);
|
||||
expect(risk.riskLevel).toBe("MEDIUM");
|
||||
expect(risk.riskWarning).toContain("特权人员");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { KyInstance } from "ky";
|
||||
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 type { CorpConfig } from "../../core/config/types.js";
|
||||
import {
|
||||
approveAssistTicketApi,
|
||||
@@ -8,6 +9,7 @@ import {
|
||||
getAssistTokenApi,
|
||||
getCorporationDetailApi,
|
||||
getStaffApi,
|
||||
getStaffMeAndRolesApi,
|
||||
searchAssistTicketsApi,
|
||||
searchCorporationsApi,
|
||||
type ApproveAssistTicketApiParams,
|
||||
@@ -18,13 +20,157 @@ import {
|
||||
type SearchCorporationsApiResponse,
|
||||
} from "./api.js";
|
||||
import type {
|
||||
AssistIdentityProfile,
|
||||
AssistPlatformCorporation,
|
||||
AssistPlatformSessionResult,
|
||||
AssistPlatformStaff,
|
||||
AssistPlatformTicket,
|
||||
CorporationDetail,
|
||||
StaffRoleItem,
|
||||
} from "./types.js";
|
||||
|
||||
export const PERMISSION_LABEL_MAP: Record<string, string> = {
|
||||
SYS_ADMIN: "系统管理",
|
||||
ROLE_ADMIN: "角色权限管理",
|
||||
CONTACTS_MANAGE: "通讯录管理",
|
||||
CORP_PAYMENT_MANAGE: "对公付款管理",
|
||||
CORPORATE_BANKING: "账户管理-付款账户",
|
||||
CORPORATE_RECEIPT: "账户管理-收款账户",
|
||||
BUDGET_MANAGE: "预算管理",
|
||||
COST_CONTROL_ADMIN: "费控管理",
|
||||
FLOW_ADMIN: "审批流管理",
|
||||
FORM_SPEC_ADMIN: "单据模板管理",
|
||||
AI_APPROVAL_NODE: "AI智能审核管理",
|
||||
INVOICE_MANAGE: "发票管理",
|
||||
INVOICE_REVIEW_QUICK_EXPENSE: "发票复核管理",
|
||||
INVOICE_RISK_CHECK: "发票风险巡检",
|
||||
MALL_MANAGE: "合思商城管理",
|
||||
LOAN_MANAGE: "借款管理",
|
||||
CREDIT_MANAGE: "信用管理",
|
||||
EXTEND_DIMENSION: "扩展档案管理",
|
||||
FEE_TYPE_ADMIN: "费用类型管理",
|
||||
HOME_PAGE_ADMIN: "移动端首页配置",
|
||||
CONSUMER_MATTERS: "申请事项管理",
|
||||
CHECKING_BILL_MANAGE: "对账单管理",
|
||||
OUTPUT_TAX_MANAGE: "销项税管理",
|
||||
SUPPLEMENT_INVOICE: "补充发票管理",
|
||||
VIRTUAL_CARD_MANAGE: "易商卡管理",
|
||||
WAIT_INVOICE_AUTHORIZE: "待开发票管理",
|
||||
RECORD_LINK_ADMIN: "档案关系管理",
|
||||
CORP_AGENCY_EXPENSE: "代垫费用管理",
|
||||
};
|
||||
|
||||
export const SENIOR_ROLE_KEYWORDS = [
|
||||
"总监", "副总", "总经理", "总裁", "CEO", "CFO", "COO", "CTO", "VP",
|
||||
"主管理员", "系统管理员", "财务主管", "财务负责人", "审计主管", "风控主管",
|
||||
"合伙人", "董事长", "董事", "行长", "部长", "处长", "站长", "分管领导", "经理", "主管"
|
||||
];
|
||||
|
||||
export function analyzeStaffRoleRisk(profile: {
|
||||
staffName: string;
|
||||
isAdmin: boolean;
|
||||
roleNames: string[];
|
||||
permissions: string[];
|
||||
}): {
|
||||
isSeniorExecutive: boolean;
|
||||
seniorTitles: string[];
|
||||
riskLevel: "HIGH" | "MEDIUM" | "NORMAL";
|
||||
riskWarning?: string;
|
||||
} {
|
||||
const seniorTitles: string[] = [];
|
||||
|
||||
if (profile.isAdmin && !seniorTitles.includes("企业主管理员")) {
|
||||
seniorTitles.push("企业主管理员");
|
||||
}
|
||||
|
||||
for (const roleName of profile.roleNames) {
|
||||
for (const kw of SENIOR_ROLE_KEYWORDS) {
|
||||
if (roleName.includes(kw) && !seniorTitles.includes(roleName)) {
|
||||
seniorTitles.push(roleName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const hasHighRiskPerms = profile.permissions.some((p) =>
|
||||
["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";
|
||||
|
||||
let riskWarning: string | undefined;
|
||||
if (isSeniorExecutive) {
|
||||
const titleSummary = seniorTitles.length > 0 ? seniorTitles.join(" / ") : "高级系统管理员";
|
||||
riskWarning =
|
||||
`当前协助会话获取的是高阶管理人员身份 [${titleSummary}](${profile.staffName})。` +
|
||||
`该身份拥有高级审批、财务权限或全系统管理权限。经理与实施人员严禁借用该身份发起或通过非授权审批,防范越权误操作!`;
|
||||
}
|
||||
|
||||
return {
|
||||
isSeniorExecutive,
|
||||
seniorTitles,
|
||||
riskLevel,
|
||||
riskWarning,
|
||||
};
|
||||
}
|
||||
|
||||
export async function inspectAssistIdentity(
|
||||
token: string,
|
||||
corpId: string,
|
||||
baseUrl: string = "https://app.ekuaibao.com",
|
||||
fallbackStaffId?: string,
|
||||
fallbackStaffName?: string
|
||||
): Promise<AssistIdentityProfile> {
|
||||
const normalizedBase = baseUrl.replace(/\/+$/, "");
|
||||
const client = ky.create({
|
||||
prefix: normalizedBase,
|
||||
headers: {
|
||||
accesstoken: token,
|
||||
corpid: corpId,
|
||||
accept: "application/json",
|
||||
"content-type": "application/json",
|
||||
},
|
||||
timeout: 10000,
|
||||
});
|
||||
|
||||
const res = await getStaffMeAndRolesApi(client, corpId, fallbackStaffId);
|
||||
const staff = res.staff;
|
||||
const staffId = String(staff.id || fallbackStaffId || "");
|
||||
const staffName = String(staff.name || fallbackStaffName || "企业操作人员");
|
||||
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 roleNames = res.roles.map((r) => r.name);
|
||||
const readablePermissions = res.permissions.map(
|
||||
(p) => `${PERMISSION_LABEL_MAP[p] || p} (${p})`
|
||||
);
|
||||
|
||||
const riskAnalysis = analyzeStaffRoleRisk({
|
||||
staffName,
|
||||
isAdmin,
|
||||
roleNames,
|
||||
permissions: res.permissions,
|
||||
});
|
||||
|
||||
return {
|
||||
staffId,
|
||||
staffName,
|
||||
cellphone,
|
||||
email,
|
||||
code,
|
||||
isAdmin,
|
||||
departmentId: String(staff.defaultDepartment || ""),
|
||||
departmentName: res.departmentName,
|
||||
roles: res.roles,
|
||||
roleNames,
|
||||
permissions: res.permissions,
|
||||
readablePermissions,
|
||||
...riskAnalysis,
|
||||
};
|
||||
}
|
||||
|
||||
export async function searchCorporations(
|
||||
client: KyInstance,
|
||||
params: SearchCorporationsApiParams = {}
|
||||
@@ -135,6 +281,20 @@ export async function generateAssistSession(
|
||||
staffId: resolvedStaffId,
|
||||
});
|
||||
|
||||
// 深度解析当前会话人员身份、所属部门与角色权限画像(包含高管权限风控检测)
|
||||
let identity: AssistIdentityProfile | undefined;
|
||||
try {
|
||||
identity = await inspectAssistIdentity(
|
||||
tokenRes.token,
|
||||
corpId,
|
||||
tokenRes.baseUrl,
|
||||
resolvedStaffId,
|
||||
resolvedStaffName
|
||||
);
|
||||
} catch {
|
||||
// 允许容错降级
|
||||
}
|
||||
|
||||
return {
|
||||
token: tokenRes.token,
|
||||
loginUrl: tokenRes.loginUrl,
|
||||
@@ -142,8 +302,9 @@ export async function generateAssistSession(
|
||||
ticketId,
|
||||
corporationId: corpId,
|
||||
isAdmin,
|
||||
staffId: resolvedStaffId,
|
||||
staffName: resolvedStaffName,
|
||||
staffId: identity?.staffId || resolvedStaffId,
|
||||
staffName: identity?.staffName || resolvedStaffName,
|
||||
identity,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -181,6 +342,24 @@ export async function importAssistSessionToLocal(
|
||||
|
||||
const corpConfig = await importFromLink(linkToImport, importOptions);
|
||||
|
||||
// 注入完整身份画像与角色权限风控元数据并保存落盘
|
||||
if (sessionResult.identity) {
|
||||
const ident = sessionResult.identity;
|
||||
corpConfig.session = {
|
||||
...corpConfig.session,
|
||||
staffName: ident.staffName || corpConfig.session?.staffName,
|
||||
cellphone: ident.cellphone || corpConfig.session?.cellphone,
|
||||
isAdmin: ident.isAdmin ?? corpConfig.session?.isAdmin,
|
||||
departmentName: ident.departmentName,
|
||||
roles: ident.roleNames,
|
||||
roleTitles: ident.seniorTitles.length > 0 ? ident.seniorTitles.join(" / ") : undefined,
|
||||
isSeniorExecutive: ident.isSeniorExecutive,
|
||||
riskLevel: ident.riskLevel,
|
||||
permissions: ident.permissions,
|
||||
};
|
||||
saveCorpConfig(corpConfig, importOptions.enterprisesDir);
|
||||
}
|
||||
|
||||
return {
|
||||
sessionResult,
|
||||
corpConfig,
|
||||
|
||||
@@ -48,6 +48,31 @@ export const AssistPlatformStaffSchema = z.object({
|
||||
});
|
||||
export type AssistPlatformStaff = z.infer<typeof AssistPlatformStaffSchema>;
|
||||
|
||||
export interface StaffRoleItem {
|
||||
id: string;
|
||||
name: string;
|
||||
code?: string;
|
||||
}
|
||||
|
||||
export interface AssistIdentityProfile {
|
||||
staffId: string;
|
||||
staffName: string;
|
||||
cellphone?: string;
|
||||
email?: string;
|
||||
code?: string;
|
||||
isAdmin: boolean;
|
||||
departmentId?: string;
|
||||
departmentName?: string;
|
||||
roles: StaffRoleItem[];
|
||||
roleNames: string[];
|
||||
permissions: string[];
|
||||
readablePermissions: string[];
|
||||
isSeniorExecutive: boolean;
|
||||
seniorTitles: string[];
|
||||
riskLevel: "HIGH" | "MEDIUM" | "NORMAL";
|
||||
riskWarning?: string;
|
||||
}
|
||||
|
||||
export const AssistPlatformSessionResultSchema = z.object({
|
||||
token: z.string().describe("临时协助会话 Token"),
|
||||
loginUrl: z.string().url().describe("免密直通登录目标 URL"),
|
||||
@@ -57,6 +82,7 @@ export const AssistPlatformSessionResultSchema = z.object({
|
||||
isAdmin: z.boolean().describe("是否为管理员模式"),
|
||||
staffId: z.string().optional().describe("用户身份模式下的员工工号"),
|
||||
staffName: z.string().optional().describe("用户姓名"),
|
||||
identity: z.custom<AssistIdentityProfile>().optional().describe("人员身份画像与角色权限风控元数据"),
|
||||
});
|
||||
export type AssistPlatformSessionResult = z.infer<typeof AssistPlatformSessionResultSchema>;
|
||||
|
||||
|
||||
Reference in new issue
Block a user