Merge pull request #78 from yunyingk/codex/sync-test-hosecloud-integrations
Add automatic hosecloud integration sync for test environments
This commit is contained in:
2 files changed
+410
No files matched your search
@@ -402,6 +402,292 @@ describe("corps sync-test", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildTestHosecloudOutboundName", () => {
|
||||
test("appends (Seal测) suffix, using up to 6 chars of corp name", async () => {
|
||||
const { buildTestHosecloudOutboundName } = await import("./corps.js");
|
||||
// Short name — all chars fit
|
||||
expect(buildTestHosecloudOutboundName("钰泰半导体")).toBe("钰泰半导体(Seal测)");
|
||||
// Exactly 6-char prefix
|
||||
expect(buildTestHosecloudOutboundName("美年大健康产业控股")).toBe("美年大健康产(Seal测)");
|
||||
// Long name — truncated to 6 chars prefix
|
||||
expect(buildTestHosecloudOutboundName("钰泰半导体股份有限公司")).toBe("钰泰半导体股(Seal测)");
|
||||
// Total is always ≤ 13 chars
|
||||
const name = buildTestHosecloudOutboundName("一二三四五六七八九十");
|
||||
expect([...name].length).toBeLessThanOrEqual(13);
|
||||
expect(name.endsWith("(Seal测)")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sync-test hosecloud integration auto-sync", () => {
|
||||
function setupHoseTestEnv() {
|
||||
const root = mkdtempSync(join(tmpdir(), "seal-use-hose-sync-"));
|
||||
const enterprises = join(root, "enterprises");
|
||||
const mappings = join(root, "mappings");
|
||||
mkdirSync(enterprises, { recursive: true });
|
||||
mkdirSync(mappings, { recursive: true });
|
||||
tempDirs.push(root);
|
||||
|
||||
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises;
|
||||
process.env.SEAL_USE_CONFIG_FILE = join(root, "config.json");
|
||||
process.env.SEAL_USE_TOKEN_STORE = join(root, "tokens.json");
|
||||
process.env.SEAL_USE_MAPPINGS_DIR = mappings;
|
||||
|
||||
// Prod corp is hose-sourced (has appKey/appSecurity)
|
||||
const prodCorp: CorpConfig = {
|
||||
id: "hose-prod",
|
||||
name: "钰泰半导体股份有限公司",
|
||||
environment: "production",
|
||||
testCorpId: "hose-test",
|
||||
seal: {
|
||||
url: "https://hose-prod.sealai.cc",
|
||||
endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" }
|
||||
},
|
||||
source: {
|
||||
type: "hose",
|
||||
domain: "https://wx2.ekuaibao.com",
|
||||
appKey: "test-app-key-123",
|
||||
appSecurity: "test-app-secret-456",
|
||||
staffId: "hose-prod:staffid",
|
||||
corpId: "hose-prod"
|
||||
},
|
||||
auth: { refreshTtl: 300 }
|
||||
};
|
||||
|
||||
const testCorp: CorpConfig = {
|
||||
id: "hose-test",
|
||||
name: "谢子豪测试环境",
|
||||
environment: "test",
|
||||
prodCorpId: "hose-prod",
|
||||
seal: {
|
||||
url: "https://hose-test.sealai.cc",
|
||||
endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" }
|
||||
},
|
||||
source: {
|
||||
type: "seal",
|
||||
token: "test-token",
|
||||
sealUrl: "https://hose-test.sealai.cc",
|
||||
expiresIn: 3600,
|
||||
staffId: "seal"
|
||||
},
|
||||
auth: { refreshTtl: 300 }
|
||||
};
|
||||
|
||||
writeFileSync(join(enterprises, "hose-prod.json"), JSON.stringify(prodCorp, null, 2));
|
||||
writeFileSync(join(enterprises, "hose-test.json"), JSON.stringify(testCorp, null, 2));
|
||||
|
||||
return { root, enterprises };
|
||||
}
|
||||
|
||||
function mockHoseSyncRequests(options: {
|
||||
prodHosecloudIntegrations?: any[];
|
||||
testHosecloudIntegrations?: any[];
|
||||
onConfigWrite?: (isProd: boolean, body: unknown) => void;
|
||||
} = {}) {
|
||||
const prodIntegrations = options.prodHosecloudIntegrations ?? [
|
||||
{
|
||||
type: "hosecloud",
|
||||
signKey: "prod-sign-key",
|
||||
outboundName: "钰泰正式审批",
|
||||
mode: "fully_automatic",
|
||||
apiKey: "test-app-key-123",
|
||||
apiSecret: "test-app-secret-456",
|
||||
apiOrigin: "custom",
|
||||
customApiUrl: "https://wx2.ekuaibao.com",
|
||||
corporationId: "hose-prod"
|
||||
}
|
||||
];
|
||||
const testIntegrations = options.testHosecloudIntegrations ?? [];
|
||||
|
||||
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const requestUrl = typeof input === "string" ? input
|
||||
: input instanceof URL ? input.toString() : input.url;
|
||||
const method = (
|
||||
init?.method ??
|
||||
(typeof input === "object" && "method" in input ? (input as Request).method : "GET")
|
||||
).toUpperCase();
|
||||
const url = new URL(requestUrl);
|
||||
const isProd = url.host.includes("prod");
|
||||
|
||||
let rawBody = typeof init?.body === "string" ? init.body : undefined;
|
||||
if (!rawBody && typeof input === "object" && "text" in input) {
|
||||
rawBody = await (input as Request).clone().text().catch(() => "{}");
|
||||
}
|
||||
|
||||
if (url.pathname === "/api/v1/auth/me") {
|
||||
return jsonResponse({
|
||||
data: {
|
||||
user: { id: "user-1", name: isProd ? "Prod User" : "Test User" },
|
||||
tenant: { id: isProd ? "tenant-prod" : "tenant-test", tenantSlug: isProd ? "hose-prod" : "hose-test" }
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Hose → Seal SSO token exchange (used when prod corp is hose-sourced)
|
||||
if (url.pathname === "/api/auth/oauth2/session/oem-hosecloud") {
|
||||
return jsonResponse({ token: "mock-hose-seal-token", expiresIn: 3600 });
|
||||
}
|
||||
|
||||
// Hose openapi token exchange
|
||||
if (url.pathname === "/api/openapi/v1/auth/getAccessToken") {
|
||||
return jsonResponse({ value: { accessToken: "mock-hose-openapi-token" } });
|
||||
}
|
||||
|
||||
// Hose provisional auth URL (getProvisionalAuth) — must return a URL with accessToken param
|
||||
if (url.pathname === "/api/openapi/v1.1/provisional/getProvisionalAuth") {
|
||||
return jsonResponse({ value: { message: "https://mock.ekuaibao.com/provisional?accessToken=mock-closeapi-token" } });
|
||||
}
|
||||
|
||||
if (url.pathname === "/api/v1/agent/ai-approval/config" && method === "GET") {
|
||||
return jsonResponse({
|
||||
data: {
|
||||
tone: "formal",
|
||||
language: "zh-CN",
|
||||
decisionPreferences: { explicitApprove: "", explicitReject: "", exemptApprove: "", review: "" },
|
||||
thinkingDepthPreference: { defaultLevel: "medium", routingPolicies: [] },
|
||||
integrations: isProd ? prodIntegrations : testIntegrations
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (url.pathname === "/api/v1/agent/ai-approval/config" && (method === "POST" || method === "PATCH")) {
|
||||
const body = JSON.parse(rawBody || "{}");
|
||||
options.onConfigWrite?.(isProd, body);
|
||||
return jsonResponse({ data: { success: true } });
|
||||
}
|
||||
|
||||
// Minimal stubs for rules/docs/versions
|
||||
if (url.pathname === "/api/v1/knowledge/articles") {
|
||||
return jsonResponse({ data: { articles: [], total: 0 } });
|
||||
}
|
||||
if (url.pathname === "/api/v1/rules") {
|
||||
return jsonResponse({ data: { rules: [], hasPendingDeletes: false } });
|
||||
}
|
||||
if (url.pathname === "/api/v1/rule-set-versions") {
|
||||
return jsonResponse({ data: [] });
|
||||
}
|
||||
if (url.pathname === "/api/v1/rule-set-versions/publish") {
|
||||
return jsonResponse({ data: { version: { id: "v1", versionNumber: 1, versionName: "v1", rules: [] }, rulesCount: 0 } });
|
||||
}
|
||||
if (url.pathname === "/api/v1/rules/batch-recode") {
|
||||
return jsonResponse({ data: { success: true } });
|
||||
}
|
||||
|
||||
return jsonResponse({ error: `Unexpected: ${method} ${url.pathname}` }, 404);
|
||||
}) as typeof fetch;
|
||||
}
|
||||
|
||||
test("hose-sourced prod corp auto-syncs hosecloud integration with assisted mode and naming convention", async () => {
|
||||
setupHoseTestEnv();
|
||||
await runCli(["corps", "bind-test", "hose-prod", "hose-test", "--confirm"]);
|
||||
|
||||
let capturedTestConfigBody: any;
|
||||
mockHoseSyncRequests({
|
||||
onConfigWrite: (isProd, body) => {
|
||||
if (!isProd) capturedTestConfigBody = body;
|
||||
}
|
||||
});
|
||||
|
||||
const result = await runCli(["corps", "sync-test", "hose-prod", "--yes"]);
|
||||
expect(result.isError).toBe(false);
|
||||
|
||||
const parsed = JSON.parse(result.stdout);
|
||||
expect(parsed.hosecloudSync).toBeDefined();
|
||||
expect(parsed.hosecloudSync.skipped).toBe(false);
|
||||
expect(parsed.hosecloudSync.synced).toHaveLength(1);
|
||||
|
||||
const synced = parsed.hosecloudSync.synced[0];
|
||||
expect(synced.outboundName).toBe("钰泰半导体股(Seal测)");
|
||||
expect(synced.corporationId).toBe("hose-prod");
|
||||
expect(synced.action).toBe("created");
|
||||
|
||||
// Verify the written integration has assisted mode regardless of prod mode
|
||||
expect(capturedTestConfigBody).toBeDefined();
|
||||
const writtenIntegration = capturedTestConfigBody.integrations?.find((i: any) => i.type === "hosecloud");
|
||||
expect(writtenIntegration?.mode).toBe("assisted");
|
||||
expect(writtenIntegration?.apiOrigin).toBe("custom");
|
||||
expect(writtenIntegration?.customApiUrl).toBe("https://wx2.ekuaibao.com");
|
||||
expect(writtenIntegration?.outboundName).toBe("钰泰半导体股(Seal测)");
|
||||
});
|
||||
|
||||
test("preserves existing test signKey when re-syncing (idempotent)", async () => {
|
||||
setupHoseTestEnv();
|
||||
await runCli(["corps", "bind-test", "hose-prod", "hose-test", "--confirm"]);
|
||||
|
||||
const existingSignKey = "existing-test-sign-key";
|
||||
let capturedBody: any;
|
||||
mockHoseSyncRequests({
|
||||
testHosecloudIntegrations: [
|
||||
{
|
||||
type: "hosecloud",
|
||||
signKey: existingSignKey,
|
||||
outboundName: "钰泰半导体股(Seal测)",
|
||||
mode: "assisted",
|
||||
apiKey: "test-app-key-123",
|
||||
apiSecret: "test-app-secret-456",
|
||||
apiOrigin: "custom",
|
||||
customApiUrl: "https://wx2.ekuaibao.com",
|
||||
corporationId: "hose-prod"
|
||||
}
|
||||
],
|
||||
onConfigWrite: (isProd, body) => {
|
||||
if (!isProd) capturedBody = body;
|
||||
}
|
||||
});
|
||||
|
||||
const result = await runCli(["corps", "sync-test", "hose-prod", "--yes"]);
|
||||
expect(result.isError).toBe(false);
|
||||
|
||||
const parsed = JSON.parse(result.stdout);
|
||||
expect(parsed.hosecloudSync.synced[0].action).toBe("updated");
|
||||
expect(parsed.hosecloudSync.synced[0].signKey).toBe(existingSignKey);
|
||||
|
||||
const writtenIntegration = capturedBody?.integrations?.find((i: any) => i.type === "hosecloud");
|
||||
expect(writtenIntegration?.signKey).toBe(existingSignKey);
|
||||
});
|
||||
|
||||
test("skips hosecloud sync for non-hose-sourced prod corps", async () => {
|
||||
const root = mkdtempSync(join(tmpdir(), "seal-use-skip-hose-"));
|
||||
const enterprises = join(root, "enterprises");
|
||||
mkdirSync(enterprises, { recursive: true });
|
||||
tempDirs.push(root);
|
||||
|
||||
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises;
|
||||
process.env.SEAL_USE_CONFIG_FILE = join(root, "config.json");
|
||||
process.env.SEAL_USE_TOKEN_STORE = join(root, "tokens.json");
|
||||
process.env.SEAL_USE_MAPPINGS_DIR = join(root, "mappings");
|
||||
mkdirSync(join(root, "mappings"), { recursive: true });
|
||||
|
||||
const sealProd: CorpConfig = {
|
||||
id: "seal-prod",
|
||||
name: "Acme Seal Native",
|
||||
environment: "production",
|
||||
testCorpId: "seal-test",
|
||||
seal: { url: "https://seal-prod.sealai.cc", endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" } },
|
||||
source: { type: "seal", token: "tok", sealUrl: "https://seal-prod.sealai.cc", expiresIn: 3600, staffId: "seal" },
|
||||
auth: { refreshTtl: 300 }
|
||||
};
|
||||
const sealTest: CorpConfig = {
|
||||
id: "seal-test",
|
||||
name: "Acme Test",
|
||||
environment: "test",
|
||||
prodCorpId: "seal-prod",
|
||||
seal: { url: "https://seal-test.sealai.cc", endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" } },
|
||||
source: { type: "seal", token: "tok2", sealUrl: "https://seal-test.sealai.cc", expiresIn: 3600, staffId: "seal" },
|
||||
auth: { refreshTtl: 300 }
|
||||
};
|
||||
writeFileSync(join(enterprises, "seal-prod.json"), JSON.stringify(sealProd, null, 2));
|
||||
writeFileSync(join(enterprises, "seal-test.json"), JSON.stringify(sealTest, null, 2));
|
||||
|
||||
mockHoseSyncRequests({});
|
||||
|
||||
const result = await runCli(["corps", "sync-test", "seal-prod", "--yes"]);
|
||||
expect(result.isError).toBe(false);
|
||||
const parsed = JSON.parse(result.stdout);
|
||||
expect(parsed.hosecloudSync.skipped).toBe(true);
|
||||
expect(parsed.hosecloudSync.reason).toContain("not hose");
|
||||
});
|
||||
});
|
||||
|
||||
describe("corps list & current", () => {
|
||||
test("outputs environment, testCorpId, and prodCorpId", async () => {
|
||||
setupTestEnv();
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
assertHoseAssistTenantMatches,
|
||||
@@ -451,6 +452,23 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
|
||||
publishVersionName: versionName,
|
||||
publishTarget: "test"
|
||||
},
|
||||
hosecloudSyncPlan: prodCorp.source.type === "hose" ? {
|
||||
sourceType: "hose",
|
||||
outboundName: buildTestHosecloudOutboundName(prodCorp.name),
|
||||
targetMode: "assisted",
|
||||
integrationsCount: (prodPref.integrations ?? []).filter((i: any) => i.type === "hosecloud").length,
|
||||
integrations: (prodPref.integrations ?? [])
|
||||
.filter((i: any) => i.type === "hosecloud")
|
||||
.map((i: any) => ({
|
||||
corporationId: i.corporationId,
|
||||
apiOrigin: i.apiOrigin,
|
||||
customApiUrl: i.customApiUrl
|
||||
}))
|
||||
} : {
|
||||
sourceType: prodCorp.source.type,
|
||||
skipped: true,
|
||||
reason: "prod source is not hose; no hosecloud credentials available"
|
||||
},
|
||||
productionGuarantees: {
|
||||
prodRulesStayDraft: true,
|
||||
prodVersionPublished: false
|
||||
@@ -574,6 +592,11 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
|
||||
});
|
||||
} catch {}
|
||||
|
||||
// 7. Sync hosecloud integrations from prod to test (hose-source corps only)
|
||||
const hosecloudSync = await syncHosecloudIntegrationsToTest(prodCorp, testCorp, prodClient, testClient).catch(
|
||||
(err) => ({ skipped: true, reason: `error: ${err?.message ?? String(err)}` } as HosecloudSyncResult)
|
||||
);
|
||||
|
||||
printJson({
|
||||
success: true,
|
||||
syncedAt: new Date().toISOString(),
|
||||
@@ -614,6 +637,7 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
|
||||
versionMapping,
|
||||
ruleMapping,
|
||||
...(mappingSavedTo ? { mappingSavedTo } : {}),
|
||||
hosecloudSync,
|
||||
productionGuarantees: {
|
||||
prodRulesStayDraft: true,
|
||||
prodVersionPublished: false
|
||||
@@ -676,6 +700,106 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
|
||||
throw new Error(`Unknown corps command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Hosecloud integration sync helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Build the outboundName for a test-env hosecloud integration.
|
||||
* Format: {企业名前7字}(Seal测) — capped at 13 chars total.
|
||||
*/
|
||||
export function buildTestHosecloudOutboundName(corpName: string): string {
|
||||
// "(Seal测)" is 7 chars; leave 6 chars for the corp name prefix.
|
||||
const suffix = "(Seal测)"
|
||||
const maxPrefix = 13 - suffix.length // 6
|
||||
const prefix = [...corpName].slice(0, maxPrefix).join("")
|
||||
return prefix + suffix
|
||||
}
|
||||
|
||||
interface HosecloudSyncResult {
|
||||
skipped: boolean
|
||||
reason?: string
|
||||
synced?: Array<{ signKey: string; outboundName: string; corporationId: string; action: "created" | "updated" }>
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync hosecloud integrations from the production Seal enterprise into the
|
||||
* test Seal enterprise. Rules:
|
||||
* - Only runs when prodCorp.source.type === "hose" (credentials available locally)
|
||||
* - outboundName: buildTestHosecloudOutboundName(prodCorp.name)
|
||||
* - mode: always "assisted"
|
||||
* - apiKey/apiSecret: from prodCorp.source.appKey / appSecurity
|
||||
* - apiOrigin/customApiUrl: copied verbatim from the production integration config
|
||||
* - signKey: existing test integration keeps its key; new ones get a fresh random key
|
||||
* - Does NOT call syncHosecloudOutbound (no sync to 合思)
|
||||
*/
|
||||
async function syncHosecloudIntegrationsToTest(
|
||||
prodCorp: import("../../core/config/types.js").CorpConfig,
|
||||
testCorp: import("../../core/config/types.js").CorpConfig,
|
||||
prodClient: import("ky").KyInstance,
|
||||
testClient: import("ky").KyInstance
|
||||
): Promise<HosecloudSyncResult> {
|
||||
if (prodCorp.source.type !== "hose") {
|
||||
return { skipped: true, reason: "prod source is not hose; no hosecloud credentials available" }
|
||||
}
|
||||
|
||||
const appKey = (prodCorp.source as any).appKey as string | undefined
|
||||
const appSecurity = (prodCorp.source as any).appSecurity as string | undefined
|
||||
if (!appKey || !appSecurity) {
|
||||
return { skipped: true, reason: "prod hose source missing appKey/appSecurity" }
|
||||
}
|
||||
|
||||
const [prodPref, testPref] = await Promise.all([
|
||||
api.getApprovalStylePreferences(prodClient, prodCorp.seal.endpoints.approvalStylePreferences).catch(() => ({} as any)),
|
||||
api.getApprovalStylePreferences(testClient, testCorp.seal.endpoints.approvalStylePreferences).catch(() => ({} as any))
|
||||
])
|
||||
|
||||
const prodIntegrations: any[] = (prodPref.integrations ?? []).filter((i: any) => i.type === "hosecloud")
|
||||
if (prodIntegrations.length === 0) {
|
||||
return { skipped: true, reason: "prod Seal enterprise has no hosecloud integrations configured" }
|
||||
}
|
||||
|
||||
const testIntegrations: any[] = (testPref.integrations ?? [])
|
||||
const testByCorpId = new Map<string, any>(
|
||||
testIntegrations.filter((i: any) => i.type === "hosecloud").map((i: any) => [i.corporationId, i])
|
||||
)
|
||||
|
||||
const outboundName = buildTestHosecloudOutboundName(prodCorp.name)
|
||||
const synced: HosecloudSyncResult["synced"] = []
|
||||
|
||||
const nextHosecloudIntegrations: any[] = prodIntegrations.map((prodInt: any) => {
|
||||
const existing = testByCorpId.get(prodInt.corporationId)
|
||||
const signKey = existing?.signKey ?? randomBytes(6).toString("hex")
|
||||
synced!.push({
|
||||
signKey,
|
||||
outboundName,
|
||||
corporationId: prodInt.corporationId,
|
||||
action: existing ? "updated" : "created"
|
||||
})
|
||||
return {
|
||||
type: "hosecloud",
|
||||
signKey,
|
||||
outboundName,
|
||||
mode: "assisted",
|
||||
apiKey: appKey,
|
||||
apiSecret: appSecurity,
|
||||
apiOrigin: prodInt.apiOrigin,
|
||||
...(prodInt.customApiUrl ? { customApiUrl: prodInt.customApiUrl } : {}),
|
||||
corporationId: prodInt.corporationId
|
||||
}
|
||||
})
|
||||
|
||||
// Merge: keep non-hosecloud entries + newly built hosecloud entries
|
||||
const otherIntegrations = testIntegrations.filter((i: any) => i.type !== "hosecloud")
|
||||
const nextConfig = {
|
||||
...testPref,
|
||||
integrations: [...otherIntegrations, ...nextHosecloudIntegrations]
|
||||
}
|
||||
await api.updateApprovalStylePreferences(testClient, nextConfig, testCorp.seal.endpoints.approvalStylePreferences)
|
||||
|
||||
return { skipped: false, synced }
|
||||
}
|
||||
|
||||
async function probeHoseCorp(input: Record<string, unknown>) {
|
||||
const appKey = requiredString(input, "appKey");
|
||||
const appSecurity = requiredString(input, "appSecurity");
|
||||
|
||||
Reference in new issue
Block a user