fix: stabilize auth identity, record operations, and workflow diagnostics

This commit is contained in:
gitea committed 2026-10-15 14:54:10 +08:00
1 parent c74fdda7da
commit 7ec369f77e
36 files changed
+1021 -337

No files matched your search

+6
View File
@@ -46,3 +46,9 @@ src/core/
- 业务域如果需要缓存,统一使用 `core/cache/` 提供的多级缓存门面
- 业务域如果需要持久化数据,统一接入 `core/db/` 并注册版本迁移
## 员工换签与默认会话
- `getCorpProvisionalAuthLink` 显式指定 `staffId` 时需要已配置的 OpenAPI 密钥;旧员工的 Session Token 不会伪装成目标员工。
- 临时换签只返回独立链接,不修改默认身份、Token 或缓存。只有 `persistStaff=true` 才把目标身份、Token、有效期和员工名称一起持久化;同一身份的普通续期保持原行为。
- 校验签发身份与目标一致,并在保存成功后更新内存配置;失败时不留下半更新的内存身份。
+80
View File
@@ -0,0 +1,80 @@
import { afterEach, describe, expect, it, spyOn } from "bun:test";
import { getCorpProvisionalAuthLink } from "./openapi-onboard.js";
import * as openapi from "./openapi-v1.js";
import * as loader from "../config/loader.js";
import * as links from "./link-import.js";
import type { CorpConfig } from "../config/types.js";
describe("provisional link identity isolation", () => {
const spies: Array<{ mockRestore(): void }> = [];
afterEach(() => { while (spies.length) spies.pop()!.mockRestore(); });
function setup(uid = "corp:B") {
const corp: CorpConfig = {
id: "corp", name: "Mock", source: "openapi", baseUrl: "https://example.test",
staffId: "corp:A", staffName: "A", session: { staffName: "A" },
credentials: { accessToken: "token-A", corpId: "corp", staffId: "corp:A", appKey: "key", appSecurity: "security" },
};
const token = spyOn(openapi, "fetchHoseOpenApiAccessToken").mockResolvedValue("openapi");
const sign = spyOn(openapi, "fetchHoseProvisionalAuth").mockResolvedValue({ uid, token: "token-B", url: "https://example.test/link", expiresIn: 7200, expiresAt: Date.now() + 7200000 });
const save = spyOn(loader, "saveCorpConfig").mockReturnValue("/mock/corp.json");
const invalidate = spyOn(links, "invalidateCorpSubdomainTokenCaches").mockImplementation(() => {});
spies.push(token, sign, save, invalidate);
return { corp, save, sign, invalidate };
}
it("does not mutate or save the default identity for a temporary staff link", async () => {
const { corp, save, invalidate } = setup();
const before = structuredClone(corp);
const result = await getCorpProvisionalAuthLink(corp, { staffId: "corp:B", staffName: "B" });
expect(result.staffId).toBe("corp:B");
expect(result.staffName).toBe("B");
expect(corp).toEqual(before);
expect(save).not.toHaveBeenCalled();
expect(invalidate).not.toHaveBeenCalled();
});
it("persists token and normalized identity together and clears the old staff name", async () => {
const { corp, save } = setup();
const result = await getCorpProvisionalAuthLink(corp, { staffId: "B", persistStaff: true });
expect(result.staffName).toBeUndefined();
expect(corp.credentials.accessToken).toBe("token-B");
expect(corp.credentials.staffId).toBe("corp:B");
expect(corp.staffId).toBe("corp:B");
expect(corp.staffName).toBeUndefined();
expect(corp.session?.staffName).toBeUndefined();
expect(save.mock.calls[0]?.[0].credentials.staffId).toBe("corp:B");
});
it("keeps ordinary renewal of the same staff working", async () => {
const { corp, save } = setup("corp:A");
await getCorpProvisionalAuthLink(corp);
expect(corp.credentials.accessToken).toBe("token-B");
expect(corp.credentials.staffId).toBe("corp:A");
expect(save).toHaveBeenCalledTimes(1);
});
it("does not partly mutate memory when saving fails", async () => {
const { corp, save } = setup();
const before = structuredClone(corp);
save.mockImplementation(() => { throw new Error("disk unavailable"); });
await expect(getCorpProvisionalAuthLink(corp, { staffId: "corp:B", persistStaff: true })).rejects.toThrow("disk unavailable");
expect(corp).toEqual(before);
});
it("rejects a mismatched signing identity before persisting", async () => {
const { corp, save } = setup("corp:C");
const before = structuredClone(corp);
await expect(getCorpProvisionalAuthLink(corp, { staffId: "corp:B", persistStaff: true })).rejects.toThrow("身份与目标员工不一致");
expect(corp).toEqual(before);
expect(save).not.toHaveBeenCalled();
});
it("does not disguise an existing session as another staff without OpenAPI keys", async () => {
const { corp, sign, save } = setup();
delete corp.credentials.appKey;
delete corp.credentials.appSecurity;
await expect(getCorpProvisionalAuthLink(corp, { staffId: "corp:B" })).rejects.toThrow("需要已配置的 OpenAPI");
expect(sign).not.toHaveBeenCalled();
expect(save).not.toHaveBeenCalled();
});
});
+23 -14
View File
@@ -424,6 +424,10 @@ export async function getCorpProvisionalAuthLink(
const targetStaffId = options.staffId || corp.staffId || corp.credentials.staffId;
const targetStaffName = options.staffName || (options.staffId ? undefined : corp.staffName || corp.session?.staffName);
const baseUrl = normalizeBaseUrl(corp.baseUrl || DEFAULT_EKB_BASE_URL);
const syncLocalSession = options.syncLocalSession !== false && (!options.staffId || options.persistStaff === true);
if (options.staffId && !hasOpenApiPersistentCredentials(corp)) {
throw new AuthenticationError("切换员工签发链接需要已配置的 OpenAPI 持久化密钥,现有会话不能代表其他员工。");
}
// 1. 若尚未配置 appKey/appSecurity,先确保会话有效并尝试自动提权提取密钥
if (!hasOpenApiPersistentCredentials(corp)) {
@@ -455,21 +459,26 @@ export async function getCorpProvisionalAuthLink(
pageType,
});
if (options.syncLocalSession !== false) {
corp.credentials.accessToken = provisional.token;
if (!corp.auth) corp.auth = { refreshTtl: 300 };
corp.auth.expiresAt = provisional.expiresAt;
if (corp.session) {
corp.session.expTime = provisional.expiresAt;
const normalizedStaffId = targetStaffId.includes(":") ? targetStaffId : `${corpId}:${targetStaffId}`;
if (provisional.uid !== normalizedStaffId) {
throw new AuthenticationError("免密链接签发身份与目标员工不一致,未更新本地会话。");
}
if (syncLocalSession) {
const updated = structuredClone(corp);
updated.credentials.accessToken = provisional.token;
if (!updated.auth) updated.auth = { refreshTtl: 300 };
updated.auth.expiresAt = provisional.expiresAt;
if (updated.session) {
updated.session.expTime = provisional.expiresAt;
}
if (options.persistStaff && options.staffId) {
corp.staffId = options.staffId;
corp.credentials.staffId = options.staffId;
if (options.staffName) {
corp.staffName = options.staffName;
}
updated.staffId = normalizedStaffId;
updated.credentials.staffId = normalizedStaffId;
updated.staffName = options.staffName;
if (updated.session) updated.session.staffName = options.staffName;
}
saveCorpConfig(corp, options.enterprisesDir);
saveCorpConfig(updated, options.enterprisesDir);
Object.assign(corp, updated);
invalidateCorpSubdomainTokenCaches(corp);
}
@@ -477,7 +486,7 @@ export async function getCorpProvisionalAuthLink(
corpId,
corpName: corp.name,
staffId: provisional.uid || targetStaffId,
staffName: targetStaffName || corp.staffName || corp.session?.staffName || undefined,
staffName: targetStaffName ?? undefined,
url: provisional.url,
token: provisional.token,
expiresIn: provisional.expiresIn,
@@ -504,7 +513,7 @@ export async function getCorpProvisionalAuthLink(
);
}
if (explicitDuration !== undefined && options.syncLocalSession !== false) {
if (explicitDuration !== undefined && syncLocalSession) {
if (!corp.auth) corp.auth = { refreshTtl: 300 };
corp.auth.expiresAt = expMs;
if (corp.session) {