diff --git a/src/cli/commands/keys.test.ts b/src/cli/commands/keys.test.ts new file mode 100644 index 0000000..a719115 --- /dev/null +++ b/src/cli/commands/keys.test.ts @@ -0,0 +1,144 @@ +import { describe, expect, test, spyOn } from "bun:test"; +import { handleKeysCommand } from "./keys.js"; +import { handleOpenApiCommand } from "./openapi.js"; +import type { CliRuntime, CliParsedArgs } from "../types.js"; +import * as storeTools from "../../domains/store/tools.js"; + +describe("CLI - keys 顶级命令与凭证提取", () => { + const dummyCorp: any = { + id: "test-corp-id", + name: "测试企业A", + corpId: "test-corp-id", + credentials: { corpId: "test-corp-id", accessToken: "token123" }, + }; + + const createRuntime = (corp: any = dummyCorp, jsonMode = false): CliRuntime => ({ + corpContext: {} as any, + selectedCorp: corp, + jsonMode, + }); + + test("未选中企业时返回提示并报错", async () => { + const runtime = createRuntime(null); + const parsed: CliParsedArgs = { area: "keys", options: {}, args: [], raw: ["keys"] }; + const res = await handleKeysCommand(parsed, runtime); + expect(res.exitCode).toBe(1); + expect(res.stderr).toContain("未选中企业"); + }); + + test("keys 默认脱敏显示 appSecurity 接入密码", async () => { + const spy = spyOn(storeTools, "fetchOpenApiKeys").mockImplementation(() => + Promise.resolve([ + { + id: "k-1", + name: "开发测试密钥", + appKey: "545f8b6a-75a7-4f99-86e1-bca747c985e7", + appSecurity: "9bc91727-e96e-4924-abcb-d8ed77557f58", + active: true, + createTime: 1751357077503, + updateTime: 1769063905460, + }, + ]) + ); + + const runtime = createRuntime(dummyCorp); + const parsed: CliParsedArgs = { area: "keys", options: {}, args: [], raw: ["keys"] }; + const res = await handleKeysCommand(parsed, runtime); + + expect(res.exitCode).toBe(0); + expect(res.stdout).toContain("开发测试密钥"); + expect(res.stdout).toContain("545f8b6a-75a7-4f99-86e1-bca747c985e7"); + // 默认脱敏 + expect(res.stdout).toContain("9bc91727...7f58"); + expect(res.stdout).not.toContain("9bc91727-e96e-4924-abcb-d8ed77557f58"); + spy.mockRestore(); + }); + + test("keys --reveal 显式输出完整接入密码明文", async () => { + const spy = spyOn(storeTools, "fetchOpenApiKeys").mockImplementation(() => + Promise.resolve([ + { + id: "k-1", + name: "生产密钥", + appKey: "key-full-123", + appSecurity: "secret-super-long-plain-text", + active: true, + createTime: 1751357077503, + updateTime: 1769063905460, + }, + ]) + ); + + const runtime = createRuntime(dummyCorp); + const parsed: CliParsedArgs = { + area: "keys", + options: { reveal: true }, + args: [], + raw: ["keys", "--reveal"], + }; + const res = await handleKeysCommand(parsed, runtime); + + expect(res.exitCode).toBe(0); + expect(res.stdout).toContain("secret-super-long-plain-text"); + spy.mockRestore(); + }); + + test("keys --json 模式正常序列化", async () => { + const spy = spyOn(storeTools, "fetchOpenApiKeys").mockImplementation(() => + Promise.resolve([ + { + id: "k-1", + name: "JSON密钥", + appKey: "json-app-key", + appSecurity: "secret-for-json-test", + active: true, + createTime: 1751357077503, + updateTime: 1769063905460, + }, + ]) + ); + + const runtime = createRuntime(dummyCorp, true); + const parsed: CliParsedArgs = { area: "keys", options: { json: true }, args: [], raw: ["keys", "--json"] }; + const res = await handleKeysCommand(parsed, runtime); + + expect(res.exitCode).toBe(0); + const data = JSON.parse(res.stdout); + expect(Array.isArray(data)).toBe(true); + expect(data[0].appKey).toBe("json-app-key"); + // 默认 json 脱敏 + expect(data[0].appSecurity).toContain("..."); + spy.mockRestore(); + }); + + test("openapi keys 子命令平滑转发至同一执行器", async () => { + const spy = spyOn(storeTools, "fetchOpenApiKeys").mockImplementation(() => + Promise.resolve([ + { + id: "k-1", + name: "OpenAPI子命令测试", + appKey: "sub-app-key", + appSecurity: "sub-app-security-123456", + active: true, + createTime: 1751357077503, + updateTime: 1769063905460, + }, + ]) + ); + + const runtime = createRuntime(dummyCorp); + const parsed: CliParsedArgs = { + area: "openapi", + action: "keys", + options: {}, + args: [], + raw: ["openapi", "keys"], + }; + const res = await handleOpenApiCommand(parsed, runtime); + + expect(res.exitCode).toBe(0); + expect(res.stdout).toContain("OpenAPI子命令测试"); + expect(res.stdout).toContain("sub-app-key"); + spy.mockRestore(); + }); +}); diff --git a/src/cli/commands/keys.ts b/src/cli/commands/keys.ts new file mode 100644 index 0000000..e57ef3c --- /dev/null +++ b/src/cli/commands/keys.ts @@ -0,0 +1,98 @@ +import { fetchOpenApiKeys } from "../../domains/store/tools.js"; +import { booleanOption } from "../parser.js"; +import { printJson, printTable } from "../printer.js"; +import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js"; + +function formatDate(ts: number): string { + if (!ts) return "-"; + const d = new Date(ts); + if (isNaN(d.getTime())) return "-"; + const Y = d.getFullYear(); + const M = String(d.getMonth() + 1).padStart(2, "0"); + const D = String(d.getDate()).padStart(2, "0"); + const h = String(d.getHours()).padStart(2, "0"); + const m = String(d.getMinutes()).padStart(2, "0"); + return `${Y}/${M}/${D} ${h}:${m}`; +} + +function maskSecret(secret: string): string { + if (!secret) return "-"; + if (secret.length <= 12) return "******"; + return `${secret.slice(0, 8)}...${secret.slice(-4)}`; +} + +export async function handleKeysCommand( + parsed: CliParsedArgs, + runtime: CliRuntime +): Promise { + const currentCorp = runtime.selectedCorp; + if (!currentCorp) { + return { + stdout: "", + stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n", + exitCode: 1, + }; + } + + const reveal = + booleanOption(parsed.options, ["reveal", "r", "plain"]) || + parsed.action === "reveal" || + parsed.args[0] === "reveal"; + + try { + const keys = await fetchOpenApiKeys(currentCorp); + + if (runtime.jsonMode) { + const outputData = reveal + ? keys + : keys.map((k) => ({ + ...k, + appSecurity: maskSecret(k.appSecurity), + })); + return { + stdout: printJson(outputData, runtime.outputOptions), + stderr: "", + exitCode: 0, + }; + } + + if (keys.length === 0) { + return { + stdout: `企业 [${currentCorp.name}] 暂未创建 OpenAPI 密钥凭证\n`, + stderr: "", + exitCode: 0, + }; + } + + const rows = keys.map((k, i) => [ + i + 1, + k.name || "-", + k.appKey, + reveal ? k.appSecurity : maskSecret(k.appSecurity), + k.active ? "🟢 启用" : "⚪ 停用", + formatDate(k.createTime), + ]); + + const table = printTable( + ["#", "密钥备注", "接入账号 (appKey)", "接入密码 (appSecurity)", "状态", "创建时间"], + rows + ); + + const title = `====== [${currentCorp.name}] 企业 OpenAPI 接入密钥列表 (共 ${keys.length} 个) ======`; + const hint = reveal + ? "" + : "\n提示: 接入密码默认脱敏,附加 --reveal (或 -r) 可查看完整明文;使用 --json 可输出完整结构。\n"; + + return { + stdout: `${title}\n\n${table}\n${hint}`, + stderr: "", + exitCode: 0, + }; + } catch (err: any) { + return { + stdout: "", + stderr: `获取企业 OpenAPI 密钥失败: ${err?.message || err}\n`, + exitCode: 1, + }; + } +} diff --git a/src/cli/commands/openapi.ts b/src/cli/commands/openapi.ts index 96355b9..827f5c4 100644 --- a/src/cli/commands/openapi.ts +++ b/src/cli/commands/openapi.ts @@ -2,18 +2,24 @@ import { getOpenApiSchema, listOpenApiPaths, type OpenApiType } from "../../core import { booleanOption, stringOption } from "../parser.js"; import { printJson, printKeyValue, printTable } from "../printer.js"; import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js"; +import { handleKeysCommand } from "./keys.js"; export async function handleOpenApiCommand( parsed: CliParsedArgs, runtime: CliRuntime ): Promise { + const action = parsed.action?.toLowerCase(); + + if (action === "keys" || action === "key") { + return handleKeysCommand(parsed, runtime); + } + const isRaw = booleanOption(parsed.options, ["raw"]) || parsed.action === "raw" || parsed.args[0] === "raw"; const type: OpenApiType = isRaw ? "raw" : "wrapped"; - const action = parsed.action?.toLowerCase(); switch (action) { case "paths": diff --git a/src/cli/commands/store.test.ts b/src/cli/commands/store.test.ts new file mode 100644 index 0000000..1bd9a2d --- /dev/null +++ b/src/cli/commands/store.test.ts @@ -0,0 +1,150 @@ +import { describe, expect, test, spyOn } from "bun:test"; +import { handleStoreCommand } from "./store.js"; +import type { CliRuntime, CliParsedArgs } from "../types.js"; +import * as storeTools from "../../domains/store/tools.js"; + +describe("CLI - store 应用中心与应用商店探查", () => { + const dummyCorp: any = { + id: "test-corp-id", + name: "测试企业A", + corpId: "test-corp-id", + credentials: { corpId: "test-corp-id", accessToken: "token123" }, + }; + + const createRuntime = (corp: any = dummyCorp, jsonMode = false): CliRuntime => ({ + corpContext: {} as any, + selectedCorp: corp, + jsonMode, + }); + + test("未选中企业时返回提示并报错", async () => { + const runtime = createRuntime(null); + const parsed: CliParsedArgs = { area: "store", options: {}, args: [], raw: ["store"] }; + const res = await handleStoreCommand(parsed, runtime); + expect(res.exitCode).toBe(1); + expect(res.stderr).toContain("未选中企业"); + }); + + test("store list 展示企业已购应用列表", async () => { + const spy = spyOn(storeTools, "fetchClientGoods").mockImplementation(() => + Promise.resolve([ + { + id: "g-1", + name: "开放接口(新)", + status: "OPENED", + expireTime: 1914422399000, + hasConfig: true, + powers: [{ powerCode: "219904", powerName: "开放接口(新)" }], + }, + ] as any) + ); + + const runtime = createRuntime(dummyCorp); + const parsed: CliParsedArgs = { + area: "store", + action: "list", + options: {}, + args: [], + raw: ["store", "list"], + }; + const res = await handleStoreCommand(parsed, runtime); + + expect(res.exitCode).toBe(0); + expect(res.stdout).toContain("开放接口(新)"); + expect(res.stdout).toContain("已开通"); + expect(res.stdout).toContain("支持配置"); + spy.mockRestore(); + }); + + test("store search 检索应用市场商品", async () => { + const spy = spyOn(storeTools, "searchGoods").mockImplementation(() => + Promise.resolve({ + total: 1, + items: [ + { + id: "g-2", + name: "纷享销客基础互联应用", + status: "OPENED", + summary: "连接纷享销客", + }, + ], + } as any) + ); + + const runtime = createRuntime(dummyCorp); + const parsed: CliParsedArgs = { + area: "store", + action: "search", + options: {}, + args: ["纷享"], + raw: ["store", "search", "纷享"], + }; + const res = await handleStoreCommand(parsed, runtime); + + expect(res.exitCode).toBe(0); + expect(res.stdout).toContain("纷享销客基础互联应用"); + expect(res.stdout).toContain("连接纷享销客"); + spy.mockRestore(); + }); + + test("store get 查看应用详情", async () => { + const spy = spyOn(storeTools, "fetchGoodsDetail").mockImplementation(() => + Promise.resolve({ + id: "g-1", + name: "开放接口(新)", + status: "OPENED", + hasConfig: true, + configStyle: "SIDESLIP", + powers: [{ powerCode: "219904", powerName: "开放接口(新)" }], + summary: "OpenAPI提供标准化接口", + } as any) + ); + + const runtime = createRuntime(dummyCorp); + const parsed: CliParsedArgs = { + area: "store", + action: "get", + options: {}, + args: ["g-1"], + raw: ["store", "get", "g-1"], + }; + const res = await handleStoreCommand(parsed, runtime); + + expect(res.exitCode).toBe(0); + expect(res.stdout).toContain("开放接口(新)"); + expect(res.stdout).toContain("219904"); + expect(res.stdout).toContain("SIDESLIP"); + spy.mockRestore(); + }); + + test("store keys 转发至 keys 执行器", async () => { + const spy = spyOn(storeTools, "fetchOpenApiKeys").mockImplementation(() => + Promise.resolve([ + { + id: "k-1", + name: "Store转发密钥", + appKey: "store-key-123", + appSecurity: "store-secret-456", + active: true, + createTime: 1751357077503, + updateTime: 1769063905460, + }, + ]) + ); + + const runtime = createRuntime(dummyCorp); + const parsed: CliParsedArgs = { + area: "store", + action: "keys", + options: {}, + args: [], + raw: ["store", "keys"], + }; + const res = await handleStoreCommand(parsed, runtime); + + expect(res.exitCode).toBe(0); + expect(res.stdout).toContain("Store转发密钥"); + expect(res.stdout).toContain("store-key-123"); + spy.mockRestore(); + }); +}); diff --git a/src/cli/commands/store.ts b/src/cli/commands/store.ts new file mode 100644 index 0000000..856fc0d --- /dev/null +++ b/src/cli/commands/store.ts @@ -0,0 +1,239 @@ +import { + fetchClientGoods, + searchGoods, + fetchGoodsDetail, +} from "../../domains/store/tools.js"; +import { booleanOption, stringOption } from "../parser.js"; +import { printJson, printKeyValue, printTable } from "../printer.js"; +import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js"; +import { handleKeysCommand } from "./keys.js"; + +function formatDate(ts: number | null | undefined): string { + if (!ts) return "长期有效"; + const d = new Date(ts); + if (isNaN(d.getTime())) return "-"; + const Y = d.getFullYear(); + const M = String(d.getMonth() + 1).padStart(2, "0"); + const D = String(d.getDate()).padStart(2, "0"); + return `${Y}/${M}/${D}`; +} + +function formatStatus(status: string | null | undefined): string { + if (!status) return "-"; + switch (status.toUpperCase()) { + case "OPENED": + return "🟢 已开通"; + case "EXPIRE": + return "🔴 已过期"; + case "APPLYING": + return "🟡 申请中"; + case "CLOSED": + return "⚪ 已关闭"; + default: + return status; + } +} + +export async function handleStoreCommand( + parsed: CliParsedArgs, + runtime: CliRuntime +): Promise { + const currentCorp = runtime.selectedCorp; + if (!currentCorp) { + return { + stdout: "", + stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n", + exitCode: 1, + }; + } + + const action = (parsed.action || "list").toLowerCase(); + + switch (action) { + case "keys": + case "key": + return handleKeysCommand(parsed, runtime); + + case "list": + case "ls": + return handleList(parsed, runtime); + + case "search": + case "find": + return handleSearch(parsed, runtime); + + case "get": + case "info": + case "detail": + return handleGet(parsed, runtime); + + default: + return { + stdout: "", + stderr: `未知 store 子命令: ${action}。支持: list, search, get, keys\n`, + exitCode: 1, + }; + } +} + +async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise { + const currentCorp = runtime.selectedCorp!; + const keyword = parsed.args[0] || stringOption(parsed.options, ["name", "keyword", "k"]); + const isAll = booleanOption(parsed.options, ["all", "a"]); + + try { + const items = await fetchClientGoods(currentCorp, { keyword, isAll }); + + if (runtime.jsonMode) { + return { + stdout: printJson(items, runtime.outputOptions), + stderr: "", + exitCode: 0, + }; + } + + if (items.length === 0) { + return { + stdout: `企业 [${currentCorp.name}] 暂无匹配的已购应用${keyword ? ` (搜索: ${keyword})` : ""}\n`, + stderr: "", + exitCode: 0, + }; + } + + const rows = items.map((item, i) => { + const powersStr = (item.powers || []) + .map((p) => (typeof p === "string" ? p : p.powerName || p.powerCode || "")) + .filter(Boolean) + .join(", "); + + return [ + i + 1, + item.id, + item.name, + formatStatus(item.status), + formatDate(item.expireTime), + item.hasConfig ? "支持配置" : "-", + powersStr || "-", + ]; + }); + + const table = printTable( + ["#", "应用 ID", "应用名称", "开通状态", "有效期限", "配置支持", "绑定能力 (Powers)"], + rows + ); + + const title = `====== [${currentCorp.name}] 企业已开通/已购应用列表 (共 ${items.length} 个) ======`; + + return { + stdout: `${title}\n\n${table}\n`, + stderr: "", + exitCode: 0, + }; + } catch (err: any) { + return { + stdout: "", + stderr: `查询企业已购应用失败: ${err?.message || err}\n`, + exitCode: 1, + }; + } +} + +async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime): Promise { + const currentCorp = runtime.selectedCorp!; + const keyword = parsed.args[0] || stringOption(parsed.options, ["name", "keyword", "k"]) || ""; + + try { + const result = await searchGoods(currentCorp, { keyword, count: 20 }); + + if (runtime.jsonMode) { + return { + stdout: printJson(result, runtime.outputOptions), + stderr: "", + exitCode: 0, + }; + } + + if (result.items.length === 0) { + return { + stdout: `应用商店未搜索到匹配应用${keyword ? ` (关键词: ${keyword})` : ""}\n`, + stderr: "", + exitCode: 0, + }; + } + + const rows = result.items.map((item, i) => [ + i + 1, + item.id, + item.name, + formatStatus(item.status), + item.summary || "-", + ]); + + const table = printTable(["#", "商品 ID", "应用名称", "企业状态", "应用简介"], rows); + const title = `====== 合思应用商店搜索结果 (共 ${result.total} 条,当前展示 ${result.items.length} 条) ======`; + + return { + stdout: `${title}\n\n${table}\n`, + stderr: "", + exitCode: 0, + }; + } catch (err: any) { + return { + stdout: "", + stderr: `搜索应用商店失败: ${err?.message || err}\n`, + exitCode: 1, + }; + } +} + +async function handleGet(parsed: CliParsedArgs, runtime: CliRuntime): Promise { + const currentCorp = runtime.selectedCorp!; + const goodsId = parsed.args[0] || stringOption(parsed.options, ["id"]); + + if (!goodsId) { + return { + stdout: "", + stderr: "请提供应用/商品 ID,例如: hose-use store get O1w2Hg000000qw\n", + exitCode: 1, + }; + } + + try { + const detail = await fetchGoodsDetail(currentCorp, goodsId); + + if (runtime.jsonMode) { + return { + stdout: printJson(detail, runtime.outputOptions), + stderr: "", + exitCode: 0, + }; + } + + const powersStr = (detail.powers || []) + .map((p) => `${p.powerName || p.powerCode || ""} (${p.powerCode || ""})`) + .join(", "); + + const out = printKeyValue({ + "应用 ID": detail.id, + "应用名称": detail.name, + "应用编码": detail.code || "-", + "开通状态": formatStatus(detail.status), + "有效期限": formatDate(detail.expireTime), + "支持配置": detail.hasConfig ? `是 (${detail.configStyle || "默认"})` : "否", + "绑定能力": powersStr || "-", + "应用摘要": detail.summary || "-", + }); + + return { + stdout: `====== 应用详情: ${detail.name} ======\n${out}\n`, + stderr: "", + exitCode: 0, + }; + } catch (err: any) { + return { + stdout: "", + stderr: `获取应用详情失败: ${err?.message || err}\n`, + exitCode: 1, + }; + } +} diff --git a/src/cli/printer.ts b/src/cli/printer.ts index 5b283d4..231b9f1 100644 --- a/src/cli/printer.ts +++ b/src/cli/printer.ts @@ -136,7 +136,9 @@ export function printHelp(): string { skill Agent Skill 管理 (install, status, dump) probe 连通性诊断 (probe [corpId]) update 版本自更新与发布记录 (update, update check, update --changelog, --github, --gitea, --repo=) - openapi OpenAPI 3.1.0 规范导出 (openapi, openapi --raw, openapi paths, openapi info) + openapi OpenAPI 3.1.0 规范导出与凭证查看 (openapi, openapi --raw, openapi paths, openapi info, openapi keys) + keys 企业 OpenAPI 接入凭证一键获取 (keys [--reveal|-r]) + store 应用中心已购应用与应用商店探查 (list, search <关键词>, get ) http 启动轻量 HTTP Server 与交互式文档 (http [--port=8888] [--host=127.0.0.1]) service 常驻守护进程管理 (service start|stop|restart|status|logs|poll) mcp MCP Server 运行 (serve) diff --git a/src/cli/runner.ts b/src/cli/runner.ts index a633c40..7d825b8 100644 --- a/src/cli/runner.ts +++ b/src/cli/runner.ts @@ -24,6 +24,8 @@ import { handlePermissionCommand } from "./commands/permission.js"; import { handleRuleCommand } from "./commands/rule.js"; import { handleApprovalCommand } from "./commands/approval.js"; import { handleContextCommand } from "./commands/context.js"; +import { handleKeysCommand } from "./commands/keys.js"; +import { handleStoreCommand } from "./commands/store.js"; import type { CliParsedArgs, CliResult, CliRunOptions } from "./types.js"; const STANDING_COMMANDS = new Set(["http", "server", "web", "mcp"]); @@ -227,6 +229,14 @@ async function dispatchCli( case "schema": case "spec": return await handleOpenApiCommand(parsed, runtime); + case "keys": + case "key": + case "secret": + case "secrets": + return await handleKeysCommand(parsed, runtime); + case "store": + case "market": + return await handleStoreCommand(parsed, runtime); case "http": case "server": case "web": diff --git a/src/core/auth/easo.ts b/src/core/auth/easo.ts index 5c3b855..49c39f3 100644 --- a/src/core/auth/easo.ts +++ b/src/core/auth/easo.ts @@ -29,6 +29,11 @@ const easoMemoryCache = new Map< { token: string; hoseToken: string; expiresAt: number } >(); +const unityMemoryCache = new Map< + string, + { token: string; expiresAt: number } +>(); + function isExpired(entry: { expiresAt: number }, refreshTtl: number): boolean { return Date.now() >= entry.expiresAt - refreshTtl * 1000; } @@ -53,7 +58,7 @@ async function fetchHoseToken( return response.data; } -async function fetchUnityJwt( +export async function fetchUnityJwt( accessToken: string, corpId: string, staffId: string, @@ -168,3 +173,58 @@ export async function getEasoClient(corp: CorpConfig): Promise<{ }), }; } + +export async function getUnityClient(corp: CorpConfig): Promise<{ + client: ReturnType; + unityJwt: string; +}> { + const refreshTtl = corp.auth?.refreshTtl ?? 300; + const cacheKey = `${corp.id}:unity`; + + const mem = unityMemoryCache.get(cacheKey); + if (mem && !isExpired(mem, refreshTtl)) { + return { + unityJwt: mem.token, + client: createAuthClient({ + prefixUrl: EASO_BASE_URL, + getHeaders: () => ({ + Authorization: `Bearer ${mem.token}`, + }), + onUnauthorized: () => { + unityMemoryCache.delete(cacheKey); + }, + }), + }; + } + + const corpId = corp.corpId || corp.credentials.corpId; + const staffId = corp.staffId || corp.credentials.staffId; + const baseUrl = corp.baseUrl || EKB_BASE_URL; + + const unityJwt = await fetchUnityJwt( + corp.credentials.accessToken, + corpId, + staffId, + baseUrl + ); + + const entry = { + token: unityJwt, + expiresAt: Date.now() + 2 * 60 * 60 * 1000, + }; + unityMemoryCache.set(cacheKey, entry); + + return { + unityJwt, + client: createAuthClient({ + prefixUrl: EASO_BASE_URL, + getHeaders: () => ({ + Authorization: `Bearer ${unityJwt}`, + }), + onUnauthorized: () => { + unityMemoryCache.delete(cacheKey); + }, + }), + }; +} + diff --git a/src/domains/README.domains.md b/src/domains/README.domains.md index 4a3291a..a41f563 100644 --- a/src/domains/README.domains.md +++ b/src/domains/README.domains.md @@ -8,6 +8,7 @@ |---|---|---| | `platform/` | 自建应用(DataLink Platform)与工作流(EASO/Piper) | [README.platform.md](./platform/README.platform.md) | | `bill/` | 费控单据、报销单、发票与 DataLink 实体字典 | [README.bill.md](./bill/README.bill.md) | +| `store/` | 企业应用中心/应用商店与 OpenAPI 密钥凭证 | [README.store.md](./store/README.store.md) | ## 分层规则 diff --git a/src/domains/store/README.store.md b/src/domains/store/README.store.md new file mode 100644 index 0000000..3293099 --- /dev/null +++ b/src/domains/store/README.store.md @@ -0,0 +1,17 @@ +# Store / OpenAPI Keys 域说明 + +本域负责企业 OpenAPI 接入凭证提取以及应用商店(Unity Store)/ 企业已购应用探查能力。 + +## 架构 + +- `api.ts`:传输层,负责与 `app.ekuaibao.com/api/innerapi` 以及 `unity.ekuaibao.com/api/store` 的 HTTP 交互。 +- `tools.ts`:业务层,负责换票与参数组装,供 CLI 与外部调用。 +- `types.ts`:Zod 模式与 TypeScript 类型定义。 + +## 关键接口 + +- `listOpenApiKeys`: 查询企业 OpenAPI 密钥列表(appKey / appSecurity / 备注 / 状态) +- `getOpenConfig`: 查询企业免登重定向配置 +- `listClientGoods`: 查询当前租户已购/已开通的应用清单(状态、到期时间、绑定能力) +- `searchStoreGoods`: 检索合思应用商店全部上架应用 +- `getGoodsDetail`: 获取指定应用的详细信息、套餐与规格 diff --git a/src/domains/store/api.test.ts b/src/domains/store/api.test.ts new file mode 100644 index 0000000..d31a219 --- /dev/null +++ b/src/domains/store/api.test.ts @@ -0,0 +1,145 @@ +import { describe, expect, test } from "bun:test"; +import { + listOpenApiKeys, + getOpenConfig, + listClientGoods, + searchStoreGoods, + getGoodsDetail, +} from "./api.js"; + +describe("Domains/Store - API 单元测试", () => { + test("listOpenApiKeys 解析规范的企业 OpenAPI 密钥响应", async () => { + const mockClient = { + get: async (url: string, opts: any) => { + expect(url).toBe("api/innerapi/v1/key"); + expect(opts.searchParams.corpId).toBe("corp-123"); + return { + json: async () => ({ + count: 1, + items: [ + { + id: "key-1", + name: "测试密钥", + appKey: "test-app-key", + appSecurity: "test-app-security", + active: true, + createTime: 1700000000000, + updateTime: 1700000000000, + }, + ], + }), + }; + }, + } as any; + + const keys = await listOpenApiKeys(mockClient, "corp-123"); + expect(keys.length).toBe(1); + expect(keys[0].id).toBe("key-1"); + expect(keys[0].name).toBe("测试密钥"); + expect(keys[0].appKey).toBe("test-app-key"); + expect(keys[0].appSecurity).toBe("test-app-security"); + expect(keys[0].active).toBe(true); + }); + + test("getOpenConfig 解析免登重定向配置响应", async () => { + const mockClient = { + get: async (url: string, opts: any) => { + expect(url).toBe("api/innerapi/v1/openConfig"); + expect(opts.searchParams.corpId).toBe("corp-123"); + return { + json: async () => ({ + items: [{ id: "cfg-1", url: "https://example.com/oauth" }], + }), + }; + }, + } as any; + + const config = await getOpenConfig(mockClient, "corp-123"); + expect(config.items.length).toBe(1); + expect(config.items[0].url).toBe("https://example.com/oauth"); + }); + + test("listClientGoods 解析企业已购应用响应", async () => { + const mockClient = { + get: async (url: string, opts: any) => { + expect(url).toBe("api/store/client/goods"); + expect(opts.searchParams.corpId).toBe("corp-123"); + return { + json: async () => ({ + value: { + items: [ + { + id: "goods-1", + name: "开放接口(新)", + status: "OPENED", + hasConfig: true, + powers: [{ powerCode: "219904", powerName: "开放接口(新)" }], + }, + ], + }, + }), + }; + }, + } as any; + + const goods = await listClientGoods(mockClient, "corp-123"); + expect(goods.length).toBe(1); + expect(goods[0].name).toBe("开放接口(新)"); + expect(goods[0].status).toBe("OPENED"); + expect(goods[0].hasConfig).toBe(true); + }); + + test("searchStoreGoods 解析全量应用搜索响应", async () => { + const mockClient = { + post: async (url: string, opts: any) => { + expect(url).toBe("api/store/goods"); + expect(opts.searchParams.corpId).toBe("corp-123"); + expect(opts.json.name).toBe("接口"); + return { + json: async () => ({ + value: { + total: 2, + items: [ + { id: "g-1", name: "通讯录接口", status: null }, + { id: "g-2", name: "开放接口(新)", status: "OPENED" }, + ], + }, + }), + }; + }, + } as any; + + const result = await searchStoreGoods(mockClient, "corp-123", { name: "接口" }); + expect(result.total).toBe(2); + expect(result.items.length).toBe(2); + expect(result.items[0].name).toBe("通讯录接口"); + expect(result.items[1].name).toBe("开放接口(新)"); + }); + + test("getGoodsDetail 解析指定应用规格与详情", async () => { + const mockClient = { + get: async (url: string, opts: any) => { + expect(url).toBe("api/store/client/goods/detail/$goods-99"); + expect(opts.searchParams.corpId).toBe("corp-123"); + return { + json: async () => ({ + value: { + id: "goods-99", + name: "合思商城", + status: "EXPIRE", + hasConfig: true, + configStyle: "SIDESLIP", + powers: [{ powerCode: "120209", powerName: "合思商城订购管理" }], + }, + }), + }; + }, + } as any; + + const detail = await getGoodsDetail(mockClient, "corp-123", "goods-99"); + expect(detail.id).toBe("goods-99"); + expect(detail.name).toBe("合思商城"); + expect(detail.hasConfig).toBe(true); + expect(detail.configStyle).toBe("SIDESLIP"); + }); +}); diff --git a/src/domains/store/api.ts b/src/domains/store/api.ts new file mode 100644 index 0000000..d8c54d0 --- /dev/null +++ b/src/domains/store/api.ts @@ -0,0 +1,98 @@ +import { z } from "zod"; +import type { KyInstance } from "ky"; +import { + OpenApiKeySchema, + OpenConfigSchema, + ClientGoodsSchema, + StoreGoodsItemSchema, + GoodsDetailSchema, + type OpenApiKey, + type OpenConfig, + type ClientGoods, + type StoreGoodsItem, + type GoodsDetail, +} from "./types.js"; + +// ── OpenAPI 密钥与配置接口 ─────────────────────────────────────────────────── + +export async function listOpenApiKeys( + ekbClient: KyInstance, + corpId: string +): Promise { + const response = await ekbClient.get("api/innerapi/v1/key", { + searchParams: { corpId }, + }); + const json = (await response.json()) as { items?: unknown[]; count?: number }; + const rawItems = json.items ?? []; + return z.array(OpenApiKeySchema).parse(rawItems); +} + +export async function getOpenConfig( + ekbClient: KyInstance, + corpId: string +): Promise { + const response = await ekbClient.get("api/innerapi/v1/openConfig", { + searchParams: { corpId }, + }); + const json = await response.json(); + return OpenConfigSchema.parse(json); +} + +// ── 应用商店与已购应用接口 ─────────────────────────────────────────────────── + +export async function listClientGoods( + unityClient: KyInstance, + corpId: string, + options: { name?: string; isAll?: boolean } = {} +): Promise { + const response = await unityClient.get("api/store/client/goods", { + searchParams: { + corpId, + name: options.name ?? "", + isAll: String(options.isAll ?? false), + }, + }); + const json = (await response.json()) as any; + const items = json?.value?.items ?? json?.items ?? json?.value ?? []; + return z.array(ClientGoodsSchema).parse(items); +} + +export async function searchStoreGoods( + unityClient: KyInstance, + corpId: string, + params: { name?: string; menuId?: string; start?: number; count?: number } = {} +): Promise<{ total: number; items: StoreGoodsItem[] }> { + const response = await unityClient.post("api/store/goods", { + searchParams: { corpId }, + json: { + menuId: params.menuId ?? "", + start: params.start ?? 0, + count: params.count ?? 20, + orderType: "recommend", + name: params.name ?? "", + goodsId: "all", + labelId: [], + }, + }); + const json = (await response.json()) as any; + const value = json?.value ?? {}; + const total = Number(value.total ?? 0); + const items = z.array(StoreGoodsItemSchema).parse(value.items ?? []); + return { total, items }; +} + +export async function getGoodsDetail( + unityClient: KyInstance, + corpId: string, + goodsId: string +): Promise { + const normalizedId = goodsId.startsWith("$") ? goodsId : `$${goodsId}`; + const response = await unityClient.get( + `api/store/client/goods/detail/${normalizedId}`, + { + searchParams: { corpId }, + } + ); + const json = (await response.json()) as any; + return GoodsDetailSchema.parse(json?.value ?? {}); +} diff --git a/src/domains/store/tools.ts b/src/domains/store/tools.ts new file mode 100644 index 0000000..1e6002c --- /dev/null +++ b/src/domains/store/tools.ts @@ -0,0 +1,74 @@ +import { createEkbClient } from "../../core/auth/ekb.js"; +import { getUnityClient } from "../../core/auth/easo.js"; +import type { CorpConfig } from "../../core/config/types.js"; +import { + listOpenApiKeys, + getOpenConfig, + listClientGoods, + searchStoreGoods, + getGoodsDetail, +} from "./api.js"; +import type { + OpenApiKey, + OpenConfig, + ClientGoods, + StoreGoodsItem, + GoodsDetail, +} from "./types.js"; + +export async function fetchOpenApiKeys(corp: CorpConfig): Promise { + const ekbClient = await createEkbClient(corp); + const corpId = corp.corpId || corp.credentials.corpId; + return listOpenApiKeys(ekbClient, corpId); +} + +export async function fetchOpenConfig(corp: CorpConfig): Promise { + const ekbClient = await createEkbClient(corp); + const corpId = corp.corpId || corp.credentials.corpId; + return getOpenConfig(ekbClient, corpId); +} + +export async function fetchClientGoods( + corp: CorpConfig, + options: { keyword?: string; isAll?: boolean } = {} +): Promise { + const { client: unityClient } = await getUnityClient(corp); + const corpId = corp.corpId || corp.credentials.corpId; + const items = await listClientGoods(unityClient, corpId, { + name: options.keyword, + isAll: options.isAll, + }); + + if (options.keyword && options.keyword.trim()) { + const kw = options.keyword.trim().toLowerCase(); + return items.filter( + (item) => + item.name.toLowerCase().includes(kw) || + (item.summary && item.summary.toLowerCase().includes(kw)) + ); + } + + return items; +} + +export async function searchGoods( + corp: CorpConfig, + options: { keyword?: string; start?: number; count?: number } = {} +): Promise<{ total: number; items: StoreGoodsItem[] }> { + const { client: unityClient } = await getUnityClient(corp); + const corpId = corp.corpId || corp.credentials.corpId; + return searchStoreGoods(unityClient, corpId, { + name: options.keyword, + start: options.start, + count: options.count, + }); +} + +export async function fetchGoodsDetail( + corp: CorpConfig, + goodsId: string +): Promise { + const { client: unityClient } = await getUnityClient(corp); + const corpId = corp.corpId || corp.credentials.corpId; + return getGoodsDetail(unityClient, corpId, goodsId); +} diff --git a/src/domains/store/types.ts b/src/domains/store/types.ts new file mode 100644 index 0000000..eb1e1cf --- /dev/null +++ b/src/domains/store/types.ts @@ -0,0 +1,112 @@ +import { z } from "zod"; + +// ── OpenAPI 密钥模型 ───────────────────────────────────────────────────────── + +export const OpenApiKeySchema = z.object({ + id: z.string(), + name: z.string().nullish().default(""), + appKey: z.string(), + appSecurity: z.string(), + active: z.boolean().default(true), + corporationId: z.string().optional(), + createTime: z.number().default(0), + updateTime: z.number().default(0), + authorities: z.any().nullish(), +}); + +export type OpenApiKey = z.infer; + +// ── 免登重定向配置模型 ─────────────────────────────────────────────────────── + +export const OpenConfigItemSchema = z + .object({ + id: z.string().optional(), + url: z.string().optional(), + }) + .passthrough(); + +export const OpenConfigSchema = z.object({ + items: z.array(OpenConfigItemSchema).default([]), +}); + +export type OpenConfig = z.infer; + +// ── 商店与应用模型 ─────────────────────────────────────────────────────────── + +export const GoodsPowerSchema = z + .object({ + id: z.string().optional(), + powerCode: z.string().optional(), + powerName: z.string().optional(), + paymentStatus: z.string().optional(), + chargeType: z.string().optional(), + authorizeType: z.string().optional(), + summary: z.string().nullish().default(""), + expireTime: z.any().optional(), + }) + .passthrough(); + +export type GoodsPower = z.infer; + +export const ClientGoodsSchema = z + .object({ + id: z.string(), + name: z.string(), + code: z.string().optional(), + summary: z.string().nullish().default(""), + menuId: z.string().optional(), + type: z.string().optional(), + logo: z.string().nullish().default(""), + status: z.string().nullish().default(""), + onLineStatus: z.string().nullish().default(""), + expireTime: z.number().nullish(), + powers: z.array(z.union([z.string(), GoodsPowerSchema])).nullish().default([]), + hasConfig: z.boolean().optional().default(false), + configStyle: z.string().optional(), + paymentMode: z.record(z.string(), z.any()).nullish(), + }) + .passthrough(); + +export type ClientGoods = z.infer; + +export const StoreGoodsItemSchema = z + .object({ + id: z.string(), + name: z.string(), + code: z.string().optional(), + summary: z.string().nullish().default(""), + menuId: z.string().optional(), + type: z.string().optional(), + logo: z.string().nullish().default(""), + status: z.string().nullish().default(""), + onLineStatus: z.string().nullish().default(""), + expireTime: z.number().nullish(), + powers: z.array(z.union([z.string(), GoodsPowerSchema])).nullish().default([]), + hasConfig: z.boolean().optional().default(false), + configStyle: z.string().optional(), + paymentMode: z.record(z.string(), z.any()).nullish(), + }) + .passthrough(); + +export type StoreGoodsItem = z.infer; + +export const GoodsDetailSchema = z + .object({ + id: z.string(), + name: z.string(), + code: z.string().optional(), + summary: z.string().nullish().default(""), + menuId: z.string().optional(), + type: z.string().optional(), + logo: z.string().nullish().default(""), + status: z.string().nullish().default(""), + powers: z.array(GoodsPowerSchema).nullish().default([]), + hasConfig: z.boolean().optional().default(false), + configStyle: z.string().optional(), + detailDesc: z.string().nullish().default(""), + paymentMode: z.record(z.string(), z.any()).nullish(), + expireTime: z.number().nullish(), + }) + .passthrough(); + +export type GoodsDetail = z.infer;