feat(store): 新增企业 OpenAPI 密钥一键提取(keys)与应用中心探查(store)能力

This commit is contained in:
gitea committed 2026-09-08 16:59:57 +08:00
1 parent 9a2d4529f5
commit 0c953df30e
14 files changed
+1159 -3

No files matched your search

+144
View File
@@ -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();
});
});
+98
View File
@@ -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<CliResult> {
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,
};
}
}
+7 -1
View File
@@ -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<CliResult> {
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":
+150
View File
@@ -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();
});
});
+239
View File
@@ -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<CliResult> {
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<CliResult> {
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<CliResult> {
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<CliResult> {
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,
};
}
}
+3 -1
View File
@@ -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=<owner/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 <ID>)
http 启动轻量 HTTP Server 与交互式文档 (http [--port=8888] [--host=127.0.0.1])
service 常驻守护进程管理 (service start|stop|restart|status|logs|poll)
mcp MCP Server 运行 (serve)
+10
View File
@@ -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":