WHMSLIVE 部署验证企微HR主数据镜像

这个提交包含在:
2026-05-18 20:10:00 +08:00
父节点 27968fba49
当前提交 e10b1cd091
共修改 14 个文件,包含 258 行新增和 67 行删除
@@ -300,6 +300,10 @@ function hrTokenCandidates(config) {
];
}
function canFallbackToAgentSecret(error) {
return error instanceof WecomHrMasterSyncError && error.code === "wecom_errcode_48009";
}
function normalizeDepartmentMap(payload) {
const map = new Map();
const departments = Array.isArray(payload?.department) ? payload.department : [];
@@ -419,6 +423,78 @@ function normalizeWecomHrProfile({ contact = {}, staff = {}, departmentMap = new
return profile;
}
async function fetchContactProfilesInput({ config, token, userids, limit, fetchImpl, timeoutMs }) {
const departmentMap = await fetchDepartmentMap({
accessToken: token.accessToken,
fetchImpl,
timeoutMs,
});
const departmentId = toSafeString(config.wecomContactDefaultDepartmentId, 32) || "1";
const contacts = userids.length
? await Promise.all(userids.map((userid) => fetchContactMember({
accessToken: token.accessToken,
userid,
fetchImpl,
timeoutMs,
})))
: await listContactMembers({
accessToken: token.accessToken,
departmentId,
limit,
fetchImpl,
timeoutMs,
});
return { departmentMap, contacts, tokenSource: token.source };
}
async function fetchContactProfilesInputWithFallback({ config, contactToken, userids, limit, fetchImpl, timeoutMs }) {
try {
return await fetchContactProfilesInput({
config,
token: contactToken,
userids,
limit,
fetchImpl,
timeoutMs,
});
} catch (error) {
if (!canFallbackToAgentSecret(error) || contactToken.source === "WECOM_AGENT_SECRET_FALLBACK") {
throw error;
}
const fallback = await getTokenFromCandidates({
config,
candidates: [{ source: "WECOM_AGENT_SECRET_FALLBACK", secret: config?.wecomAgentSecret }],
timeoutMs,
fetchImpl,
});
if (!fallback.ok) {
throw error;
}
try {
return await fetchContactProfilesInput({
config,
token: fallback,
userids,
limit,
fetchImpl,
timeoutMs,
});
} catch (fallbackError) {
if (canFallbackToAgentSecret(fallbackError)) {
fallbackError.details = {
...(fallbackError.details ?? {}),
firstTokenSource: contactToken.source,
fallbackTokenSource: fallback.source,
};
}
throw fallbackError;
}
}
}
async function fetchWecomHrProfiles({ config, userids, limit, fetchImpl = fetch }) {
const timeoutMs = config.wecomRequestTimeoutMs ?? 10000;
const contactToken = await getTokenFromCandidates({
@@ -441,29 +517,17 @@ async function fetchWecomHrProfiles({ config, userids, limit, fetchImpl = fetch
throw new WecomHrMasterSyncError(hrToken.code, hrToken.message, { missing: hrToken.missing });
}
const departmentMap = await fetchDepartmentMap({
accessToken: contactToken.accessToken,
const contactInput = await fetchContactProfilesInputWithFallback({
config,
contactToken,
userids,
limit,
fetchImpl,
timeoutMs,
});
const departmentId = toSafeString(config.wecomContactDefaultDepartmentId, 32) || "1";
const contacts = userids.length
? await Promise.all(userids.map((userid) => fetchContactMember({
accessToken: contactToken.accessToken,
userid,
fetchImpl,
timeoutMs,
})))
: await listContactMembers({
accessToken: contactToken.accessToken,
departmentId,
limit,
fetchImpl,
timeoutMs,
});
const profiles = [];
for (const contact of contacts) {
for (const contact of contactInput.contacts) {
const userid = toSafeString(contact.userid, 128);
if (!userid) continue;
const staff = await fetchHrStaffInfo({
@@ -472,13 +536,13 @@ async function fetchWecomHrProfiles({ config, userids, limit, fetchImpl = fetch
fetchImpl,
timeoutMs,
});
profiles.push(normalizeWecomHrProfile({ contact, staff, departmentMap }));
profiles.push(normalizeWecomHrProfile({ contact, staff, departmentMap: contactInput.departmentMap }));
}
return {
profiles,
tokenSource: {
contact: contactToken.source,
contact: contactInput.tokenSource,
hr: hrToken.source,
},
};
@@ -2,11 +2,20 @@ const {
maskEmail,
maskExternalUserId,
maskPhone,
fetchWecomHrProfiles,
normalizeWecomHrProfile,
__testables,
} = require("../../src/services/integrations/wecomHrMaster");
describe("wecom HR master sync helpers", () => {
function jsonResponse(payload, status = 200) {
return {
ok: status >= 200 && status < 300,
status,
json: async () => payload,
};
}
it("normalizes contact and HR assistant data without leaking full sensitive values in summary", () => {
const departmentMap = new Map([
["1", { externalId: "1", name: "研发部" }],
@@ -101,4 +110,67 @@ describe("wecom HR master sync helpers", () => {
expect(changes.email.before).toBe(maskEmail("[email protected]"));
expect(changes.externalUserId.after).toBe(maskExternalUserId("oa_smoke002"));
});
it("falls back to the authorized app secret when the contact secret is forbidden for read APIs", async () => {
const calls = [];
const fetchImpl = async (url, init = {}) => {
const parsed = new URL(String(url));
calls.push({ path: parsed.pathname, token: parsed.searchParams.get("access_token") });
if (parsed.pathname === "/cgi-bin/gettoken") {
const secret = parsed.searchParams.get("corpsecret");
if (secret === "contact-secret-whms-fallback") {
return jsonResponse({ errcode: 0, access_token: "contact-token", expires_in: 7200 });
}
if (secret === "agent-secret-whms-fallback") {
return jsonResponse({ errcode: 0, access_token: "agent-token", expires_in: 7200 });
}
if (secret === "hr-secret-whms-fallback") {
return jsonResponse({ errcode: 0, access_token: "hr-token", expires_in: 7200 });
}
}
if (parsed.pathname === "/cgi-bin/department/list" && parsed.searchParams.get("access_token") === "contact-token") {
return jsonResponse({ errcode: 48009, errmsg: "api forbidden for contact assistant" });
}
if (parsed.pathname === "/cgi-bin/department/list" && parsed.searchParams.get("access_token") === "agent-token") {
return jsonResponse({ errcode: 0, department: [{ id: 1, name: "管理部", parentid: 0 }] });
}
if (parsed.pathname === "/cgi-bin/user/get" && parsed.searchParams.get("access_token") === "agent-token") {
return jsonResponse({
errcode: 0,
userid: "oa_smoke002",
name: "测试员工",
mobile: "19912345678",
email: "[email protected]",
department: [1],
enable: 1,
});
}
if (parsed.pathname === "/cgi-bin/hr/get_staff_info" && parsed.searchParams.get("access_token") === "hr-token") {
expect(init.method).toBe("POST");
return jsonResponse({ errcode: 0, staff_info: [{ fieldid: "在职状态", value: "在职" }] });
}
return jsonResponse({ errcode: 40001, errmsg: "unexpected mock request" });
};
const result = await fetchWecomHrProfiles({
config: {
wecomCorpId: "corp-whms-fallback",
wecomAgentId: "1000002",
wecomContactSecret: "contact-secret-whms-fallback",
wecomAgentSecret: "agent-secret-whms-fallback",
wecomHrAssistantSecret: "hr-secret-whms-fallback",
wecomContactDefaultDepartmentId: "1",
},
userids: ["oa_smoke002"],
limit: 1,
fetchImpl,
});
expect(result.tokenSource.contact).toBe("WECOM_AGENT_SECRET_FALLBACK");
expect(result.tokenSource.hr).toBe("WECOM_HR_ASSISTANT_SECRET");
expect(result.profiles).toHaveLength(1);
expect(result.profiles[0].externalUserId).toBe("oa_smoke002");
expect(calls.some((call) => call.path === "/cgi-bin/department/list" && call.token === "contact-token")).toBe(true);
expect(calls.some((call) => call.path === "/cgi-bin/department/list" && call.token === "agent-token")).toBe(true);
});
});