Add auth hose-openapi-token command for Hose enterprises
This commit is contained in:
1 parent
7304578bc7
commit
6e4a8cb088
9 files changed
+301
-11
No files matched your search
@@ -385,6 +385,162 @@ describe("auth links", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("auth hose-openapi-token", () => {
|
||||
function setupRoot(name: string) {
|
||||
const root = mkdtempSync(join(tmpdir(), name));
|
||||
const enterprises = join(root, "enterprises");
|
||||
tempDirs.push(root);
|
||||
mkdirSync(enterprises, { recursive: true });
|
||||
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_USAGE_FILE = join(root, "usage.json");
|
||||
return { root, enterprises };
|
||||
}
|
||||
|
||||
function writeHoseCorp(enterprises: string, sourceOverride: Record<string, unknown> = {}) {
|
||||
writeFileSync(
|
||||
join(enterprises, "hose-corp.json"),
|
||||
JSON.stringify({
|
||||
id: "hose-corp",
|
||||
name: "合思测试企业",
|
||||
environment: "production",
|
||||
seal: { url: "https://hose-corp.sealai.cc" },
|
||||
source: {
|
||||
type: "hose",
|
||||
domain: "https://app.ekuaibao.com",
|
||||
appKey: "key-1",
|
||||
appSecurity: "sec-1",
|
||||
corpId: "HOSE-CORP",
|
||||
staffId: "HOSE-CORP:STAFF-1",
|
||||
...sourceOverride
|
||||
},
|
||||
auth: { refreshTtl: 300 }
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
function mockGetAccessToken(counter: { count: number }, token = "fresh-openapi-token") {
|
||||
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/openapi/v1/auth/getAccessToken") {
|
||||
counter.count += 1;
|
||||
return new Response(JSON.stringify({ value: { accessToken: token, expireTime: 7200 } }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" }
|
||||
});
|
||||
}
|
||||
return new Response(JSON.stringify({ error: `Unexpected request: ${url.pathname}` }), {
|
||||
status: 404,
|
||||
headers: { "content-type": "application/json" }
|
||||
});
|
||||
}) as typeof fetch;
|
||||
}
|
||||
|
||||
test("mints a fresh OpenAPI token from persisted keys and prints it as machine JSON", async () => {
|
||||
const { enterprises } = setupRoot("seal-use-auth-openapi-token-");
|
||||
writeHoseCorp(enterprises);
|
||||
const counter = { count: 0 };
|
||||
mockGetAccessToken(counter);
|
||||
|
||||
const result = await runCli(["auth", "hose-openapi-token", "--corp", "hose-corp"]);
|
||||
|
||||
expect(result.isError).toBe(false);
|
||||
expect(counter.count).toBe(1);
|
||||
const parsed = JSON.parse(result.stdout);
|
||||
expect(parsed).toMatchObject({
|
||||
corpId: "HOSE-CORP",
|
||||
corpName: "合思测试企业",
|
||||
domain: "https://app.ekuaibao.com",
|
||||
token: "fresh-openapi-token",
|
||||
cached: false
|
||||
});
|
||||
expect(parsed.expiresAt).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+08:00$/);
|
||||
});
|
||||
|
||||
test("reuses a fresh cached token by default and mints a new one with --force", async () => {
|
||||
const { root, enterprises } = setupRoot("seal-use-auth-openapi-token-force-");
|
||||
writeHoseCorp(enterprises);
|
||||
writeFileSync(
|
||||
join(root, "tokens.json"),
|
||||
JSON.stringify({
|
||||
"hose-corp": {
|
||||
hose: {
|
||||
openapi: { token: "cached-openapi-token", expiresAt: Date.now() + 3600_000 }
|
||||
}
|
||||
}
|
||||
})
|
||||
);
|
||||
const counter = { count: 0 };
|
||||
mockGetAccessToken(counter);
|
||||
|
||||
const cachedResult = await runCli(["auth", "hose-openapi-token", "--corp", "hose-corp"]);
|
||||
expect(cachedResult.isError).toBe(false);
|
||||
expect(counter.count).toBe(0);
|
||||
const cachedParsed = JSON.parse(cachedResult.stdout);
|
||||
expect(cachedParsed).toMatchObject({ token: "cached-openapi-token", cached: true });
|
||||
expect(cachedResult.stderr).toContain("复用本地仍有效的 accessToken");
|
||||
|
||||
const forcedResult = await runCli(["auth", "openapi-token", "--corp", "hose-corp", "--force"]);
|
||||
expect(forcedResult.isError).toBe(false);
|
||||
expect(counter.count).toBe(1);
|
||||
const forcedParsed = JSON.parse(forcedResult.stdout);
|
||||
expect(forcedParsed).toMatchObject({ token: "fresh-openapi-token", cached: false });
|
||||
});
|
||||
|
||||
test("rejects a native Seal enterprise with exit code 2", async () => {
|
||||
const { enterprises } = setupRoot("seal-use-auth-openapi-token-native-");
|
||||
writeFileSync(
|
||||
join(enterprises, "native-seal.json"),
|
||||
JSON.stringify({
|
||||
id: "native-seal",
|
||||
name: "原生 Seal 企业",
|
||||
environment: "production",
|
||||
seal: { url: "https://native.seal.test", tenantSlug: "native-seal" },
|
||||
source: {
|
||||
type: "seal",
|
||||
token: "seal-token",
|
||||
sealUrl: "https://native.seal.test",
|
||||
expiresIn: 3600,
|
||||
corpId: "native-corp",
|
||||
staffId: "native-staff"
|
||||
},
|
||||
auth: { refreshTtl: 300 }
|
||||
})
|
||||
);
|
||||
const counter = { count: 0 };
|
||||
mockGetAccessToken(counter);
|
||||
|
||||
const result = await runCli(["auth", "hose-openapi-token", "--corp", "native-seal"]);
|
||||
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.exitCode).toBe(2);
|
||||
expect(result.stderr).toContain("非合思");
|
||||
expect(counter.count).toBe(0);
|
||||
});
|
||||
|
||||
test("exits 13 when the Hose enterprise has no OpenAPI credentials", async () => {
|
||||
const { enterprises } = setupRoot("seal-use-auth-openapi-token-nocreds-");
|
||||
writeHoseCorp(enterprises, {
|
||||
appKey: undefined,
|
||||
appSecurity: undefined,
|
||||
closeToken: "web-session-token",
|
||||
expiresAt: "2099-01-01T00:00:00+08:00"
|
||||
});
|
||||
const counter = { count: 0 };
|
||||
mockGetAccessToken(counter);
|
||||
|
||||
const result = await runCli(["auth", "hose-openapi-token", "--corp", "hose-corp"]);
|
||||
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.exitCode).toBe(13);
|
||||
expect(result.stderr).toContain("缺少合思凭证");
|
||||
expect(counter.count).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
function restoreEnv(name: string, value: string | undefined) {
|
||||
if (value === undefined) delete process.env[name];
|
||||
else process.env[name] = value;
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
import { assertHoseAssistTenantMatches, exchangeHoseAssistLink, getHoseProvisionalAuthLink } from "../../core/auth/hose.js";
|
||||
import {
|
||||
assertHoseAssistTenantMatches,
|
||||
exchangeHoseAssistLink,
|
||||
getHoseOpenapiToken,
|
||||
getHoseProvisionalAuthLink,
|
||||
normalizeBaseUrl
|
||||
} from "../../core/auth/hose.js";
|
||||
import { clearCorpTokenCache } from "../../core/auth/token-store.js";
|
||||
import { formatBeijingIso } from "../../core/config/timestamps.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import { CliError, validationError } from "../../core/errors.js";
|
||||
import { createSealClient, createSealClientForUrl } from "../../core/http/factory.js";
|
||||
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
|
||||
import { createDelegation, getMe } from "../../domains/seal/api.js";
|
||||
@@ -147,6 +154,44 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
action === "hose-openapi-token" ||
|
||||
action === "openapi-token" ||
|
||||
action === "hose-token"
|
||||
) {
|
||||
if (corp.source.type !== "hose") {
|
||||
throw new CliError(
|
||||
`【合思专享能力】当前企业「${corp.name}」(id: ${corp.id}) 为原生 Seal (${corp.source.type}) 租户,非合思 (Hose/合思云/易快报) 渠道企业。\n` +
|
||||
"OpenAPI accessToken 签发能力专属于合思生态租户(使用持久化的 appKey/appSecurity 向合思 OpenAPI 换取 token),非合思渠道企业不支持此命令。",
|
||||
2
|
||||
);
|
||||
}
|
||||
const appKey = corp.source.appKey ?? corp.source.key;
|
||||
const appSecurity = corp.source.appSecurity ?? corp.source.password;
|
||||
if (!appKey || !appSecurity) {
|
||||
throw validationError(
|
||||
`缺少合思凭证:企业「${corp.name}」(id: ${corp.id}) 未配置 appKey/appSecurity(或 key/password),无法向合思 OpenAPI 签发 accessToken。`
|
||||
);
|
||||
}
|
||||
const force =
|
||||
booleanOption(args.options.force) === true ||
|
||||
booleanOption(args.options.refresh) === true ||
|
||||
booleanOption(args.options.f) === true;
|
||||
const entry = await getHoseOpenapiToken(corp, { force });
|
||||
if (entry.cached) {
|
||||
console.error("ℹ️ [合思 OpenAPI] 复用本地仍有效的 accessToken 缓存,追加 --force 可强制签发全新 token。");
|
||||
}
|
||||
printJson({
|
||||
corpId: corp.source.corpId ?? corp.id,
|
||||
corpName: corp.name,
|
||||
domain: normalizeBaseUrl(corp.source.domain),
|
||||
token: entry.token,
|
||||
expiresAt: formatBeijingIso(entry.expiresAt),
|
||||
cached: entry.cached
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "keys" || action === "hose-keys") {
|
||||
const reveal =
|
||||
booleanOption(args.options.reveal) === true ||
|
||||
|
||||
@@ -972,6 +972,17 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
description:
|
||||
"专用于合思 (Hose) 来源企业。向合思申请临时 ticket,生成直达外部合思/易快报主站 (https://app.ekuaibao.com/web/thirdparty.html) 的免密登录链接。若需生成 Seal 自身的审核后台访问链接,请使用 'seal-use auth link'。"
|
||||
},
|
||||
{
|
||||
name: "hose-openapi-token",
|
||||
aliases: ["openapi-token", "hose-token"],
|
||||
summary: "【合思】用持久化密钥签发合思 OpenAPI accessToken",
|
||||
usage: ["seal-use auth hose-openapi-token [--corp <corpId>] [--force]"],
|
||||
options: [
|
||||
{ flag: "--force, --refresh, -f", description: "跳过本地缓存,强制向合思 OpenAPI 签发全新 token" }
|
||||
],
|
||||
description:
|
||||
"专用于合思 (Hose) 来源企业。使用已持久化的 appKey/appSecurity 调用 /api/openapi/v1/auth/getAccessToken 换取 OpenAPI accessToken(约 1 小时有效),stdout 输出含 token、expiresAt 与 cached 字段(cached=true 表示复用了本地仍有效的缓存)。"
|
||||
},
|
||||
{
|
||||
name: "hose-extract-keys",
|
||||
aliases: ["extract-keys", "extract-key", "extract-hose-keys"],
|
||||
|
||||
@@ -100,6 +100,8 @@ describe("CLI read-only classification", () => {
|
||||
["mcp"],
|
||||
["update"],
|
||||
["auth", "keys"],
|
||||
// Mints and prints an OpenAPI credential, so it never qualifies as a read.
|
||||
["auth", "hose-openapi-token"],
|
||||
["analytics", "analyze", "record-1"],
|
||||
["tool", "sealApprovalRuleCreate", "--json", "{}"],
|
||||
["langfuse", "unknown-verb"],
|
||||
|
||||
Reference in new issue
Block a user