1128 lines
37 KiB
TypeScript
1128 lines
37 KiB
TypeScript
import { afterEach, describe, expect, test } from "bun:test";
|
|
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
import { runCli } from "../runner.js";
|
|
|
|
const ORIGINAL_ENV = {
|
|
enterprises: process.env.SEAL_USE_ENTERPRISES_DIR,
|
|
config: process.env.SEAL_USE_CONFIG_FILE,
|
|
tokenStore: process.env.SEAL_USE_TOKEN_STORE,
|
|
usageFile: process.env.SEAL_USE_USAGE_FILE
|
|
};
|
|
const ORIGINAL_FETCH = globalThis.fetch;
|
|
const tempDirs: string[] = [];
|
|
|
|
afterEach(() => {
|
|
restoreEnv("SEAL_USE_ENTERPRISES_DIR", ORIGINAL_ENV.enterprises);
|
|
restoreEnv("SEAL_USE_CONFIG_FILE", ORIGINAL_ENV.config);
|
|
restoreEnv("SEAL_USE_TOKEN_STORE", ORIGINAL_ENV.tokenStore);
|
|
restoreEnv("SEAL_USE_USAGE_FILE", ORIGINAL_ENV.usageFile);
|
|
globalThis.fetch = ORIGINAL_FETCH;
|
|
|
|
for (const dir of tempDirs.splice(0)) {
|
|
rmSync(dir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
describe("corps link onboarding", () => {
|
|
test("imports a Hose assistance link and writes a verified Hose web-session config", async () => {
|
|
const enterprises = setupConfigEnv();
|
|
mockSealLinkRequests();
|
|
|
|
const link = hoseLink();
|
|
const result = await runCli(["corps", "add-link", link, "--name", "Acme Corporation"]);
|
|
|
|
expect(result.isError).toBe(false);
|
|
expect(result.stdout).not.toContain("hose-token");
|
|
expect(result.stdout).not.toContain(link);
|
|
|
|
const config = JSON.parse(readFileSync(join(enterprises, "acme-01.json"), "utf-8")) as {
|
|
id: string;
|
|
name: string;
|
|
seal: { url?: string; tenantSlug?: string };
|
|
source: {
|
|
type: string;
|
|
closeToken: string;
|
|
staffId: string;
|
|
provider?: string;
|
|
corpId?: string;
|
|
};
|
|
};
|
|
expect(config).toMatchObject({
|
|
id: "acme-01",
|
|
name: "Acme Corporation",
|
|
seal: {
|
|
url: "https://acme-01.sealai.cc",
|
|
tenantSlug: "acme-01"
|
|
},
|
|
source: {
|
|
type: "hose",
|
|
closeToken: "hose-token",
|
|
staffId: "acme-01:admin",
|
|
provider: "hosecloud",
|
|
corpId: "acme-01"
|
|
}
|
|
});
|
|
});
|
|
|
|
test("creates a delegation directly from a Hose assistance link via auth link", async () => {
|
|
mockSealLinkRequests({ delegation: true });
|
|
|
|
const result = await runCli([
|
|
"auth",
|
|
"link",
|
|
"--from-link",
|
|
hoseLink(),
|
|
"--note",
|
|
"Customer support"
|
|
]);
|
|
|
|
expect(result.isError).toBe(false);
|
|
expect(JSON.parse(result.stdout)).toMatchObject({
|
|
tenant: {
|
|
corpId: "acme-01",
|
|
tenantSlug: "acme-01"
|
|
},
|
|
user: {
|
|
id: "user-1",
|
|
providerUserId: "staff-1"
|
|
},
|
|
delegation: {
|
|
id: "delegation-1",
|
|
token: "delegation-token",
|
|
link: "https://acme-01.sealai.cc/delegation?token=delegation-token"
|
|
},
|
|
expiresIn: 1800
|
|
});
|
|
});
|
|
|
|
test("imports a Seal native delegate link and writes a verified Seal config", async () => {
|
|
const enterprises = setupConfigEnv();
|
|
mockSealLinkRequests();
|
|
|
|
const link = "https://acme-01.sealai.cc/delegate?token=del-tok";
|
|
const result = await runCli(["corps", "add-link", link, "--name", "Acme Seal Corp"]);
|
|
|
|
expect(result.isError).toBe(false);
|
|
expect(result.stdout).not.toContain("del-tok");
|
|
expect(result.stdout).not.toContain(link);
|
|
|
|
const config = JSON.parse(readFileSync(join(enterprises, "acme-01.json"), "utf-8")) as {
|
|
id: string;
|
|
name: string;
|
|
seal: { url?: string; tenantSlug?: string };
|
|
source: {
|
|
type: string;
|
|
token: string;
|
|
provider?: string;
|
|
};
|
|
};
|
|
expect(config).toMatchObject({
|
|
id: "acme-01",
|
|
name: "Acme Seal Corp",
|
|
seal: {
|
|
url: "https://acme-01.sealai.cc",
|
|
tenantSlug: "acme-01"
|
|
},
|
|
source: {
|
|
type: "seal",
|
|
token: "mock-delegate-token",
|
|
provider: "seal"
|
|
}
|
|
});
|
|
});
|
|
|
|
test("previews a Seal native delegate link with --dry-run", async () => {
|
|
mockSealLinkRequests();
|
|
|
|
const link = "https://acme-01.sealai.cc/delegate?token=del-tok";
|
|
const result = await runCli(["corps", "add-link", link, "--dry-run"]);
|
|
|
|
expect(result.isError).toBe(false);
|
|
const parsed = JSON.parse(result.stdout);
|
|
expect(parsed).toMatchObject({
|
|
dryRun: true,
|
|
kind: "seal-delegate",
|
|
sealUrl: "https://acme-01.sealai.cc",
|
|
tenant: {
|
|
name: "Delegate Tenant"
|
|
},
|
|
user: {
|
|
name: "Delegate User"
|
|
},
|
|
delegationId: "del-1"
|
|
});
|
|
});
|
|
|
|
test("does not save a Hose assistance link with --dry-run", async () => {
|
|
const enterprises = setupConfigEnv();
|
|
mockSealLinkRequests();
|
|
|
|
const result = await runCli(["corps", "add-link", hoseLink(), "--dry-run"]);
|
|
|
|
expect(result.isError).toBe(false);
|
|
expect(JSON.parse(result.stdout)).toMatchObject({
|
|
dryRun: true,
|
|
kind: "hose",
|
|
corpId: "acme-01",
|
|
sealUrl: "https://acme-01.sealai.cc"
|
|
});
|
|
expect(readDirectory(enterprises)).toEqual([]);
|
|
});
|
|
|
|
test("imports a normalized Hose web session and stores the Hose source", async () => {
|
|
const enterprises = setupConfigEnv();
|
|
mockSealLinkRequests();
|
|
|
|
const result = await runCli([
|
|
"corps",
|
|
"add-hose-web-session",
|
|
"--json",
|
|
JSON.stringify({
|
|
baseUrl: "https://wx2.ekuaibao.com",
|
|
corpId: "Acme-01",
|
|
accessToken: "hose-token",
|
|
staffId: "staff-1"
|
|
})
|
|
]);
|
|
|
|
expect(result.isError).toBe(false);
|
|
expect(result.exitCode).toBe(0);
|
|
const config = JSON.parse(readFileSync(join(enterprises, "acme-01.json"), "utf-8"));
|
|
expect(config.source.type).toBe("hose");
|
|
expect(config.source.provider).toBe("hosecloud");
|
|
expect(config.source.closeToken).toBe("hose-token");
|
|
expect(config.source.staffId).toBe("staff-1");
|
|
});
|
|
|
|
test("rejects --elevate-hose when passed with a Seal native delegate link", async () => {
|
|
mockSealLinkRequests();
|
|
|
|
const link = "https://acme-01.sealai.cc/delegate?token=del-tok";
|
|
const result = await runCli(["corps", "add-link", link, "--elevate-hose"]);
|
|
|
|
expect(result.isError).toBe(true);
|
|
expect(result.stderr).toContain("Option --elevate-hose cannot be used with a Seal native delegate link");
|
|
});
|
|
|
|
test("rejects a link when Seal identity does not match ekbCorpId", async () => {
|
|
mockSealLinkRequests({ tenantSlug: "other-tenant", corporationId: "other-corp" });
|
|
const enterprises = setupConfigEnv();
|
|
|
|
const result = await runCli(["corps", "add-link", hoseLink()]);
|
|
|
|
expect(result.isError).toBe(true);
|
|
expect(result.stderr).toContain("tenant mismatch");
|
|
expect(result.stderr).not.toContain("hose-token");
|
|
expect(readDirectory(enterprises)).toEqual([]);
|
|
});
|
|
});
|
|
|
|
describe("corp compatibility alias", () => {
|
|
test("exposes add-hose-persistent as the canonical Hose onboarding command", async () => {
|
|
setupConfigEnv();
|
|
const result = await runCli(["corps", "add-hose-persistent", "--json", "{}"]);
|
|
|
|
expect(result.isError).toBe(true);
|
|
expect(result.stderr).toContain("Missing required JSON field: appKey");
|
|
expect(result.stderr).not.toContain("Unknown corps action");
|
|
});
|
|
|
|
test("exposes add-seal-bearer as the canonical Seal onboarding command", async () => {
|
|
setupConfigEnv();
|
|
const result = await runCli(["corps", "add-seal-bearer", "--json", "{}"]);
|
|
|
|
expect(result.isError).toBe(true);
|
|
expect(result.stderr).toContain("Missing required JSON field: token");
|
|
expect(result.stderr).not.toContain("Unknown corps action");
|
|
});
|
|
|
|
test("seal-use corp list executes and resolves cleanly like seal-use corps", async () => {
|
|
setupConfigEnv();
|
|
const result = await runCli(["corp", "list"]);
|
|
expect(result.exitCode).toBe(0);
|
|
expect(result.isError).toBe(false);
|
|
expect(JSON.parse(result.stdout)).toEqual([]);
|
|
});
|
|
|
|
test("seal-use corp --help executes and resolves cleanly like seal-use corps", async () => {
|
|
const result = await runCli(["corp", "--help"]);
|
|
expect(result.exitCode).toBe(0);
|
|
expect(result.isError).toBe(false);
|
|
expect(result.stdout).toContain("seal-use corps - Enterprise and tenant management");
|
|
expect(result.stdout).toContain("seal-use corps list");
|
|
expect(result.stdout).not.toContain("seal-use webhook");
|
|
});
|
|
});
|
|
|
|
describe("corps get and search", () => {
|
|
test("corps get retrieves rich details with sensitive secrets safely redacted", async () => {
|
|
const enterprises = setupConfigEnv();
|
|
mkdirSync(enterprises, { recursive: true });
|
|
|
|
writeFileSync(
|
|
join(enterprises, "demo-hose.json"),
|
|
JSON.stringify({
|
|
id: "demo-hose",
|
|
name: "演示合思企业",
|
|
environment: "test",
|
|
seal: {
|
|
url: "https://demo-hose.sealai.cc",
|
|
tenantSlug: "demo-hose",
|
|
headers: { "x-custom-env": "staging" }
|
|
},
|
|
source: {
|
|
type: "hose",
|
|
domain: "https://dd2.hosecloud.com",
|
|
appKey: "myAppKey123456",
|
|
appSecurity: "superSecretAppSecurityValue",
|
|
corpId: "ID01VAdCnJEdFd",
|
|
staffId: "staff-xiezihao"
|
|
},
|
|
auth: { refreshTtl: 600 },
|
|
testCorpId: "demo-hose",
|
|
prodCorpId: "demo-prod"
|
|
})
|
|
);
|
|
|
|
const result = await runCli(["corps", "get", "demo-hose"]);
|
|
expect(result.exitCode).toBe(0);
|
|
expect(result.isError).toBe(false);
|
|
expect(result.stdout).not.toContain("superSecretAppSecurityValue");
|
|
|
|
const data = JSON.parse(result.stdout);
|
|
expect(data.id).toBe("demo-hose");
|
|
expect(data.name).toBe("演示合思企业");
|
|
expect(data.environment).toBe("test");
|
|
expect(data.configFile).toContain("demo-hose.json");
|
|
expect(data.seal.url).toBe("https://demo-hose.sealai.cc");
|
|
expect(data.seal.tenantSlug).toBe("demo-hose");
|
|
expect(data.seal.customHeaderNames).toEqual(["x-custom-env"]);
|
|
expect(data.source.type).toBe("hose");
|
|
expect(data.source.corpId).toBe("ID01VAdCnJEdFd");
|
|
expect(data.source.staffId).toBe("staff-xiezihao");
|
|
expect(data.source.hasAppSecurity).toBe(true);
|
|
expect(data.source.appKey).toContain("...");
|
|
expect(data.source.appKey).not.toBe("myAppKey123456");
|
|
expect(data.relations.prodCorpId).toBe("demo-prod");
|
|
expect(data.auth.refreshTtl).toBe(600);
|
|
});
|
|
|
|
test("corps show works as alias for corps get", async () => {
|
|
const enterprises = setupConfigEnv();
|
|
mkdirSync(enterprises, { recursive: true });
|
|
|
|
writeFileSync(
|
|
join(enterprises, "native-seal.json"),
|
|
JSON.stringify({
|
|
id: "native-seal",
|
|
name: "原生Seal租户",
|
|
environment: "production",
|
|
seal: {
|
|
url: "https://native.sealai.cc",
|
|
tenantSlug: "native-slug"
|
|
},
|
|
source: {
|
|
type: "seal",
|
|
sealUrl: "https://native.sealai.cc",
|
|
token: "veryLongSecretBearerToken1234567890",
|
|
expiresIn: 3600,
|
|
tenantSlug: "native-slug",
|
|
tenantName: "原生租户",
|
|
provider: "feishu"
|
|
},
|
|
auth: { refreshTtl: 300 }
|
|
})
|
|
);
|
|
|
|
const result = await runCli(["corps", "show", "native-seal"]);
|
|
expect(result.exitCode).toBe(0);
|
|
expect(result.isError).toBe(false);
|
|
expect(result.stdout).not.toContain("veryLongSecretBearerToken1234567890");
|
|
|
|
const data = JSON.parse(result.stdout);
|
|
expect(data.id).toBe("native-seal");
|
|
expect(data.source.type).toBe("seal");
|
|
expect(data.source.provider).toBe("feishu");
|
|
expect(data.source.hasToken).toBe(true);
|
|
expect(data.source.tokenMasked).toContain("...");
|
|
});
|
|
|
|
test("corps search filters across name, staffId, environment, and keywords", async () => {
|
|
const enterprises = setupConfigEnv();
|
|
mkdirSync(enterprises, { recursive: true });
|
|
|
|
writeFileSync(
|
|
join(enterprises, "corp-prod.json"),
|
|
JSON.stringify({
|
|
id: "corp-prod",
|
|
name: "生产正式企业",
|
|
environment: "production",
|
|
seal: { url: "https://prod.sealai.cc" },
|
|
source: {
|
|
type: "hose",
|
|
domain: "https://app.ekuaibao.com",
|
|
appKey: "key1",
|
|
appSecurity: "sec1",
|
|
corpId: "PROD001",
|
|
staffId: "admin-zhangsan"
|
|
},
|
|
auth: { refreshTtl: 300 }
|
|
})
|
|
);
|
|
|
|
writeFileSync(
|
|
join(enterprises, "corp-test.json"),
|
|
JSON.stringify({
|
|
id: "corp-test",
|
|
name: "测试演练企业",
|
|
environment: "test",
|
|
seal: { url: "https://test.sealai.cc" },
|
|
source: {
|
|
type: "hose",
|
|
domain: "https://dd2.hosecloud.com",
|
|
appKey: "key2",
|
|
appSecurity: "sec2",
|
|
corpId: "TEST002",
|
|
staffId: "tester-lisi"
|
|
},
|
|
auth: { refreshTtl: 300 }
|
|
})
|
|
);
|
|
|
|
// Search by name
|
|
const searchName = await runCli(["corps", "search", "演练"]);
|
|
expect(searchName.exitCode).toBe(0);
|
|
const resultsName = JSON.parse(searchName.stdout);
|
|
expect(resultsName.length).toBe(1);
|
|
expect(resultsName[0].id).toBe("corp-test");
|
|
expect(resultsName[0].staffId).toBe("tester-lisi");
|
|
|
|
// Search by staffId
|
|
const searchStaff = await runCli(["corps", "search", "zhangsan"]);
|
|
expect(searchStaff.exitCode).toBe(0);
|
|
const resultsStaff = JSON.parse(searchStaff.stdout);
|
|
expect(resultsStaff.length).toBe(1);
|
|
expect(resultsStaff[0].id).toBe("corp-prod");
|
|
|
|
// Search with --env test
|
|
const searchEnv = await runCli(["corps", "search", "--env", "test"]);
|
|
expect(searchEnv.exitCode).toBe(0);
|
|
const resultsEnv = JSON.parse(searchEnv.stdout);
|
|
expect(resultsEnv.length).toBe(1);
|
|
expect(resultsEnv[0].id).toBe("corp-test");
|
|
|
|
// corps find alias
|
|
const findResult = await runCli(["corps", "find", "PROD001"]);
|
|
expect(findResult.exitCode).toBe(0);
|
|
expect(JSON.parse(findResult.stdout).length).toBe(1);
|
|
|
|
// corps list with query positional arg
|
|
const listWithQuery = await runCli(["corps", "list", "演练"]);
|
|
expect(listWithQuery.exitCode).toBe(0);
|
|
expect(JSON.parse(listWithQuery.stdout).length).toBe(1);
|
|
|
|
// Soft search by homophone (盛产 -> 生产正式企业)
|
|
const softHomophone = await runCli(["corps", "search", "盛产"]);
|
|
expect(softHomophone.exitCode).toBe(0);
|
|
const softHResults = JSON.parse(softHomophone.stdout);
|
|
expect(softHResults.length).toBe(1);
|
|
expect(softHResults[0].id).toBe("corp-prod");
|
|
|
|
// Soft search by initials (sc -> 生产)
|
|
const softInitials = await runCli(["corps", "search", "sc"]);
|
|
expect(softInitials.exitCode).toBe(0);
|
|
const softIResults = JSON.parse(softInitials.stdout);
|
|
expect(softIResults.length).toBe(1);
|
|
expect(softIResults[0].id).toBe("corp-prod");
|
|
|
|
// Soft search with missing letter / typo (zhangsa -> admin-zhangsan)
|
|
const softTypo = await runCli(["corps", "search", "zhangsa"]);
|
|
expect(softTypo.exitCode).toBe(0);
|
|
const softTResults = JSON.parse(softTypo.stdout);
|
|
expect(softTResults.length).toBe(1);
|
|
expect(softTResults[0].id).toBe("corp-prod");
|
|
|
|
// Strict mode rejects fuzzy matches
|
|
const strictFuzzy = await runCli(["corps", "search", "盛产", "--strict"]);
|
|
expect(strictFuzzy.exitCode).toBe(0);
|
|
expect(JSON.parse(strictFuzzy.stdout).length).toBe(0);
|
|
expect(strictFuzzy.stderr).toContain("智能软搜索");
|
|
|
|
// Strict mode accepts exact substring
|
|
const strictExact = await runCli(["corps", "search", "生产", "--strict"]);
|
|
expect(strictExact.exitCode).toBe(0);
|
|
expect(JSON.parse(strictExact.stdout).length).toBe(1);
|
|
});
|
|
});
|
|
|
|
function setupConfigEnv() {
|
|
const root = mkdtempSync(join(tmpdir(), "seal-use-link-cli-"));
|
|
const enterprises = join(root, "enterprises");
|
|
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");
|
|
return enterprises;
|
|
}
|
|
|
|
function hoseLink() {
|
|
return "https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=hose-token&ekbCorpId=Acme-01&pageType=home";
|
|
}
|
|
|
|
function mockSealLinkRequests(options: {
|
|
delegation?: boolean;
|
|
tenantSlug?: string;
|
|
corporationId?: string;
|
|
} = {}) {
|
|
globalThis.fetch = (async (input: RequestInfo | URL) => {
|
|
const requestUrl = typeof input === "string"
|
|
? input
|
|
: input instanceof URL
|
|
? input.toString()
|
|
: input.url;
|
|
const url = new URL(requestUrl);
|
|
|
|
if (url.pathname === "/api/auth/oauth2/session/oem-hosecloud") {
|
|
return jsonResponse({ accessToken: "seal-bearer-token", expiresIn: 1800 });
|
|
}
|
|
|
|
if (url.pathname === "/api/v1/auth/me") {
|
|
return jsonResponse({
|
|
data: {
|
|
user: {
|
|
id: "user-1",
|
|
tenantId: "tenant-1",
|
|
name: "Support User",
|
|
providerUserId: "staff-1",
|
|
isAdmin: true
|
|
},
|
|
tenant: {
|
|
id: "tenant-1",
|
|
name: "Acme Tenant",
|
|
tenantSlug: options.tenantSlug ?? "acme-01",
|
|
hoseCorpConfig: {
|
|
corporationId: options.corporationId ?? "acme-01",
|
|
corporationName: "Acme Corporation"
|
|
}
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
if (options.delegation && url.pathname === "/api/v1/delegation/create") {
|
|
return jsonResponse({
|
|
data: {
|
|
id: "delegation-1",
|
|
token: "delegation-token",
|
|
link: "https://acme-01.sealai.cc/delegation?token=delegation-token"
|
|
}
|
|
});
|
|
}
|
|
|
|
if (url.pathname === "/api/v1/delegation/consume") {
|
|
return new Response(
|
|
JSON.stringify({
|
|
data: {
|
|
userId: "user-delegate",
|
|
userName: "Delegate User",
|
|
tenantId: "tenant-delegate",
|
|
tenantName: "Delegate Tenant",
|
|
delegationId: "del-1"
|
|
}
|
|
}),
|
|
{
|
|
headers: {
|
|
"content-type": "application/json",
|
|
"set-cookie": "__Secure-x-seal.session_token=mock-delegate-token.sig; Path=/; HttpOnly; Secure"
|
|
}
|
|
}
|
|
);
|
|
}
|
|
|
|
if (url.pathname === "/api/v1/delegation/preview") {
|
|
return jsonResponse({
|
|
data: {
|
|
userId: "user-delegate",
|
|
userName: "Delegate User",
|
|
tenantId: "tenant-delegate",
|
|
tenantName: "Delegate Tenant",
|
|
delegationId: "del-1"
|
|
}
|
|
});
|
|
}
|
|
|
|
if (url.pathname === "/api/auth/get-session") {
|
|
return jsonResponse({
|
|
user: { name: "Delegate User", id: "user-delegate" },
|
|
session: { token: "mock-delegate-token", expiresAt: "2026-10-22T01:00:00.000Z" }
|
|
});
|
|
}
|
|
|
|
return jsonResponse({ error: `Unexpected request: ${url.pathname}` }, 404);
|
|
}) as typeof fetch;
|
|
}
|
|
|
|
function jsonResponse(value: unknown, status = 200) {
|
|
return new Response(JSON.stringify(value), {
|
|
status,
|
|
headers: { "content-type": "application/json" }
|
|
});
|
|
}
|
|
|
|
function readDirectory(path: string) {
|
|
try {
|
|
return Array.from(new Bun.Glob("*.json").scanSync({ cwd: path })).sort();
|
|
} catch {
|
|
return [];
|
|
}
|
|
}
|
|
|
|
function restoreEnv(name: string, value: string | undefined) {
|
|
if (value === undefined) delete process.env[name];
|
|
else process.env[name] = value;
|
|
}
|
|
|
|
describe("corps list sorting and limit", () => {
|
|
test("limits output to 10 by default and sorts by 7-day usage frequency", async () => {
|
|
const enterprisesDir = setupConfigEnv();
|
|
mkdirSync(enterprisesDir, { recursive: true });
|
|
const usageDir = mkdtempSync(join(tmpdir(), "seal-usage-test-"));
|
|
tempDirs.push(usageDir);
|
|
const usageFile = join(usageDir, "usage.json");
|
|
process.env.SEAL_USE_USAGE_FILE = usageFile;
|
|
|
|
// Create 12 corporations: corp-01 to corp-12
|
|
for (let i = 1; i <= 12; i++) {
|
|
const id = `corp-${String(i).padStart(2, "0")}`;
|
|
writeFileSync(
|
|
join(enterprisesDir, `${id}.json`),
|
|
JSON.stringify({
|
|
id,
|
|
name: `Enterprise ${id}`,
|
|
environment: "production",
|
|
seal: { url: `https://${id}.sealai.cc` },
|
|
source: {
|
|
type: "hose",
|
|
domain: "https://dd2.hosecloud.com",
|
|
appKey: "key",
|
|
appSecurity: "sec",
|
|
corpId: id,
|
|
staffId: id
|
|
},
|
|
auth: { refreshTtl: 300 }
|
|
})
|
|
);
|
|
}
|
|
|
|
// Record usage: corp-05 has 20 hits, corp-02 has 10 hits, corp-11 has 5 hits
|
|
const today = new Date().toISOString().slice(0, 10);
|
|
writeFileSync(
|
|
usageFile,
|
|
JSON.stringify({
|
|
"corp-05": { [today]: 20 },
|
|
"corp-02": { [today]: 10 },
|
|
"corp-11": { [today]: 5 }
|
|
})
|
|
);
|
|
|
|
// 1. Default list should limit to 10 and show hint in stderr
|
|
const defaultList = await runCli(["corps", "list"]);
|
|
expect(defaultList.isError).toBe(false);
|
|
const defaultItems = JSON.parse(defaultList.stdout);
|
|
expect(defaultItems.length).toBe(10);
|
|
expect(defaultItems[0].id).toBe("corp-05");
|
|
expect(defaultItems[1].id).toBe("corp-02");
|
|
expect(defaultItems[2].id).toBe("corp-11");
|
|
expect(defaultList.stderr).toContain("当前共有 12 家企业,已按最近 7 天使用频次展示前 10 家");
|
|
expect(defaultList.stderr).toContain("seal-use corps list --all");
|
|
|
|
// 2. --all should output all 12 without truncation
|
|
const allList = await runCli(["corps", "list", "--all"]);
|
|
expect(allList.isError).toBe(false);
|
|
const allItems = JSON.parse(allList.stdout);
|
|
expect(allItems.length).toBe(12);
|
|
expect(allItems[0].id).toBe("corp-05");
|
|
expect(allItems[1].id).toBe("corp-02");
|
|
expect(allItems[2].id).toBe("corp-11");
|
|
expect(allList.stderr).not.toContain("展示前 10 家");
|
|
|
|
// 3. Custom --limit should respect given number
|
|
const limitedList = await runCli(["corps", "list", "--limit", "3"]);
|
|
expect(limitedList.isError).toBe(false);
|
|
const limitedItems = JSON.parse(limitedList.stdout);
|
|
expect(limitedItems.length).toBe(3);
|
|
expect(limitedItems.map((c: any) => c.id)).toEqual(["corp-05", "corp-02", "corp-11"]);
|
|
});
|
|
});
|
|
|
|
describe("Hose OpenAPI key extraction from assistance link", () => {
|
|
function mockHoseKeysRequests(options: {
|
|
staffId?: string;
|
|
corpName?: string;
|
|
keys?: Array<{
|
|
id: string;
|
|
name?: string;
|
|
appKey: string;
|
|
appSecurity: string;
|
|
active?: boolean;
|
|
corporationId?: string;
|
|
createTime?: number;
|
|
}>;
|
|
} = {}) {
|
|
const staffId = options.staffId ?? "acme-01:admin01";
|
|
const corpName = options.corpName ?? "Acme Corporation";
|
|
const keys = options.keys ?? [
|
|
{
|
|
id: "key-1",
|
|
name: "生产系统接入",
|
|
appKey: "ak_acme_production_123",
|
|
appSecurity: "sec_secret_password_456789",
|
|
active: true,
|
|
corporationId: "acme-01",
|
|
createTime: 1700000000000
|
|
}
|
|
];
|
|
|
|
const jwtPayload = Buffer.from(
|
|
JSON.stringify({
|
|
staffId,
|
|
corporationName: corpName,
|
|
staffName: "Alice Admin"
|
|
})
|
|
).toString("base64url");
|
|
const fakeJwt = `header.${jwtPayload}.signature`;
|
|
|
|
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
const urlStr = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
|
const url = new URL(urlStr);
|
|
|
|
if (url.pathname === "/api/engine/realm/$UNITY/actions/jwt") {
|
|
return jsonResponse({ value: fakeJwt });
|
|
}
|
|
|
|
if (url.pathname === "/api/innerapi/v1/key") {
|
|
return jsonResponse({ items: keys, count: keys.length });
|
|
}
|
|
|
|
if (url.pathname === "/api/openapi/v1/auth/getAccessToken") {
|
|
return jsonResponse({
|
|
value: {
|
|
accessToken: "openapi-token-xyz",
|
|
corporation: { id: "acme-01", name: corpName },
|
|
staff: { id: staffId, name: "Alice Admin" }
|
|
}
|
|
});
|
|
}
|
|
|
|
if (url.pathname === "/api/auth/oauth2/session/oem-hosecloud") {
|
|
return jsonResponse({ accessToken: "seal-bearer-token", expiresIn: 1800 });
|
|
}
|
|
|
|
if (url.pathname === "/api/v1/auth/me") {
|
|
return jsonResponse({
|
|
data: {
|
|
user: { id: "u-1", providerUserId: staffId, name: "Alice Admin" },
|
|
tenant: { id: "t-1", tenantSlug: "acme-01", name: corpName }
|
|
}
|
|
});
|
|
}
|
|
|
|
return jsonResponse({ error: `Unexpected request: ${url.pathname}` }, 404);
|
|
}) as typeof fetch;
|
|
}
|
|
|
|
test("corps extract-keys masks appSecurity by default", async () => {
|
|
setupConfigEnv();
|
|
mockHoseKeysRequests();
|
|
|
|
const link = hoseLink();
|
|
const result = await runCli(["corps", "extract-keys", link]);
|
|
|
|
expect(result.isError).toBe(false);
|
|
expect(result.exitCode).toBe(0);
|
|
const parsed = JSON.parse(result.stdout);
|
|
expect(parsed.corpId).toBe("acme-01");
|
|
expect(parsed.keys.length).toBe(1);
|
|
expect(parsed.keys[0].appKey).toBe("ak_acme_production_123");
|
|
expect(parsed.keys[0].appSecurity).toBe("sec_secr...6789");
|
|
expect(result.stdout).not.toContain("sec_secret_password_456789");
|
|
expect(result.stderr).toContain("附加 --reveal (或 -r) 可查看完整 appSecurity 明文");
|
|
});
|
|
|
|
test("corps extract-keys --reveal outputs plain text appSecurity", async () => {
|
|
setupConfigEnv();
|
|
mockHoseKeysRequests();
|
|
|
|
const link = hoseLink();
|
|
const result = await runCli(["corps", "extract-keys", link, "--reveal"]);
|
|
|
|
expect(result.isError).toBe(false);
|
|
expect(result.exitCode).toBe(0);
|
|
const parsed = JSON.parse(result.stdout);
|
|
expect(parsed.keys[0].appSecurity).toBe("sec_secret_password_456789");
|
|
expect(result.stdout).toContain("sec_secret_password_456789");
|
|
});
|
|
|
|
test("corps extract-keys --save saves durable Hose enterprise configuration", async () => {
|
|
const enterprises = setupConfigEnv();
|
|
mockHoseKeysRequests();
|
|
|
|
const link = hoseLink();
|
|
const result = await runCli(["corps", "extract-keys", link, "--save", "--name", "Acme Hose", "--force"]);
|
|
|
|
expect(result.isError).toBe(false);
|
|
expect(result.exitCode).toBe(0);
|
|
|
|
const savedFile = join(enterprises, "acme-01.json");
|
|
expect(existsSync(savedFile)).toBe(true);
|
|
const config = JSON.parse(readFileSync(savedFile, "utf-8"));
|
|
expect(config.id).toBe("acme-01");
|
|
expect(config.name).toBe("Acme Hose");
|
|
expect(config.source.type).toBe("hose");
|
|
expect(config.source.appKey).toBe("ak_acme_production_123");
|
|
expect(config.source.appSecurity).toBe("sec_secret_password_456789");
|
|
expect(config.source.domain).toBe("https://wx2.ekuaibao.com");
|
|
expect(config.source.staffId).toBe("acme-01:admin01");
|
|
});
|
|
|
|
test("corps add-link --elevate-hose automatically registers as Hose OpenAPI configuration", async () => {
|
|
const enterprises = setupConfigEnv();
|
|
mockHoseKeysRequests();
|
|
|
|
const link = hoseLink();
|
|
const result = await runCli(["corps", "add-link", link, "--elevate-hose", "--name", "Acme Auto Hose", "--force"]);
|
|
|
|
expect(result.isError).toBe(false);
|
|
expect(result.exitCode).toBe(0);
|
|
|
|
const savedFile = join(enterprises, "acme-01.json");
|
|
expect(existsSync(savedFile)).toBe(true);
|
|
const config = JSON.parse(readFileSync(savedFile, "utf-8"));
|
|
expect(config.id).toBe("acme-01");
|
|
expect(config.source.type).toBe("hose");
|
|
expect(config.source.appKey).toBe("ak_acme_production_123");
|
|
expect(config.source.appSecurity).toBe("sec_secret_password_456789");
|
|
});
|
|
|
|
test("corps add-link --elevate-hose --dry-run does not save a Hose configuration", async () => {
|
|
const enterprises = setupConfigEnv();
|
|
mockHoseKeysRequests();
|
|
|
|
const result = await runCli(["corps", "add-link", hoseLink(), "--elevate-hose", "--dry-run"]);
|
|
|
|
expect(result.isError).toBe(false);
|
|
const parsed = JSON.parse(result.stdout);
|
|
expect(parsed).toMatchObject({
|
|
dryRun: true,
|
|
kind: "hose",
|
|
corpId: "acme-01",
|
|
selectedKey: {
|
|
appKey: "ak_acme_production_123",
|
|
appSecurity: "sec_secr...6789"
|
|
}
|
|
});
|
|
expect(readDirectory(enterprises)).toEqual([]);
|
|
});
|
|
|
|
test("corps add-link keeps --as-hose as a deprecated compatibility alias", async () => {
|
|
const enterprises = setupConfigEnv();
|
|
mockHoseKeysRequests();
|
|
|
|
const result = await runCli(["corps", "add-link", hoseLink(), "--as-hose", "--force"]);
|
|
|
|
expect(result.isError).toBe(false);
|
|
expect(result.exitCode).toBe(0);
|
|
expect(result.stderr).toContain("'--as-hose' is deprecated");
|
|
expect(existsSync(join(enterprises, "acme-01.json"))).toBe(true);
|
|
});
|
|
|
|
test("auth extract-keys alias works before any enterprise is configured", async () => {
|
|
setupConfigEnv();
|
|
mockHoseKeysRequests();
|
|
|
|
const link = hoseLink();
|
|
const result = await runCli(["auth", "extract-keys", link]);
|
|
|
|
expect(result.isError).toBe(false);
|
|
expect(result.exitCode).toBe(0);
|
|
const parsed = JSON.parse(result.stdout);
|
|
expect(parsed.corpId).toBe("acme-01");
|
|
expect(parsed.keys[0].appKey).toBe("ak_acme_production_123");
|
|
});
|
|
|
|
test("corps hose-keys works as alias for keys", async () => {
|
|
const enterprises = setupConfigEnv();
|
|
mkdirSync(enterprises, { recursive: true });
|
|
writeFileSync(
|
|
join(enterprises, "demo-hose.json"),
|
|
JSON.stringify({
|
|
id: "demo-hose",
|
|
name: "Demo Hose Corp",
|
|
environment: "production",
|
|
seal: { url: "https://demo.sealai.cc", endpoints: { approvalStylePreferences: "" } },
|
|
source: {
|
|
type: "hose",
|
|
domain: "https://app.ekuaibao.com",
|
|
appKey: "my-app-key-111",
|
|
appSecurity: "my-super-secret-password-222",
|
|
corpId: "demo-hose",
|
|
staffId: "demo:admin"
|
|
}
|
|
})
|
|
);
|
|
|
|
const result = await runCli(["corps", "hose-keys", "demo-hose"]);
|
|
expect(result.isError).toBe(false);
|
|
expect(result.exitCode).toBe(0);
|
|
const parsed = JSON.parse(result.stdout);
|
|
expect(parsed.corpId).toBe("demo-hose");
|
|
});
|
|
|
|
test("auth keys displays configured Hose keys and supports --reveal", async () => {
|
|
const enterprises = setupConfigEnv();
|
|
mkdirSync(enterprises, { recursive: true });
|
|
writeFileSync(
|
|
join(enterprises, "demo-hose.json"),
|
|
JSON.stringify({
|
|
id: "demo-hose",
|
|
name: "Demo Hose Corp",
|
|
environment: "production",
|
|
seal: { url: "https://demo.sealai.cc", endpoints: { approvalStylePreferences: "" } },
|
|
source: {
|
|
type: "hose",
|
|
domain: "https://app.ekuaibao.com",
|
|
appKey: "my-app-key-111",
|
|
appSecurity: "my-super-secret-password-222",
|
|
corpId: "demo-hose",
|
|
staffId: "demo:admin"
|
|
},
|
|
auth: { refreshTtl: 300 }
|
|
})
|
|
);
|
|
|
|
// 1. Default masked
|
|
const resMasked = await runCli(["auth", "keys", "--corp", "demo-hose"]);
|
|
expect(resMasked.isError).toBe(false);
|
|
const parsedMasked = JSON.parse(resMasked.stdout);
|
|
expect(parsedMasked.appKey).toBe("my-app-key-111");
|
|
expect(parsedMasked.appSecurity).toBe("my-super...-222");
|
|
expect(resMasked.stdout).not.toContain("my-super-secret-password-222");
|
|
|
|
// 2. Revealed
|
|
const resRevealed = await runCli(["auth", "keys", "--corp", "demo-hose", "--reveal"]);
|
|
expect(resRevealed.isError).toBe(false);
|
|
const parsedRevealed = JSON.parse(resRevealed.stdout);
|
|
expect(parsedRevealed.appSecurity).toBe("my-super-secret-password-222");
|
|
});
|
|
|
|
test("corps extract-keys --save errors when multiple keys exist and no selector given", async () => {
|
|
setupConfigEnv();
|
|
mockHoseKeysRequests({
|
|
keys: [
|
|
{
|
|
id: "key-prod",
|
|
name: "生产系统",
|
|
appKey: "ak_prod_111",
|
|
appSecurity: "sec_prod_111",
|
|
active: true,
|
|
corporationId: "acme-01"
|
|
},
|
|
{
|
|
id: "key-dev",
|
|
name: "测试系统",
|
|
appKey: "ak_dev_222",
|
|
appSecurity: "sec_dev_222",
|
|
active: true,
|
|
corporationId: "acme-01"
|
|
}
|
|
]
|
|
});
|
|
|
|
const link = hoseLink();
|
|
const result = await runCli(["corps", "extract-keys", link, "--save"]);
|
|
|
|
expect(result.exitCode).toBe(2);
|
|
expect(result.stderr).toContain("存在多套 (2 套) OpenAPI 应用密钥凭据");
|
|
expect(result.stderr).toContain("ak_prod_111");
|
|
expect(result.stderr).toContain("ak_dev_222");
|
|
expect(result.stderr).toContain("--app-key");
|
|
});
|
|
|
|
test("corps extract-keys --save succeeds with multiple keys when --app-key specified", async () => {
|
|
const enterprises = setupConfigEnv();
|
|
mockHoseKeysRequests({
|
|
keys: [
|
|
{
|
|
id: "key-prod",
|
|
name: "生产系统",
|
|
appKey: "ak_prod_111",
|
|
appSecurity: "sec_prod_111",
|
|
active: true,
|
|
corporationId: "acme-01"
|
|
},
|
|
{
|
|
id: "key-dev",
|
|
name: "测试系统",
|
|
appKey: "ak_dev_222",
|
|
appSecurity: "sec_dev_222",
|
|
active: true,
|
|
corporationId: "acme-01"
|
|
}
|
|
]
|
|
});
|
|
|
|
const link = hoseLink();
|
|
const result = await runCli([
|
|
"corps",
|
|
"extract-keys",
|
|
link,
|
|
"--save",
|
|
"--app-key",
|
|
"ak_dev_222",
|
|
"--force"
|
|
]);
|
|
|
|
expect(result.isError).toBe(false);
|
|
expect(result.exitCode).toBe(0);
|
|
|
|
const savedFile = join(enterprises, "acme-01.json");
|
|
expect(existsSync(savedFile)).toBe(true);
|
|
const config = JSON.parse(readFileSync(savedFile, "utf-8"));
|
|
expect(config.source.appKey).toBe("ak_dev_222");
|
|
expect(config.source.appSecurity).toBe("sec_dev_222");
|
|
});
|
|
|
|
test("corps extract-keys --save succeeds with multiple keys when --key-id specified", async () => {
|
|
const enterprises = setupConfigEnv();
|
|
mockHoseKeysRequests({
|
|
keys: [
|
|
{
|
|
id: "key-prod",
|
|
name: "生产系统",
|
|
appKey: "ak_prod_111",
|
|
appSecurity: "sec_prod_111",
|
|
active: true,
|
|
corporationId: "acme-01"
|
|
},
|
|
{
|
|
id: "key-dev",
|
|
name: "测试系统",
|
|
appKey: "ak_dev_222",
|
|
appSecurity: "sec_dev_222",
|
|
active: true,
|
|
corporationId: "acme-01"
|
|
}
|
|
]
|
|
});
|
|
|
|
const link = hoseLink();
|
|
const result = await runCli([
|
|
"corps",
|
|
"extract-keys",
|
|
link,
|
|
"--save",
|
|
"--key-id",
|
|
"key-prod",
|
|
"--force"
|
|
]);
|
|
|
|
expect(result.isError).toBe(false);
|
|
expect(result.exitCode).toBe(0);
|
|
|
|
const savedFile = join(enterprises, "acme-01.json");
|
|
expect(existsSync(savedFile)).toBe(true);
|
|
const config = JSON.parse(readFileSync(savedFile, "utf-8"));
|
|
expect(config.source.appKey).toBe("ak_prod_111");
|
|
expect(config.source.appSecurity).toBe("sec_prod_111");
|
|
});
|
|
|
|
test("corps keys and auth keys reject native Seal enterprise with exit code 2", async () => {
|
|
const enterprises = setupConfigEnv();
|
|
mkdirSync(enterprises, { recursive: true });
|
|
writeFileSync(
|
|
join(enterprises, "native-seal.json"),
|
|
JSON.stringify({
|
|
id: "native-seal",
|
|
name: "原生 Seal 企业",
|
|
environment: "production",
|
|
seal: { url: "https://seal.example.com" },
|
|
source: {
|
|
type: "seal",
|
|
sealUrl: "https://seal.example.com",
|
|
token: "token-123"
|
|
}
|
|
})
|
|
);
|
|
|
|
// 1. corps keys
|
|
const corpsResult = await runCli(["corps", "keys", "native-seal"]);
|
|
expect(corpsResult.exitCode).toBe(2);
|
|
expect(corpsResult.stderr).toContain("合思子域专享能力");
|
|
expect(corpsResult.stderr).toContain("原生 Seal (seal) 租户");
|
|
|
|
// 2. auth keys
|
|
const authResult = await runCli(["auth", "keys", "--corp", "native-seal"]);
|
|
expect(authResult.exitCode).toBe(2);
|
|
expect(authResult.stderr).toContain("合思子域专享能力");
|
|
});
|
|
|
|
test("corps rename updates enterprise name successfully", async () => {
|
|
const enterprises = setupConfigEnv();
|
|
mkdirSync(enterprises, { recursive: true });
|
|
writeFileSync(
|
|
join(enterprises, "corp-rename.json"),
|
|
JSON.stringify({
|
|
id: "corp-rename",
|
|
name: "待识别企业",
|
|
environment: "production",
|
|
seal: { url: "https://seal.example.com" },
|
|
source: {
|
|
type: "seal",
|
|
sealUrl: "https://seal.example.com",
|
|
token: "token-123"
|
|
}
|
|
})
|
|
);
|
|
|
|
const result = await runCli(["corps", "rename", "corp-rename", "--name", "已识别真实企业"]);
|
|
expect(result.exitCode).toBe(0);
|
|
const parsed = JSON.parse(result.stdout);
|
|
expect(parsed).toEqual({
|
|
id: "corp-rename",
|
|
previousName: "待识别企业",
|
|
name: "已识别真实企业",
|
|
success: true
|
|
});
|
|
|
|
const updated = JSON.parse(readFileSync(join(enterprises, "corp-rename.json"), "utf-8"));
|
|
expect(updated.name).toBe("已识别真实企业");
|
|
});
|
|
|
|
test("corps rename rejects missing --name parameter", async () => {
|
|
setupConfigEnv();
|
|
const result = await runCli(["corps", "rename", "some-corp"]);
|
|
expect(result.exitCode).toBe(2);
|
|
expect(result.stderr).toContain("Usage: seal-use corps rename <corpId> --name <newName>");
|
|
});
|
|
|
|
test("maskCellphone masks standard 11-digit mobile and non-standard phones safely", async () => {
|
|
const { maskCellphone } = await import("./corps.js");
|
|
expect(maskCellphone("13812345678")).toBe("138****5678");
|
|
expect(maskCellphone("19988887777")).toBe("199****7777");
|
|
expect(maskCellphone(undefined)).toBe("未绑定手机");
|
|
expect(maskCellphone("")).toBe("未绑定手机");
|
|
expect(maskCellphone("010123456")).toBe("010****3456");
|
|
});
|
|
|
|
test("RULE_SUMMARY_FIELDS excludes raw internal UUID and prioritizes business fields", async () => {
|
|
const { RULE_SUMMARY_FIELDS } = await import("../printer.js");
|
|
expect(RULE_SUMMARY_FIELDS).not.toContain("id");
|
|
expect(RULE_SUMMARY_FIELDS).toContain("code");
|
|
expect(RULE_SUMMARY_FIELDS).toContain("status");
|
|
expect(RULE_SUMMARY_FIELDS).toContain("strictness");
|
|
expect(RULE_SUMMARY_FIELDS).toContain("scope");
|
|
});
|
|
});
|