Refactor codebase architecture and add core auth/search unit tests
This commit is contained in:
1 parent
f315fc7485
commit
ab440024b8
5 files changed
+465
No files matched your search
@@ -0,0 +1,91 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { CorpConfig } from "../config/types.js";
|
||||
import { getDirectSealSession } from "./direct.js";
|
||||
|
||||
describe("getDirectSealSession", () => {
|
||||
test("resolves direct source session correctly", async () => {
|
||||
const corp: CorpConfig = {
|
||||
id: "corp-direct-1",
|
||||
name: "Direct Corp",
|
||||
seal: {
|
||||
url: "https://seal.example.com",
|
||||
tenantSlug: "direct-slug",
|
||||
endpoints: {
|
||||
approvalStylePreferences: "api/v1/agent/ai-approval/config"
|
||||
}
|
||||
},
|
||||
source: {
|
||||
type: "direct",
|
||||
token: "bearer-token-direct",
|
||||
sealUrl: "https://seal.example.com",
|
||||
expiresIn: 3600,
|
||||
staffId: "staff-123",
|
||||
corpId: "corp-direct-1"
|
||||
},
|
||||
auth: {
|
||||
refreshTtl: 300
|
||||
}
|
||||
};
|
||||
|
||||
const session = await getDirectSealSession(corp);
|
||||
expect(session.token).toBe("bearer-token-direct");
|
||||
expect(session.enterprise).toEqual({
|
||||
provider: "direct",
|
||||
corpId: "corp-direct-1",
|
||||
staffId: "staff-123",
|
||||
sealUrl: "https://seal.example.com",
|
||||
tenantId: undefined,
|
||||
tenantSlug: "direct-slug",
|
||||
tenantName: undefined,
|
||||
raw: {
|
||||
sourceType: "direct"
|
||||
}
|
||||
});
|
||||
expect(session.expiresAt).toBeGreaterThan(Date.now());
|
||||
});
|
||||
|
||||
test("resolves native seal source session correctly", async () => {
|
||||
const corp: CorpConfig = {
|
||||
id: "corp-native-1",
|
||||
name: "Native Seal Corp",
|
||||
seal: {
|
||||
url: "https://tenant.sealai.cc",
|
||||
tenantSlug: "tenant-slug",
|
||||
endpoints: {
|
||||
approvalStylePreferences: "api/v1/agent/ai-approval/config"
|
||||
}
|
||||
},
|
||||
source: {
|
||||
type: "seal",
|
||||
token: "bearer-token-native",
|
||||
sealUrl: "https://tenant.sealai.cc",
|
||||
expiresIn: 7200,
|
||||
staffId: "seal-admin",
|
||||
tenantId: "tenant-100",
|
||||
tenantSlug: "tenant-slug",
|
||||
tenantName: "Tenant 100 Name"
|
||||
},
|
||||
auth: {
|
||||
refreshTtl: 300
|
||||
}
|
||||
};
|
||||
|
||||
const session = await getDirectSealSession(corp);
|
||||
expect(session.token).toBe("bearer-token-native");
|
||||
expect(session.enterprise.provider).toBe("seal");
|
||||
expect(session.enterprise.tenantId).toBe("tenant-100");
|
||||
expect(session.enterprise.tenantName).toBe("Tenant 100 Name");
|
||||
});
|
||||
|
||||
test("throws error for unsupported source type", async () => {
|
||||
const invalidCorp = {
|
||||
id: "corp-invalid",
|
||||
name: "Invalid",
|
||||
seal: { endpoints: { approvalStylePreferences: "" } },
|
||||
source: { type: "hose" as const, domain: "https://app.ekuaibao.com", staffId: "a", corpId: "b" },
|
||||
auth: { refreshTtl: 300 }
|
||||
} as unknown as CorpConfig;
|
||||
|
||||
expect(getDirectSealSession(invalidCorp)).rejects.toThrow("Unsupported Seal source");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { CorpConfig, HoseSealSource } from "../config/types.js";
|
||||
import { defaultSealUrl, getHoseEnterpriseUrl, normalizeBaseUrl } from "./hose.js";
|
||||
|
||||
const ORIGINAL_ENV = process.env.SEAL_HOME_TOKEN_STORE;
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
function setupTokenStore(data: Record<string, unknown>): string {
|
||||
const dir = mkdtempSync(join(tmpdir(), "hose-auth-test-"));
|
||||
tempDirs.push(dir);
|
||||
const storePath = join(dir, "tokens.json");
|
||||
process.env.SEAL_HOME_TOKEN_STORE = storePath;
|
||||
writeFileSync(storePath, JSON.stringify(data, null, 2));
|
||||
return storePath;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
if (ORIGINAL_ENV === undefined) {
|
||||
delete process.env.SEAL_HOME_TOKEN_STORE;
|
||||
} else {
|
||||
process.env.SEAL_HOME_TOKEN_STORE = ORIGINAL_ENV;
|
||||
}
|
||||
|
||||
for (const dir of tempDirs.splice(0)) {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
describe("hose auth helpers", () => {
|
||||
test("normalizeBaseUrl strips trailing slashes", () => {
|
||||
expect(normalizeBaseUrl("https://app.ekuaibao.com///")).toBe("https://app.ekuaibao.com");
|
||||
expect(normalizeBaseUrl("https://app.ekuaibao.com")).toBe("https://app.ekuaibao.com");
|
||||
});
|
||||
|
||||
test("defaultSealUrl resolves corp.seal.url, source.sealUrl, or fallback subdomain", () => {
|
||||
const source: HoseSealSource = {
|
||||
type: "hose",
|
||||
domain: "https://app.ekuaibao.com",
|
||||
appKey: "key",
|
||||
appSecurity: "sec",
|
||||
staffId: "user1",
|
||||
corpId: "CORP123"
|
||||
};
|
||||
|
||||
const corpWithSealUrl: CorpConfig = {
|
||||
id: "corp-1",
|
||||
name: "Corp 1",
|
||||
seal: { url: "https://custom.sealai.cc", endpoints: { approvalStylePreferences: "" } },
|
||||
source,
|
||||
auth: { refreshTtl: 300 }
|
||||
};
|
||||
expect(defaultSealUrl(corpWithSealUrl, source)).toBe("https://custom.sealai.cc");
|
||||
|
||||
const corpWithoutSealUrl: CorpConfig = {
|
||||
id: "corp-1",
|
||||
name: "Corp 1",
|
||||
seal: { endpoints: { approvalStylePreferences: "" } },
|
||||
source,
|
||||
auth: { refreshTtl: 300 }
|
||||
};
|
||||
expect(defaultSealUrl(corpWithoutSealUrl, source)).toBe("https://corp123.sealai.cc");
|
||||
});
|
||||
|
||||
test("getHoseEnterpriseUrl retrieves cached provisional auth URL", async () => {
|
||||
setupTokenStore({
|
||||
"corp-cached": {
|
||||
hose: {
|
||||
closeapi: {
|
||||
token: "close-token",
|
||||
url: "https://app.ekuaibao.com/web/home.html?accessToken=close-token",
|
||||
expiresAt: Date.now() + 3600_000
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const corp: CorpConfig = {
|
||||
id: "corp-cached",
|
||||
name: "Corp Cached",
|
||||
seal: { endpoints: { approvalStylePreferences: "" } },
|
||||
source: {
|
||||
type: "hose",
|
||||
domain: "https://app.ekuaibao.com",
|
||||
appKey: "key",
|
||||
appSecurity: "sec",
|
||||
staffId: "staff",
|
||||
corpId: "corp"
|
||||
},
|
||||
auth: { refreshTtl: 300 }
|
||||
};
|
||||
|
||||
const url = await getHoseEnterpriseUrl(corp);
|
||||
expect(url).toBe("https://app.ekuaibao.com/web/home.html?accessToken=close-token");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
clearCorpTokenCache,
|
||||
clearSealSession,
|
||||
getCorpTokenCache,
|
||||
getHoseAuthCache,
|
||||
getSealSession,
|
||||
setHoseAuthCache,
|
||||
setSealSession
|
||||
} from "./token-store.js";
|
||||
import { SealSession } from "./types.js";
|
||||
|
||||
const ORIGINAL_ENV = process.env.SEAL_HOME_TOKEN_STORE;
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
function makeTempStore(): string {
|
||||
const dir = mkdtempSync(join(tmpdir(), "seal-token-store-test-"));
|
||||
tempDirs.push(dir);
|
||||
const filePath = join(dir, "tokens.json");
|
||||
process.env.SEAL_HOME_TOKEN_STORE = filePath;
|
||||
return filePath;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
if (ORIGINAL_ENV === undefined) {
|
||||
delete process.env.SEAL_HOME_TOKEN_STORE;
|
||||
} else {
|
||||
process.env.SEAL_HOME_TOKEN_STORE = ORIGINAL_ENV;
|
||||
}
|
||||
|
||||
for (const dir of tempDirs.splice(0)) {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
describe("token-store", () => {
|
||||
test("returns empty cache when store file does not exist", () => {
|
||||
makeTempStore();
|
||||
expect(getSealSession("corp-test")).toBeUndefined();
|
||||
expect(getCorpTokenCache("corp-test")).toEqual({});
|
||||
expect(getHoseAuthCache("corp-test")).toEqual({});
|
||||
});
|
||||
|
||||
test("handles corrupted JSON gracefully", () => {
|
||||
const storePath = makeTempStore();
|
||||
writeFileSync(storePath, "{ invalid json", "utf-8");
|
||||
expect(getSealSession("corp-test")).toBeUndefined();
|
||||
});
|
||||
|
||||
test("sets, retrieves, and clears seal session", () => {
|
||||
makeTempStore();
|
||||
const session: SealSession = {
|
||||
token: "test-token-123",
|
||||
expiresAt: Date.now() + 3600_000,
|
||||
enterprise: {
|
||||
provider: "direct",
|
||||
corpId: "corp-1",
|
||||
staffId: "staff-1",
|
||||
sealUrl: "https://seal.example.com"
|
||||
}
|
||||
};
|
||||
|
||||
setSealSession("corp-1", session);
|
||||
expect(getSealSession("corp-1")).toEqual(session);
|
||||
|
||||
clearSealSession("corp-1");
|
||||
expect(getSealSession("corp-1")).toBeUndefined();
|
||||
});
|
||||
|
||||
test("sets, retrieves, and clears hose auth cache", () => {
|
||||
makeTempStore();
|
||||
const hoseCache = {
|
||||
openapi: {
|
||||
token: "openapi-token",
|
||||
expiresAt: Date.now() + 3600_000
|
||||
},
|
||||
closeapi: {
|
||||
token: "closeapi-token",
|
||||
url: "https://app.ekuaibao.com/web/home.html",
|
||||
expiresAt: Date.now() + 7200_000
|
||||
}
|
||||
};
|
||||
|
||||
setHoseAuthCache("corp-hose", hoseCache);
|
||||
expect(getHoseAuthCache("corp-hose")).toEqual(hoseCache);
|
||||
|
||||
clearCorpTokenCache("corp-hose");
|
||||
expect(getHoseAuthCache("corp-hose")).toEqual({});
|
||||
expect(getCorpTokenCache("corp-hose")).toEqual({});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,174 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { KyInstance } from "ky";
|
||||
import { CorpConfig } from "../../core/config/types.js";
|
||||
import { searchApprovalContent } from "./search.js";
|
||||
|
||||
function fakeSearchClient(): KyInstance {
|
||||
return {
|
||||
get: (url: string) => ({
|
||||
json: async () => {
|
||||
if (url.startsWith("api/v1/rules")) {
|
||||
return {
|
||||
data: {
|
||||
rules: [
|
||||
{
|
||||
id: "rule-101",
|
||||
scope: "差旅报销",
|
||||
strictness: "MUST_FOLLOW",
|
||||
status: "active",
|
||||
description: "差旅住宿发票必须提供明细与住宿清单"
|
||||
},
|
||||
{
|
||||
id: "rule-102",
|
||||
scope: "餐饮招待",
|
||||
strictness: "SHOULD_FOLLOW",
|
||||
status: "active",
|
||||
description: "餐饮发票单笔超过 500 元需附同人同行名单"
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
}
|
||||
if (url.startsWith("api/v1/knowledge/articles")) {
|
||||
return {
|
||||
data: {
|
||||
total: 1,
|
||||
articles: [
|
||||
{
|
||||
id: "doc-1",
|
||||
title: "企业差旅管理制度",
|
||||
purpose: "规范集团员工出差标准",
|
||||
contentType: "policy",
|
||||
content: "第一条 出差前需提交申请单\n第二条 住宿费标准每晚最高 800 元\n第三条 报销须在出差结束后 15 天内提交",
|
||||
status: "published",
|
||||
scenarios: ["差旅"],
|
||||
tags: ["制度"]
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
}
|
||||
if (url === "api/v1/agent/ai-approval/config") {
|
||||
return {
|
||||
data: {
|
||||
tone: "professional",
|
||||
decisionPreferences: {
|
||||
explicitApprove: "规则全过且无风险时直接通过",
|
||||
review: "存疑单据转人工复核"
|
||||
},
|
||||
integrations: [
|
||||
{
|
||||
type: "hosecloud",
|
||||
outboundName: "合思推送",
|
||||
mode: "automatic"
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
}
|
||||
return { data: {} };
|
||||
}
|
||||
})
|
||||
} as unknown as KyInstance;
|
||||
}
|
||||
|
||||
function fakeCorp(): CorpConfig {
|
||||
return {
|
||||
id: "corp-search-test",
|
||||
name: "Search Test Corp",
|
||||
seal: {
|
||||
url: "https://seal.test",
|
||||
endpoints: {
|
||||
approvalStylePreferences: "api/v1/agent/ai-approval/config"
|
||||
}
|
||||
},
|
||||
source: {
|
||||
type: "direct",
|
||||
token: "tok",
|
||||
sealUrl: "https://seal.test",
|
||||
expiresIn: 3600,
|
||||
staffId: "direct"
|
||||
},
|
||||
auth: {
|
||||
refreshTtl: 300
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
describe("searchApprovalContent", () => {
|
||||
test("searches across rules, documents, and preferences by default", async () => {
|
||||
const client = fakeSearchClient();
|
||||
const corp = fakeCorp();
|
||||
|
||||
const result = await searchApprovalContent(client, corp, {
|
||||
keywords: ["差旅"],
|
||||
refresh: true
|
||||
});
|
||||
|
||||
expect(result.total).toBeGreaterThan(0);
|
||||
const areas = new Set(result.results.map((r) => r.area));
|
||||
expect(areas.has("rules")).toBe(true);
|
||||
expect(areas.has("documents")).toBe(true);
|
||||
});
|
||||
|
||||
test("respects matchMode 'all' vs 'any'", async () => {
|
||||
const client = fakeSearchClient();
|
||||
const corp = fakeCorp();
|
||||
|
||||
const anyResult = await searchApprovalContent(client, corp, {
|
||||
keywords: ["住宿", "发票"],
|
||||
matchMode: "any",
|
||||
refresh: true
|
||||
});
|
||||
expect(anyResult.total).toBeGreaterThan(0);
|
||||
|
||||
const allResult = await searchApprovalContent(client, corp, {
|
||||
keywords: ["住宿", "发票"],
|
||||
matchMode: "all",
|
||||
refresh: true
|
||||
});
|
||||
// Line: "差旅住宿发票必须提供明细与住宿清单" contains both "住宿" and "发票"
|
||||
expect(allResult.total).toBeGreaterThan(0);
|
||||
expect(allResult.results[0]?.matchedKeywords).toEqual(["住宿", "发票"]);
|
||||
});
|
||||
|
||||
test("filters search by explicit area", async () => {
|
||||
const client = fakeSearchClient();
|
||||
const corp = fakeCorp();
|
||||
|
||||
const rulesOnly = await searchApprovalContent(client, corp, {
|
||||
keywords: ["住宿"],
|
||||
areas: ["rules"],
|
||||
refresh: true
|
||||
});
|
||||
|
||||
expect(rulesOnly.results.every((r) => r.area === "rules")).toBe(true);
|
||||
});
|
||||
|
||||
test("supports snippetOnly and maxChars truncation", async () => {
|
||||
const client = fakeSearchClient();
|
||||
const corp = fakeCorp();
|
||||
|
||||
const snippetResult = await searchApprovalContent(client, corp, {
|
||||
keywords: ["住宿"],
|
||||
snippetOnly: true,
|
||||
maxChars: 10,
|
||||
refresh: true
|
||||
});
|
||||
|
||||
const first = snippetResult.results[0];
|
||||
expect(first).toBeDefined();
|
||||
expect(first?.context.before).toEqual([]);
|
||||
expect(first?.context.after).toEqual([]);
|
||||
expect(first?.matchedText.length).toBeLessThanOrEqual(13); // 10 chars + "..."
|
||||
});
|
||||
|
||||
test("throws error when keywords array is empty", () => {
|
||||
const client = fakeSearchClient();
|
||||
const corp = fakeCorp();
|
||||
|
||||
expect(searchApprovalContent(client, corp, { keywords: [" "] })).rejects.toThrow(
|
||||
"keywords must contain at least one non-empty string"
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -30,6 +30,14 @@ async function main() {
|
||||
|
||||
server.setRequestHandler(ListToolsRequestSchema, async () => ({
|
||||
tools: [
|
||||
{
|
||||
name: "seal_corps_list",
|
||||
description: "列出当前已加载的 Seal 企业配置及选中状态",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {}
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_corp_switch",
|
||||
description: "切换当前 Seal 企业",
|
||||
|
||||
Reference in new issue
Block a user