fix: 拒绝歧义员工身份与业务字段写入

协助登录按唯一启用员工解析姓名,新增 --staff-id 及完整参数解析覆盖;同名不同员工在换票前拒绝。DataLink 筛选、赋值与 JSON 安全合并共用物理键优先的唯一字段解析,未知原始字段维持透传。
补充无换票/无写入请求的负例、精确目标正例,恢复 CLI 测试环境变量并清理临时目录,同步模块说明。

验证:bun test 902 通过、0 失败;bun run check、git diff --check 通过。全量验证使用隔离配置和数据库,没有调用真实企业接口。
This commit is contained in:
gitea committed 2026-10-29 18:10:21 +08:00
1 parent bb703620f2
commit 9916936eae
12 files changed
+167 -42

No files matched your search

+1 -1
View File
@@ -831,7 +831,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
"forward": "transfer"
},
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 days day to recipient target remarks comment corp", "value"),
...flagList("token t user name u hose-token jwt ticket ticket-id auth-code staff staff-id staffId alias corp-name count limit n start offset state status corpid id keyword query q message msg reason matter hours hour duration days day to recipient target remarks comment corp", "value"),
...flagList("all a logout admin save import persist switch current overwrite candidates list-candidates", "boolean")
}
}
+21 -1
View File
@@ -1,8 +1,9 @@
import { describe, expect, it, beforeEach } from "bun:test";
import { describe, expect, it, beforeEach, afterEach } from "bun:test";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { handleAssistPlatformCommand } from "./assist-platform/index.js";
import { parseArgs } from "../parser.js";
import {
saveAssistPlatformSession,
clearAssistPlatformSession,
@@ -28,14 +29,33 @@ function createMockRuntime(enterprisesDir: string): CliRuntime {
}
describe("CLI Commands - assist-platform (合思协助平台)", () => {
it("enter 的 staff-id 通过完整解析并选择员工模式预览", async () => {
const parsed = parseArgs(["assist-platform", "enter", "corp", "--staff-id", "staff-two", "--dry-run", "--json"]);
const result = await handleAssistPlatformCommand(parsed, { jsonMode: true } as CliRuntime);
expect(result.exitCode).toBe(0);
expect(JSON.parse(result.stdout).changes).toMatchObject({ staffId: "staff-two", isAdmin: false });
});
it("enter 不允许管理员模式覆盖显式员工 ID", async () => {
const parsed = parseArgs(["assist-platform", "enter", "corp", "--staff-id", "staff-two", "--admin", "--dry-run"]);
await expect(handleAssistPlatformCommand(parsed, {} as CliRuntime)).rejects.toThrow("不能与");
});
let tempDir: string;
let previousStateDir: string | undefined;
beforeEach(() => {
previousStateDir = process.env.HOSE_STATE_DIR;
tempDir = mkdtempSync(join(tmpdir(), "hose-assist-test-"));
process.env.HOSE_STATE_DIR = tempDir;
clearAssistPlatformSession();
});
afterEach(() => {
if (previousStateDir === undefined) delete process.env.HOSE_STATE_DIR;
else process.env.HOSE_STATE_DIR = previousStateDir;
rmSync(tempDir, { recursive: true, force: true });
});
it("assist-platform help 输出完整使用指南与子命令", async () => {
const runtime = createMockRuntime(tempDir);
const parsed: CliParsedArgs = {
+10 -5
View File
@@ -60,16 +60,18 @@ export async function handleEnter(
if (!corpId) {
return {
stdout: "",
stderr: "用法: hose-use assist-platform enter <企业ID> [--admin] [--staff <姓名>] [--save] [--switch]\n示例: hose-use assist-platform enter Cxa3oOtQi2eS$g --staff 李志财 --save --yes\n",
stderr: "用法: hose-use assist-platform enter <企业ID> [--admin | --staff <姓名> | --staff-id <ID>] [--save] [--switch]\n示例: hose-use assist-platform enter Cxa3oOtQi2eS$g --staff 李志财 --save --yes\n",
exitCode: 1,
};
}
const ticketId = stringOption(parsed.options, ["ticket", "ticket-id", "auth-code"]);
const staffName = stringOption(parsed.options, ["staff", "user", "name"]);
const staffId = stringOption(parsed.options, ["staff-id", "staffId"]);
const forceAdmin = booleanOption(parsed.options, ["admin"]);
// 如果显式指定了 staffName 且未显式指定 --admin,则为用户模式;否则默认为管理员模式
const isAdmin = forceAdmin || !staffName;
if (forceAdmin && (staffName || staffId)) throw new BusinessError("--admin 不能与 --staff / --staff-id 同时使用");
// 如果显式指定了 staffName/staffId 且未显式指定 --admin,则为用户模式;否则默认为管理员模式
const isAdmin = forceAdmin || !(staffName || staffId);
const shouldSave = booleanOption(parsed.options, ["save", "import", "persist"]);
const shouldSwitch = booleanOption(parsed.options, ["switch", "current"]);
@@ -88,6 +90,7 @@ export async function handleEnter(
corpId,
isAdmin,
staffName: staffName || null,
staffId: staffId || null,
ticketId: ticketId || "自动选择最新有效工单",
save: shouldSave || shouldSwitch,
switchCurrent: shouldSwitch,
@@ -105,6 +108,7 @@ export async function handleEnter(
ticketId,
isAdmin,
staffName,
staffId,
});
if (runtime.jsonMode) {
@@ -133,14 +137,14 @@ export async function handleEnter(
`====== 协助平台免密会话生成成功 ======\n${printKeyValue(pairs)}\n` +
`${warningText}\n操作提示:\n` +
` - 在浏览器中打开以上链接可直接进入协助调试工作台\n` +
` - 若要一键落盘到本地企业配置: hose-use assist-platform enter ${corpId} ${sessionRes.isAdmin ? "--admin" : `--staff "${sessionRes.staffName}"`} --save --yes\n`,
` - 若要一键落盘到本地企业配置: hose-use assist-platform enter ${corpId} ${sessionRes.isAdmin ? "--admin" : `--staff-id "${sessionRes.staffId}"`} --save --yes\n`,
stderr: "",
exitCode: 0,
};
}
// 2. 要求持久化落盘 / 切换为工作企业
const nextConfirmCmd = `hose-use assist-platform enter ${corpId} ${isAdmin ? "--admin" : `--staff "${staffName}"`} --save ${shouldSwitch ? "--switch " : ""}--yes`;
const nextConfirmCmd = `hose-use assist-platform enter ${corpId} ${isAdmin ? "--admin" : staffId ? `--staff-id "${staffId}"` : `--staff "${staffName}"`} --save ${shouldSwitch ? "--switch " : ""}--yes`;
requireMutationConfirmation(
parsed,
runtime,
@@ -153,6 +157,7 @@ export async function handleEnter(
ticketId,
isAdmin,
staffName,
staffId,
saveName,
overwrite: overwrite ?? true,
});
@@ -96,6 +96,7 @@ function printHelp(): CliResult {
--token, -t <TOKEN> 显式指定当前操作使用的协助平台 Token
--admin 指定使用企业管理员模式换取免密链接(默认)
--staff <员工姓名> 指定使用特定员工身份换取免密链接
--staff-id <员工ID> 显式指定唯一员工,避免同名歧义
--save 一键将换取的免密会话持久化落盘至本地企业列表(自动提取 OpenAPI 密钥)
--switch 配合 --save,导入后自动切换为当前激活工作企业
--json 输出结构化 JSON 格式结果
@@ -29,6 +29,8 @@
## 会话生成、导入与身份完整度
- `enter --staff <姓名>` 优先精确姓名且必须定位到唯一启用员工,重复行按员工 ID 去重;多个候选会在换票前拒绝。可用 `--staff-id <员工ID>` 明确目标并跳过姓名搜索;`--admin` 不能与员工选项组合。
- `assist-platform enter <corpId> --dry-run` 在换票、身份查询和落盘前返回预览;无论是否带 `--save` / `--switch`,均不需要协助平台登录,也不会发出网络请求。
- `--save --yes` 导入后同步注册当前企业上下文;`--switch` 仅在实际切换成功后输出 `switched: true`。失败时说明配置已保存并提示重试切换。
- 生成成功的文本与 JSON 明确交付会话 Token 和可用免密链接,使用 CLI 受控凭证输出机制;捕获的诊断日志和错误继续统一脱敏。
+8 -1
View File
@@ -285,7 +285,14 @@ export async function generateAssistSession(
`在企业 [${corpId}] 中未找到名为 "${resolvedStaffName}" 的员工`
);
}
const targetStaff = staffList[0];
const activeStaff = staffList.filter((staff) => staff.active !== false && staff.id);
const exact = activeStaff.filter((staff) => staff.name === resolvedStaffName);
const candidates = [...new Map((exact.length ? exact : activeStaff).map((staff) => [staff.id, staff])).values()];
if (candidates.length > 1) {
throw new BusinessError(`匹配到多个员工 [${resolvedStaffName}],请使用 --staff-id 指定唯一员工 ID`);
}
const targetStaff = candidates[0];
if (!targetStaff) throw new NotFoundError(`在企业 [${corpId}] 中未找到可用员工 [${resolvedStaffName}]`);
resolvedStaffId = targetStaff.id;
resolvedStaffName = targetStaff.name;
}
@@ -0,0 +1,46 @@
import { afterEach, expect, test } from "bun:test";
import ky from "ky";
import { generateAssistSession } from "./services.js";
const originalFetch = globalThis.fetch;
afterEach(() => { globalThis.fetch = originalFetch; });
function fixture(staff: Array<{ id: string; name: string; active?: boolean }>) {
const requests: Array<{ path: string; body: Record<string, unknown> }> = [];
// Identity probing is separate from the assist client; keep it offline too.
globalThis.fetch = (async () => Response.json({})) as unknown as typeof fetch;
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);
const body = await request.json() as Record<string, unknown>;
requests.push({ path: new URL(request.url).pathname, body });
return request.url.endsWith("/getStaff")
? Response.json({ items: staff })
: Response.json({ value: { token: "fake", loginUrl: "https://tenant.invalid/login", baseUrl: "https://tenant.invalid" } });
} });
return { client, requests };
}
test("同名不同员工不会请求任意一人的免密凭证", async () => {
const { client, requests } = fixture([{ id: "one", name: "同名" }, { id: "two", name: "同名" }]);
await expect(generateAssistSession(client, { corpId: "corp", ticketId: "ticket", staffName: "同名" })).rejects.toThrow("--staff-id");
expect(requests.map(r => r.path)).toEqual(["/api/assistPlatform/getStaff"]);
});
test("重复查询行按员工 ID 去重;唯一精确姓名优先于模糊候选", async () => {
const { client, requests } = fixture([{ id: "one", name: "张三" }, { id: "one", name: "张三" }, { id: "two", name: "张三丰" }]);
await generateAssistSession(client, { corpId: "corp", ticketId: "ticket", staffName: "张三" });
expect(requests.at(-1)?.body.staffId).toBe("one");
});
test("停用员工不会被选为换票目标", async () => {
const { client, requests } = fixture([{ id: "one", name: "张三", active: false }]);
await expect(generateAssistSession(client, { corpId: "corp", ticketId: "ticket", staffName: "张三" })).rejects.toThrow("未找到可用员工");
expect(requests).toHaveLength(1);
});
test("显式员工 ID 跳过姓名搜索并按该 ID 换票", async () => {
const { client, requests } = fixture([]);
await generateAssistSession(client, { corpId: "corp", ticketId: "ticket", staffId: "two" });
expect(requests).toHaveLength(1);
expect(requests[0].body).toEqual({ ticketId: "ticket", corporationId: "corp", isAdmin: false, staffId: "two" });
});
+1
View File
@@ -62,6 +62,7 @@ hose-use platform imports <应用 ID|名称> <对象 ID|名称>
- `audit --expect="字段 ~= 期望值 [+- 容差]"`:基线数值离群诊断,自动识别并列出偏离基准值的异常记录明细与差额。
- `record update <应用> <业务对象> [--where="条件"] --set="字段=值" [--dry-run] [--yes]`:声明式原地批量修改,支持中文字段标签解析与智能类型转换,通过 `--dry-run` 预览拟更新记录与合并后字段,追加 `--yes` 真正执行。
- `record get` 支持直传 `<记录ID>` 免传应用与业务对象。
- 筛选、`--set` 与 JSON 安全合并共用字段解析:明确物理键优先,标签或模糊匹配必须唯一;歧义在写入前拒绝,须改用完整物理字段名。未知原始字段继续保持兼容透传,`--raw` 仍直接透传原始补丁。
- `record edit` 与 `record batch-edit` 默认启用 **Read-Modify-Write 安全全量合并**(保留全部 `E_<entityId>_*` 字段、将嵌套引用对象归一化为字符串 ID、保留 `active` 与 `visibility` 结构,支持字段短名/中文标签映射);仅当显式传入 `--raw` 时才直接透传原始补丁。
- `records --all` 自动按 `500` 条/页循环拉取全量台账记录。
- `audit` 一键巡检必填/指定字段缺失、引用已停用档案以及跨台账同名字段同步差异,并输出 `suggestedPatches`。
+3 -12
View File
@@ -1,5 +1,6 @@
import { z } from "zod";
import type { KyInstance } from "ky";
import { resolveDatalinkField } from "./fields.js";
import {
DatalinkEntitySchema,
DatalinkPlatformDetailSchema,
@@ -356,19 +357,9 @@ export function resolveEntityFieldKey(
existingForm: Record<string, unknown> = {}
): { key: string; fieldDef?: DatalinkField } {
const bareEntityId = entityId.startsWith("$") ? entityId.slice(1) : entityId;
const exactByName = fields.find((f) => f.name === inputKey);
if (exactByName) {
return { key: exactByName.name, fieldDef: exactByName };
}
const field = resolveDatalinkField(fields, bareEntityId, inputKey);
if (field) return { key: field.name, fieldDef: field };
const prefixedKey = `E_${bareEntityId}_${inputKey}`;
const byPrefixedName = fields.find((f) => f.name === prefixedKey);
if (byPrefixedName) {
return { key: byPrefixedName.name, fieldDef: byPrefixedName };
}
const byLabel = fields.find((f) => f.label === inputKey);
if (byLabel && byLabel.name) {
return { key: byLabel.name, fieldDef: byLabel };
}
if (inputKey.startsWith(`E_${bareEntityId}_`)) {
return { key: inputKey };
}
+46
View File
@@ -0,0 +1,46 @@
import { expect, test } from "bun:test";
import ky from "ky";
import { DatalinkEntitySchema } from "./types.js";
import { buildSafeRecordEditPayload, compileRecordPredicate, parseSetClause, safeEditRecord } from "./services.js";
const entity = DatalinkEntitySchema.parse({ id: "entity", fields: [
{ name: "E_entity_a", label: "金额", type: "number" },
{ name: "E_entity_b", label: "金额", type: "number" },
] });
test("筛选、赋值和 JSON 安全合并均拒绝歧义标签", () => {
expect(() => compileRecordPredicate("金额 == 10", entity)).toThrow("歧义");
expect(() => parseSetClause("金额=10", entity)).toThrow("歧义");
expect(() => buildSafeRecordEditPayload({ entityId: entity.id, recordId: "r", fields: entity.fields, patchForm: { 金额: 10 } })).toThrow("歧义");
});
test("明确物理键即使与另一个字段的标签冲突,也保持唯一目标", () => {
const collision = DatalinkEntitySchema.parse({ id: "entity", fields: [
{ name: "E_entity_a", label: "E_entity_b", type: "number" },
{ name: "E_entity_b", label: "金额", type: "number" },
] });
expect(parseSetClause("E_entity_b=10", collision)).toEqual({ E_entity_b: 10 });
expect(compileRecordPredicate("E_entity_b == 10", collision)({ E_entity_a: 1, E_entity_b: 10 })).toBe(true);
const payload = buildSafeRecordEditPayload({ entityId: entity.id, recordId: "r", fields: collision.fields, patchForm: { E_entity_b: 10 } });
expect(payload.form.E_entity_b).toBe(10);
expect(payload.form.E_entity_a).toBeUndefined();
});
test("模糊匹配不唯一时拒绝;物理短名、唯一标签和未知字段兼容保留", () => {
const fields = DatalinkEntitySchema.parse({ id: "entity", fields: [
{ name: "E_entity_a", label: "原始金额", type: "number" },
{ name: "E_entity_b", label: "折算金额", type: "number" },
] });
expect(() => parseSetClause("金额=10", fields)).toThrow("歧义");
expect(parseSetClause("a=10,折算金额=20,active=true", fields)).toEqual({ E_entity_a: 10, E_entity_b: 20, active: true });
});
test("安全编辑遇到歧义字段在发出写请求前终止", async () => {
const requests: string[] = [];
const client = ky.create({ prefix: "https://tenant.invalid", fetch: async input => {
requests.push(String(input));
return Response.json({});
} });
await expect(safeEditRecord(client, "corp", { entityId: entity.id, recordId: "r", detail: { id: "r" }, fields: entity.fields, patchForm: { 金额: 10 } })).rejects.toThrow("歧义");
expect(requests).toEqual([]);
});
+24
View File
@@ -0,0 +1,24 @@
import { ValidationError } from "../../core/errors.js";
import type { DatalinkField } from "./types.js";
/** 物理键优先;标签和模糊匹配必须指向唯一物理字段。未知字段由调用方决定是否透传。 */
export function resolveDatalinkField(
fields: DatalinkField[],
entityId: string,
query: string
): DatalinkField | undefined {
const key = query.trim().toLowerCase();
if (!key) return undefined;
const prefix = `e_${entityId.replace(/^\$/, "").toLowerCase()}_`;
const unique = (matches: DatalinkField[]): DatalinkField | undefined => {
const byName = new Map(matches.map((field) => [field.name, field]));
if (byName.size > 1) {
throw new ValidationError(`字段存在歧义: ${query},请使用完整字段名`);
}
return byName.values().next().value;
};
return unique(fields.filter((field) => field.name.toLowerCase() === key))
?? unique(fields.filter((field) => field.name.toLowerCase() === prefix + key))
?? unique(fields.filter((field) => field.label?.toLowerCase() === key))
?? unique(fields.filter((field) => field.label?.toLowerCase().includes(key)));
}
+4 -22
View File
@@ -1,6 +1,7 @@
import type { KyInstance } from "ky";
import * as api from "./api.js";
import { ValidationError } from "../../core/errors.js";
import { resolveDatalinkField } from "./fields.js";
import type {
DatalinkEntity,
DatalinkField,
@@ -990,19 +991,7 @@ export function resolveEntityField(
entity: DatalinkEntity,
query: string
): DatalinkField | undefined {
const q = query.trim().toLowerCase();
const bareQ = q.replace(/^e_[^_]+_/, "").replace(/^e_/, "");
return (
entity.fields.find(
(f) =>
f.name.toLowerCase() === q ||
f.label?.toLowerCase() === q ||
f.name.toLowerCase() === `e_${entity.id.toLowerCase()}_${bareQ}` ||
f.name.replace(/^e_[^_]+_/, "").toLowerCase() === bareQ
) ||
entity.fields.find((f) => f.label?.toLowerCase().includes(q))
);
return resolveDatalinkField(entity.fields, entity.id, query);
}
/**
@@ -1316,15 +1305,8 @@ function predicateLiteral(raw: string): string | number | boolean | null {
}
function predicateField(entity: DatalinkEntity, query: string): DatalinkField | string {
const key = query.trim().toLowerCase();
const candidates = entity.fields.filter(f =>
f.name.toLowerCase() === key || f.label?.toLowerCase() === key ||
f.name.toLowerCase() === `e_${entity.id.replace(/^\$/, "").toLowerCase()}_${key}`
);
if (!candidates.length && ["id", "recordId", "active", "name", "code", "createTime", "updateTime", "entityId"].includes(query)) return query;
const matches = candidates.length ? candidates : entity.fields.filter(f => f.label?.toLowerCase().includes(key));
if (matches.length > 1) throw new ValidationError(`筛选字段存在歧义: ${query},请使用完整字段名`);
if (matches.length === 1) return matches[0];
const field = resolveEntityField(entity, query);
if (field) return field;
if (["id", "recordId", "active", "name", "code", "createTime", "updateTime", "entityId"].includes(query)) return query;
throw new ValidationError(`未知筛选字段: ${query}`);
}