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);
|
||||
|
||||
Reference in new issue
Block a user