Compare commits

...
11 Commits
Author SHA1 Message Date
yunyingk 2502a49fb9 Merge pull request #60 from yunyingk/release/v0.8.1
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
chore(release): bump version to v0.8.1
2026-09-09 09:24:54 +08:00
gitea 212371eb03 chore(release): bump version to v0.8.1 2026-09-09 09:23:47 +08:00
yunyingk e852dbfd47 Merge pull request #59 from yunyingk/feat/store-and-openapi-keys
feat(store): 新增企业 OpenAPI 密钥一键提取(keys)与应用中心探查(store)能力
2026-09-09 09:23:02 +08:00
gitea 0c953df30e feat(store): 新增企业 OpenAPI 密钥一键提取(keys)与应用中心探查(store)能力 2026-09-08 16:59:57 +08:00
yunyingk 9a2d4529f5 Merge pull request #58 from yunyingk/release/v0.8.0
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
chore(release): bump version to v0.8.0
2026-09-08 15:53:54 +08:00
gitea 3937d3799b chore(release): bump version to v0.8.0 2026-09-08 15:53:41 +08:00
yunyingk bcf8ac0de6 Merge pull request #57 from yunyingk/refactor_db_cache_cleanup
refactor(core): 规范数据库表结构、版本迁移与多级缓存体系加固
2026-09-08 15:49:57 +08:00
gitea 3a15b064fe refactor(core): 规范数据库表结构、版本迁移与多级缓存体系加固
- 数据库表规范化与原子事务版本迁移机制 (_schema_migrations)
- 增加 SQLite 复合主键、PRAGMA busy_timeout 与索引覆盖
- 构建统一两级协同缓存 (L1 Memory LRU + L2 SQLite 持久化)
- withCache 增加 In-flight Promise 去重并发防击穿 (单飞机制)
- 收敛 dimension、role、bill 与 token-store 缓存逻辑
- 100% 保持现有 API 契约与零功能删除
2026-09-08 15:49:27 +08:00
gitea 00cbf039eb chore(release): bump version to v0.7.5
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-09-08 14:04:03 +08:00
yunyingk a2eb04c4c1 Merge pull request #56 from yunyingk/codex/issue-55-auth-bill
fix(auth): guard temporary token refresh and translate bill flow
2026-09-08 12:11:35 +08:00
gitea 3f015d8e22 fix(auth): guard temporary token refresh and translate bill flow 2026-09-08 12:08:12 +08:00
50 changed files with 2667 additions and 301 deletions

No files matched your search

+2
View File
@@ -46,3 +46,5 @@ data/
# Local roadmaps & scratch notes
*.local.md
.agents/
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "hose-use",
"version": "0.7.4",
"version": "0.8.1",
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
"author": {
"name": "yingqing"
+1 -1
View File
@@ -1,4 +1,4 @@
# hose-use (v0.7.4)
# hose-use (v0.8.1)
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
+1 -1
View File
@@ -2,7 +2,7 @@
"openapi": "3.1.0",
"info": {
"title": "hose-use API & MCP Tools Specification",
"version": "0.7.4",
"version": "0.8.1",
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
},
"servers": [
+1 -1
View File
@@ -1,7 +1,7 @@
openapi: 3.1.0
info:
title: hose-use API & MCP Tools Specification
version: 0.7.4
version: 0.8.1
description: >-
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
servers:
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "hose-use",
"version": "0.7.4",
"version": "0.8.1",
"module": "src/server.ts",
"type": "module",
"bin": {
+4 -4
View File
@@ -1,12 +1,12 @@
---
name: hose-use
description: "v0.7.4: 合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号 API 登录、租户切换、单据检索与审批动作、工作流跨域扫描、内置 HTTP 交互文档与常驻守护进程。"
description: "v0.8.1: 合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号 API 登录、租户切换、单据检索与审批动作、工作流跨域扫描、内置 HTTP 交互文档与常驻守护进程。"
metadata:
version: 0.7.4
short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.7.4)
version: 0.8.1
short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.8.1)
---
# hose-use (v0.7.4)
# hose-use (v0.8.1)
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
+6
View File
@@ -49,11 +49,17 @@ hose-use corps add-link "https://wx2.ekuaibao.com/web/thirdparty.html?accessToke
# 可选附加别名与覆盖参数
hose-use corps add-link "<url>" --name="客户企业别名" --overwrite
# 未提供服务端 expTime 时,可显式指定本地有效期
hose-use corps add-link "<url>" --ttl 3d
hose-use corps add-link "<url>" --expires 3 # 等价于 3 天;--days 3 也可以
```
- **全自动识别与身份探测**:
- 自动从 URL 提取服务节点 `baseUrl`、集群环境 `cluster`(如 `wx2`、`app`)、`accessToken` 与 `corpId`;
- 自动向 `$UNITY` JWT 与主站 Session 反查员工工号 (`staffId`)、员工姓名、绑定手机、企业全称与是否企业管理员,无需手动寻找工号;
- 动态自适应多集群环境换票,确保主站单据审批与 EASO 低代码工作流平台权限全绿连通。
- 非账号来源(link/browser/assist/curl/manual)不会触发账号换票;Token 失效时提示重新导入链接。
- 服务端返回的 expTime 优先;未返回时不再强制套用 2 小时,可使用 `--ttl` / `--expires` 指定有效期。
### 代客协助凭证导入
```bash
+4
View File
@@ -240,6 +240,8 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
let staffId = stringOption(parsed.options, ["staff", "staffId"]);
let name = stringOption(parsed.options, ["name"]);
const overwrite = booleanOption(parsed.options, ["overwrite", "force", "f"], false);
const ttl = stringOption(parsed.options, ["ttl"]);
const expires = stringOption(parsed.options, ["expires", "days"]);
if (!raw && !accessToken && process.stdin.isTTY) {
raw = await prompt("请粘贴抓包文本 / cURL 命令行 / 协助免密 URL (直接回车则手动逐项输入): ");
@@ -270,6 +272,8 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
name,
baseUrl,
overwrite,
ttl,
expires,
source: raw && (raw.startsWith("http://") || raw.startsWith("https://")) ? "link" : undefined,
});
+2 -1
View File
@@ -6,6 +6,7 @@ import {
searchAndFormatBills,
getBillByCodeOrId,
getBillFlow,
formatBillFlowOperator,
getBillRisk,
getBillReferences,
getBillRelations,
@@ -339,7 +340,7 @@ export async function handleBillCommand(
entry.time ? new Date(entry.time).toLocaleString("zh-CN") : "-",
entry.nodeName || "-",
entry.action || "-",
entry.operator?.name || (entry.automatic ? "系统" : "-"),
formatBillFlowOperator(entry.operator, entry.automatic, entry.operator?.id?.toLowerCase().includes("ebot")),
entry.durationMs !== undefined ? `${Math.round(entry.durationMs / 1000)} 秒` : "-",
entry.skipped ? "自动跳过" : entry.automatic ? "自动" : "",
entry.comment || "-",
+5 -1
View File
@@ -160,6 +160,8 @@ async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promis
let linkUrl = parsed.args[0] || stringOption(parsed.options, ["url", "link"]);
const name = stringOption(parsed.options, ["name"]);
const overwrite = booleanOption(parsed.options, ["overwrite", "force", "f"], false);
const ttl = stringOption(parsed.options, ["ttl"]);
const expires = stringOption(parsed.options, ["expires", "days"]);
if (!linkUrl && process.stdin.isTTY) {
linkUrl = await prompt("请输入第三方协助/免密登录链接 URL: ");
@@ -168,7 +170,7 @@ async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promis
if (!linkUrl) {
return {
stdout: "",
stderr: "错误:必须提供协助/免密链接 URL!用法: hose-use corps add-link <url> [--name <企业别名>] [--overwrite]\n",
stderr: "错误:必须提供协助/免密链接 URL!用法: hose-use corps add-link <url> [--name <企业别名>] [--ttl 3d|--expires 3] [--overwrite]\n",
exitCode: 1,
};
}
@@ -177,6 +179,8 @@ async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promis
const corp = await importFromLink(linkUrl, {
name,
overwrite,
ttl,
expires,
});
if (runtime.jsonMode) {
+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":
+13 -2
View File
@@ -1,6 +1,6 @@
# Core 层说明
Core 层负责基础设施:企业配置管理、认证 Token 获取与缓存、HTTP 客户端工厂、统一异常语义。
Core 层负责基础设施:企业配置管理、认证 Token 获取与缓存、统一数据库与版本迁移、多级协同缓存、HTTP 客户端工厂、统一异常语义。
## 代码结构
@@ -13,7 +13,16 @@ src/core/
│ ├── ekb.ts # 快报主站三 Header 认证
│ ├── easo.ts # EASO(unity.ekuaibao.com)四步认证
│ ├── piper.ts # Piper(piper.ekuaibao.com)三步认证
│ ├── token-store.ts # 动态 Token 缓存(~/.cache/ekb-mcp/tokens.json)
│ ├── token-store.ts # 动态 Token 缓存(兼容 ~/.config/hose-use/tokens.json 与历史路径)
│ └── types.ts
├── cache/ # 统一多级协同缓存
│ ├── memory.ts # L1 内存缓存(TTL、容量限制、按命名空间清理)
│ ├── sqlite.ts # L2 SQLite 持久化缓存(跨 CLI 进程复用)
│ ├── multi-level.ts # 多级联动门面与 withCache 透明包装器
│ └── types.ts
├── db/ # 统一 SQLite 数据库与结构化版本迁移
│ ├── connection.ts # SQLite 单例、WAL 模式、文件权限 0o600 保护
│ ├── migrations.ts # 结构化增量迁移运行器(_schema_migrations)
│ └── types.ts
├── config/ # 企业配置管理
│ ├── loader.ts
@@ -29,3 +38,5 @@ src/core/
- `domains/*/api.ts` 只通过 `core/http/factory.ts` 或 `core/auth/*` 获取客户端
- `domains/*` 层只抛 `EkbError` 子类
- `server.ts` 负责把 `EkbError` 映射为 MCP error
- 业务域如果需要缓存,统一使用 `core/cache/` 提供的多级缓存门面
- 业务域如果需要持久化数据,统一接入 `core/db/` 并注册版本迁移
+61 -1
View File
@@ -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<typeof createAuthClient>;
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);
},
}),
};
}
+52
View File
@@ -0,0 +1,52 @@
import { describe, expect, it } from "bun:test";
import { canRefreshCorpAccessToken, resolveLinkExpiresAt } from "./login.js";
import { createEkbClient } from "./ekb.js";
import type { CorpConfig } from "../config/types.js";
function corp(overrides: Partial<CorpConfig> = {}): CorpConfig {
return {
id: "corp-1",
name: "测试企业",
source: "link",
credentials: { accessToken: "token", corpId: "corp-1", staffId: "staff-1" },
...overrides,
baseUrl: overrides.baseUrl ?? "https://app.ekuaibao.com",
};
}
describe("core/auth/ekb refresh policy", () => {
it("only allows account credentials with an explicit account binding to refresh", () => {
expect(canRefreshCorpAccessToken(corp())).toBe(false);
expect(canRefreshCorpAccessToken(corp({ source: "browser", accountId: "86-1" }))).toBe(false);
expect(canRefreshCorpAccessToken(corp({ source: "account" }))).toBe(false);
expect(canRefreshCorpAccessToken(corp({ source: "account", accountId: "86-1" }))).toBe(true);
expect(canRefreshCorpAccessToken(corp({ source: "account", accountId: "86-1", session: { isShortTermToken: true } }))).toBe(false);
});
it("fails expired temporary credentials without retrying or refreshing", async () => {
const originalFetch = globalThis.fetch;
let calls = 0;
globalThis.fetch = (async () => {
calls += 1;
return new Response("expired", { status: 401 });
}) as unknown as typeof fetch;
try {
const client = await createEkbClient(corp());
await expect(client.get("api/test")).rejects.toThrow("临时凭证已过期,请使用 hose-use corps add-link 重新导入");
expect(calls).toBe(1);
} finally {
globalThis.fetch = originalFetch;
}
});
});
describe("core/auth/login link expiry", () => {
it("parses explicit ttl and expires durations", () => {
const base = 1_700_000_000_000;
expect(resolveLinkExpiresAt({ ttl: "72h" }, base)).toBe(base + 72 * 60 * 60 * 1000);
expect(resolveLinkExpiresAt({ ttl: "3d" }, base)).toBe(base + 3 * 24 * 60 * 60 * 1000);
expect(resolveLinkExpiresAt({ expires: "3" }, base)).toBe(base + 3 * 24 * 60 * 60 * 1000);
expect(resolveLinkExpiresAt({}, base)).toBeUndefined();
});
});
+16 -6
View File
@@ -1,6 +1,7 @@
import { CorpConfig } from "../config/types.js";
import { AuthenticationError } from "../errors.js";
import { createAuthClient } from "../http/factory.js";
import { refreshSingleCorpAccessToken } from "./login.js";
import { canRefreshCorpAccessToken, refreshSingleCorpAccessToken } from "./login.js";
export function getEkbHeaders(corp: CorpConfig): Record<string, string> {
return {
@@ -11,20 +12,29 @@ export function getEkbHeaders(corp: CorpConfig): Record<string, string> {
}
export async function createEkbClient(corp: CorpConfig) {
const canRefresh = canRefreshCorpAccessToken(corp);
// 1. 预检:若 Token 即将过期 (提前 refreshTtl 秒),静默无感自动续杯
if (corp.auth?.expiresAt) {
if (canRefresh && corp.auth?.expiresAt) {
const ttlMs = (corp.auth.refreshTtl || 300) * 1000;
if (Date.now() >= corp.auth.expiresAt - ttlMs) {
await refreshSingleCorpAccessToken(corp);
}
}
// 2. 使用带 401 自动重试与换票的 AuthClient
// 2. 仅账号凭证启用 401 自动重试与换票;临时凭证直接给出可操作错误
return createAuthClient({
prefixUrl: corp.baseUrl || "https://app.ekuaibao.com",
getHeaders: () => getEkbHeaders(corp),
onUnauthorized: async () => {
await refreshSingleCorpAccessToken(corp);
},
retryUnauthorized: canRefresh,
...(canRefresh
? {
onUnauthorized: async () => {
await refreshSingleCorpAccessToken(corp);
},
}
: {
onAuthFailure: () => new AuthenticationError("临时凭证已过期,请使用 hose-use corps add-link 重新导入"),
}),
});
}
+38 -4
View File
@@ -231,6 +231,8 @@ export interface F12ImportParams {
source?: import("../config/types.js").CredentialSource;
enterprisesDir?: string;
overwrite?: boolean;
ttl?: string | number;
expires?: string | number;
}
export interface ImportFromLinkOptions {
@@ -238,6 +240,34 @@ export interface ImportFromLinkOptions {
baseUrl?: string;
enterprisesDir?: string;
overwrite?: boolean;
ttl?: string | number;
expires?: string | number;
}
export function canRefreshCorpAccessToken(corp: CorpConfig): boolean {
return corp.source === "account" && !corp.session?.isShortTermToken && Boolean(corp.accountId);
}
function parseDurationMs(value: string | number, defaultUnit: "hours" | "days"): number {
const raw = String(value).trim().toLowerCase();
const match = raw.match(/^(\d+(?:\.\d+)?)\s*(h|hr|hrs|hour|hours|d|day|days)?$/);
if (!match) throw new AuthenticationError(`无效的有效期参数: ${value}(示例:3d、72h)`);
const amount = Number(match[1]);
if (!Number.isFinite(amount) || amount <= 0) {
throw new AuthenticationError(`有效期必须是大于 0 的数字: ${value}`);
}
const unit = match[2];
const isDays = unit ? ["d", "day", "days"].includes(unit) : defaultUnit === "days";
return amount * (isDays ? 24 : 1) * 60 * 60 * 1000;
}
export function resolveLinkExpiresAt(
options: { ttl?: string | number; expires?: string | number },
baseTime = Date.now()
): number | undefined {
if (options.ttl !== undefined) return baseTime + parseDurationMs(options.ttl, "hours");
if (options.expires !== undefined) return baseTime + parseDurationMs(options.expires, "days");
return undefined;
}
/**
@@ -361,6 +391,7 @@ export async function importCredentials(
let isAdmin: boolean | undefined;
let sourceChannel: string | undefined;
let jwtExpMs: number | undefined;
const requestedExpiresAt = resolveLinkExpiresAt(params);
try {
const jwtHeaders: Record<string, string> = {
@@ -495,9 +526,8 @@ export async function importCredentials(
expiresAt = sessionData.expTime;
} else if (jwtExpMs && jwtExpMs > 0) {
expiresAt = jwtExpMs;
} else if ((sessionData?.isAssistPlatform || source === "link") && sessionData?.loginTime) {
// 协助/免密平台短期调试 Token 通常 2 小时有效
expiresAt = sessionData.loginTime + 2 * 3600 * 1000;
} else if (requestedExpiresAt) {
expiresAt = requestedExpiresAt;
}
const corpConfig: CorpConfig = {
@@ -566,6 +596,8 @@ export async function importFromLink(
enterprisesDir: options.enterprisesDir,
overwrite: options.overwrite,
source: "link",
ttl: options.ttl,
expires: options.expires,
});
}
@@ -679,7 +711,9 @@ export async function refreshSingleCorpAccessToken(
businessCenterUrl: string = DEFAULT_BUSINESS_CENTER_URL,
idpUrl: string = DEFAULT_IDP_URL
): Promise<boolean> {
const account = corp.accountId ? getAccount(corp.accountId) : getActiveAccount();
if (!canRefreshCorpAccessToken(corp)) return false;
const account = getAccount(corp.accountId!);
if (!account?.cloudAuthToken) return false;
try {
+72 -13
View File
@@ -1,31 +1,82 @@
import { readFileSync, writeFileSync, mkdirSync } from "fs";
import { join, dirname } from "path";
import { chmodSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "fs";
import { homedir } from "os";
import { dirname, join } from "path";
import { TokenStore, TokenStoreSchema } from "./types";
const TOKEN_CACHE_PATH = join(
export const PRIMARY_TOKEN_CACHE_PATH = join(
homedir(),
".config",
"hose-use",
"tokens.json"
);
export const LEGACY_TOKEN_CACHE_PATH = join(
homedir(),
".cache",
"ekb-mcp",
"tokens.json"
);
function ensureDir(path: string): void {
mkdirSync(dirname(path), { recursive: true });
function resolveTokenCachePath(): string {
if (existsSync(PRIMARY_TOKEN_CACHE_PATH)) {
return PRIMARY_TOKEN_CACHE_PATH;
}
if (existsSync(LEGACY_TOKEN_CACHE_PATH)) {
return LEGACY_TOKEN_CACHE_PATH;
}
return PRIMARY_TOKEN_CACHE_PATH;
}
export function loadTokenStore(): TokenStore {
try {
const content = readFileSync(TOKEN_CACHE_PATH, "utf-8");
return TokenStoreSchema.parse(JSON.parse(content));
} catch {
return {};
function ensureDir(path: string): void {
const dir = dirname(path);
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true, mode: 0o700 });
}
try {
chmodSync(dir, 0o700);
} catch {}
}
let memoryTokenCache: TokenStore | null = null;
let lastMtimeMs = 0;
export function loadTokenStore(): TokenStore {
const filePath = resolveTokenCachePath();
if (existsSync(filePath)) {
try {
const stats = statSync(filePath);
if (memoryTokenCache && stats.mtimeMs === lastMtimeMs) {
return memoryTokenCache;
}
const content = readFileSync(filePath, "utf-8");
const parsed = TokenStoreSchema.parse(JSON.parse(content));
memoryTokenCache = parsed;
lastMtimeMs = stats.mtimeMs;
return parsed;
} catch {
// 若已有内存缓存则保留,避免解析失败直接冲刷为 {}
return memoryTokenCache ?? {};
}
}
return memoryTokenCache ?? {};
}
export function saveTokenStore(store: TokenStore): void {
ensureDir(TOKEN_CACHE_PATH);
writeFileSync(TOKEN_CACHE_PATH, JSON.stringify(store, null, 2));
memoryTokenCache = store;
const targetPath = PRIMARY_TOKEN_CACHE_PATH;
ensureDir(targetPath);
// MAJ-03: 强制写入 0o600 保护敏感凭证
writeFileSync(targetPath, JSON.stringify(store, null, 2), {
encoding: "utf-8",
mode: 0o600,
});
try {
chmodSync(targetPath, 0o600);
lastMtimeMs = statSync(targetPath).mtimeMs;
} catch {}
}
export function getCorpTokens(corpId: string): TokenStore[string] | undefined {
@@ -44,3 +95,11 @@ export function clearCorpTokens(corpId: string): void {
delete store[corpId];
saveTokenStore(store);
}
/**
* 重置内存 Token 缓存(测试隔离用)
*/
export function resetTokenStoreMemory(): void {
memoryTokenCache = null;
lastMtimeMs = 0;
}
+162
View File
@@ -0,0 +1,162 @@
import { Database } from "bun:sqlite";
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { closeDatabase, getDatabase } from "../db/connection.js";
import { MemoryCache } from "./memory.js";
import { MultiLevelCache } from "./multi-level.js";
import { SqliteCache } from "./sqlite.js";
describe("Core Cache - 多级缓存架构与淘汰机制 (加固测试)", () => {
let db: Database;
beforeEach(() => {
db = getDatabase(":memory:");
});
afterEach(() => {
closeDatabase();
});
describe("L1: MemoryCache", () => {
test("基础读写、删除与命名空间隔离", () => {
const cache = new MemoryCache();
cache.set("100", { name: "用户A" }, { namespace: "users" });
cache.set("100", { title: "角色B" }, { namespace: "roles" });
// CRIT-02 验证:相同 key 在不同命名空间下完全隔离、互不覆写
expect(cache.get<{ name: string }>("100", "users")).toEqual({ name: "用户A" });
expect(cache.get<{ title: string }>("100", "roles")).toEqual({ title: "角色B" });
expect(cache.has("100", "users")).toBe(true);
expect(cache.has("100", "departments")).toBe(false);
// 按 namespace 清理
cache.clear("users");
expect(cache.get("100", "users")).toBeUndefined();
expect(cache.get<{ title: string }>("100", "roles")).toEqual({ title: "角色B" });
// 单条删除
cache.delete("100", "roles");
expect(cache.get("100", "roles")).toBeUndefined();
});
test("TTL 过期检查", async () => {
const cache = new MemoryCache();
cache.set("temp", "value", { ttlMs: 10 });
expect(cache.get<string>("temp")).toBe("value");
await new Promise((r) => setTimeout(r, 20));
expect(cache.get("temp")).toBeUndefined();
});
test("严格 LRU 访问热度调整与容量淘汰 (MAJ-08 & MAJ-09)", () => {
const cache = new MemoryCache(3);
cache.set("k1", "v1");
cache.set("k2", "v2");
cache.set("k3", "v3");
// 访问 k1,使 k1 成为最热的条目(移至队尾)
expect(cache.get<string>("k1")).toBe("v1");
// 此时最冷的是 k2。插入 k4 触发容量超限(容量 3)
cache.set("k4", "v4");
// 验证 k2 被淘汰,而最近被访问的 k1 依然存活
expect(cache.get("k2")).toBeUndefined();
expect(cache.get<string>("k1")).toBe("v1");
expect(cache.get<string>("k3")).toBe("v3");
expect(cache.get<string>("k4")).toBe("v4");
// 更新已有键不会增加容量,也不会误伤淘汰其他键
cache.set("k1", "v1_updated");
expect(cache.size()).toBe(3);
expect(cache.get<string>("k1")).toBe("v1_updated");
});
});
describe("L2: SqliteCache", () => {
test("复合主键 (namespace, key) 跨域存储与隔离 (CRIT-02)", () => {
const cache = new SqliteCache(db);
cache.set("id_1", { type: "dim" }, { namespace: "dimensions" });
cache.set("id_1", { type: "role" }, { namespace: "roles" });
const dim = cache.get<{ type: string }>("id_1", "dimensions");
const role = cache.get<{ type: string }>("id_1", "roles");
expect(dim?.type).toBe("dim");
expect(role?.type).toBe("role");
// 验证底层 SQLite 表结构行记录
const rows = db.query("SELECT namespace, key FROM cache_entries WHERE key = 'id_1'").all() as any[];
expect(rows.length).toBe(2);
// 按 namespace 清除
cache.clear("dimensions");
expect(cache.get("id_1", "dimensions")).toBeUndefined();
expect(cache.get("id_1", "roles")).toBeDefined();
});
test("TTL 过期与 pruneExpired 清理", async () => {
const cache = new SqliteCache(db);
cache.set("expire_soon", "data", { ttlMs: 15 });
expect(cache.get<string>("expire_soon")).toBe("data");
await new Promise((r) => setTimeout(r, 25));
expect(cache.get("expire_soon")).toBeUndefined();
cache.set("stale", "foo", { ttlMs: 5 });
await new Promise((r) => setTimeout(r, 15));
const pruned = cache.pruneExpired();
expect(pruned).toBeGreaterThanOrEqual(1);
});
});
describe("MultiLevelCache 两级协同与防击穿 (MAJ-01)", () => {
test("L1 miss 后从 L2 命中并自动回填至 L1", () => {
const l1 = new MemoryCache();
const l2 = new SqliteCache(db);
const multi = new MultiLevelCache({ l1, l2 });
multi.set("order:100", { amount: 888 }, { namespace: "orders" });
// 手动清空 L1 模拟内存冷启动
l1.clear();
expect(l1.get("order:100", "orders")).toBeUndefined();
// 从多级缓存读取:从 L2 命中,并回填至 L1
const val = multi.get<{ amount: number }>("order:100", "orders");
expect(val).toEqual({ amount: 888 });
// 验证 L1 已被自动回填
expect(l1.get<{ amount: number }>("order:100", "orders")).toEqual({ amount: 888 });
});
test("并发防击穿 (Thundering Herd Protection / In-flight Deduplication)", async () => {
const multi = new MultiLevelCache({ l2: new SqliteCache(db) });
let fetchCount = 0;
const slowFetcher = async () => {
fetchCount++;
await new Promise((r) => setTimeout(r, 20)); // 模拟慢网络
return { data: "fresh", fetchCount };
};
// 模拟 10 个并发请求在缓存冷启动时同时调用 withCache
const promises = Array.from({ length: 10 }).map(() =>
multi.withCache("concurrent_key", slowFetcher, {
namespace: "test_herd",
ttlMs: 5000,
})
);
const results = await Promise.all(promises);
// 验证:所有并发请求获取到相同的数据
expect(results.length).toBe(10);
for (const res of results) {
expect(res.fetchCount).toBe(1);
}
// 核心断言:底层 slowFetcher 严格只被调用了 1 次!彻底防御了缓存击穿
expect(fetchCount).toBe(1);
});
});
});
+35
View File
@@ -0,0 +1,35 @@
import { MultiLevelCache, type MultiLevelCacheOptions } from "./multi-level.js";
export * from "./types.js";
export * from "./memory.js";
export * from "./sqlite.js";
export * from "./multi-level.js";
let defaultCacheInstance: MultiLevelCache | null = null;
/**
* 获取全局默认多级缓存实例(单例)
*/
export function getGlobalCache(): MultiLevelCache {
if (!defaultCacheInstance) {
defaultCacheInstance = new MultiLevelCache();
}
return defaultCacheInstance;
}
/**
* 创建独立的多级缓存实例
*/
export function createMultiLevelCache(options?: MultiLevelCacheOptions): MultiLevelCache {
return new MultiLevelCache(options);
}
/**
* 重置全局缓存实例(测试清理用)
*/
export function resetGlobalCache(): void {
if (defaultCacheInstance) {
defaultCacheInstance.clear();
defaultCacheInstance = null;
}
}
+143
View File
@@ -0,0 +1,143 @@
import type { CacheEntry, CacheOptions, ICache } from "./types.js";
const DEFAULT_TTL_MS = 10 * 60 * 1000; // 10 分钟
const DEFAULT_MAX_ENTRIES = 2000;
export class MemoryCache implements ICache {
// Map 保持键的插入顺序,结合重新插入机制实现高效的 O(1) LRU 淘汰
private map = new Map<string, CacheEntry<any>>();
private maxEntries: number;
constructor(maxEntries = DEFAULT_MAX_ENTRIES) {
this.maxEntries = maxEntries;
}
/**
* CRIT-02: 构建命名空间隔离的复合内存键,彻底规避跨域碰撞
*/
private toCompositeKey(key: string, namespace?: string): string {
const ns = namespace || "default";
return `${ns}:${key}`;
}
public get<T>(key: string, namespace = "default"): T | undefined {
const compositeKey = this.toCompositeKey(key, namespace);
const entry = this.map.get(compositeKey);
if (!entry) return undefined;
const now = Date.now();
if (entry.expiresAt <= now) {
this.map.delete(compositeKey);
return undefined;
}
// MAJ-09: 真正 LRU 访问刷新 —— 命中后移至 Map 末尾
this.map.delete(compositeKey);
this.map.set(compositeKey, entry);
return entry.value as T;
}
public getEntry<T>(key: string, namespace = "default"): CacheEntry<T> | undefined {
const compositeKey = this.toCompositeKey(key, namespace);
const entry = this.map.get(compositeKey);
if (!entry) return undefined;
const now = Date.now();
if (entry.expiresAt <= now) {
this.map.delete(compositeKey);
return undefined;
}
// 命中后移至 Map 末尾保持热度
this.map.delete(compositeKey);
this.map.set(compositeKey, entry);
return entry as CacheEntry<T>;
}
public set<T>(key: string, value: T, options?: CacheOptions): void {
const namespace = options?.namespace ?? "default";
const compositeKey = this.toCompositeKey(key, namespace);
const now = Date.now();
const ttl = options?.ttlMs ?? DEFAULT_TTL_MS;
const entry: CacheEntry<T> = {
value,
expiresAt: now + ttl,
updatedAt: now,
namespace,
};
// MAJ-08: 更新已有键时,先删后插调至末尾,不应误触发 LRU 淘汰
if (this.map.has(compositeKey)) {
this.map.delete(compositeKey);
this.map.set(compositeKey, entry);
return;
}
// 若达到容量限制,执行 LRU 淘汰
if (this.map.size >= this.maxEntries) {
this.evict();
}
this.map.set(compositeKey, entry);
}
public setEntry<T>(key: string, entry: CacheEntry<T>): void {
const compositeKey = this.toCompositeKey(key, entry.namespace);
if (this.map.has(compositeKey)) {
this.map.delete(compositeKey);
} else if (this.map.size >= this.maxEntries) {
this.evict();
}
this.map.set(compositeKey, entry);
}
public delete(key: string, namespace = "default"): void {
const compositeKey = this.toCompositeKey(key, namespace);
this.map.delete(compositeKey);
}
public clear(namespace?: string): void {
if (!namespace) {
this.map.clear();
return;
}
const prefix = `${namespace}:`;
for (const k of this.map.keys()) {
if (k.startsWith(prefix)) {
this.map.delete(k);
}
}
}
public has(key: string, namespace = "default"): boolean {
return this.get(key, namespace) !== undefined;
}
public size(): number {
return this.map.size;
}
private evict(): void {
const now = Date.now();
// 1. 优先剔除已过期的死键
for (const [k, v] of this.map.entries()) {
if (v.expiresAt <= now) {
this.map.delete(k);
}
}
// 2. 若仍然超限,按真正的 LRU(头部为最久未访问的条目)淘汰最早的条目
while (this.map.size >= this.maxEntries) {
const oldestKey = this.map.keys().next().value;
if (oldestKey !== undefined) {
this.map.delete(oldestKey);
} else {
break;
}
}
}
}
+113
View File
@@ -0,0 +1,113 @@
import { MemoryCache } from "./memory.js";
import { SqliteCache } from "./sqlite.js";
import type { CacheOptions, ICache, WithCacheOptions } from "./types.js";
export interface MultiLevelCacheOptions {
l1?: MemoryCache;
l2?: SqliteCache | null;
}
export class MultiLevelCache implements ICache {
private l1: MemoryCache;
private l2: SqliteCache | null;
// MAJ-01: 防击穿 / 单飞并发请求去重表 (In-flight Promise Deduplication)
private inFlight = new Map<string, Promise<any>>();
constructor(options?: MultiLevelCacheOptions) {
this.l1 = options?.l1 ?? new MemoryCache();
this.l2 = options?.l2 !== undefined ? options.l2 : new SqliteCache();
}
public get<T>(key: string, namespace = "default"): T | undefined {
// 1. 优先从 L1 (Memory) 获取
const l1Value = this.l1.get<T>(key, namespace);
if (l1Value !== undefined) {
return l1Value;
}
// 2. L1 穿透,查询 L2 (SQLite 持久化)
if (this.l2) {
const l2Entry = this.l2.getEntry<T>(key, namespace);
if (l2Entry !== undefined) {
// 回填至 L1,保持相同的到期时间与命名空间
this.l1.setEntry(key, l2Entry);
return l2Entry.value;
}
}
return undefined;
}
public set<T>(key: string, value: T, options?: CacheOptions): void {
// 同时写入 L1 与 L2
this.l1.set(key, value, options);
if (this.l2) {
this.l2.set(key, value, options);
}
}
public delete(key: string, namespace = "default"): void {
this.l1.delete(key, namespace);
if (this.l2) {
this.l2.delete(key, namespace);
}
}
public clear(namespace?: string): void {
this.l1.clear(namespace);
if (this.l2) {
this.l2.clear(namespace);
}
}
public has(key: string, namespace = "default"): boolean {
return this.get(key, namespace) !== undefined;
}
/**
* MAJ-01: 业务透明包装器,自动多级缓存查验 + In-flight 请求合并防击穿
*/
public async withCache<T>(
key: string,
fetcher: () => Promise<T>,
options?: WithCacheOptions
): Promise<T> {
const namespace = options?.namespace ?? "default";
const lockKey = `${namespace}:${key}`;
if (!options?.forceRefresh) {
const cached = this.get<T>(key, namespace);
if (cached !== undefined) {
return cached;
}
}
// 防击穿:检查是否已有相同命名空间与键的并发请求在执行中
const ongoing = this.inFlight.get(lockKey);
if (ongoing) {
return ongoing as Promise<T>;
}
const promise = (async () => {
try {
const fresh = await fetcher();
this.set(key, fresh, options);
return fresh;
} finally {
this.inFlight.delete(lockKey);
}
})();
this.inFlight.set(lockKey, promise);
return promise;
}
/**
* 清理过期条目(MIN-11: L1 与 L2 同步清理)
*/
public pruneExpired(): void {
if (this.l2) {
this.l2.pruneExpired();
}
}
}
+128
View File
@@ -0,0 +1,128 @@
import type { Database } from "bun:sqlite";
import { getDatabase } from "../db/connection.js";
import type { CacheEntry, CacheOptions, ICache } from "./types.js";
const DEFAULT_TTL_MS = 10 * 60 * 1000; // 10 分钟
interface CacheRow {
namespace: string;
key: string;
value: string;
expires_at: number;
updated_at: number;
}
export class SqliteCache implements ICache {
private db: Database;
constructor(db?: Database) {
this.db = db ?? getDatabase();
}
public get<T>(key: string, namespace = "default"): T | undefined {
const entry = this.getEntry<T>(key, namespace);
return entry ? entry.value : undefined;
}
public getEntry<T>(key: string, namespace = "default"): CacheEntry<T> | undefined {
try {
const row = this.db
.query(
"SELECT namespace, key, value, expires_at, updated_at FROM cache_entries WHERE namespace = ? AND key = ?"
)
.get(namespace, key) as CacheRow | null;
if (!row) return undefined;
const now = Date.now();
if (row.expires_at <= now) {
this.delete(key, namespace);
return undefined;
}
const parsedValue = JSON.parse(row.value) as T;
return {
value: parsedValue,
expiresAt: row.expires_at,
updatedAt: row.updated_at,
namespace: row.namespace,
};
} catch {
// 容错处理损坏数据
this.delete(key, namespace);
return undefined;
}
}
public set<T>(key: string, value: T, options?: CacheOptions): void {
if (value === undefined) {
// MIN-05: undefined 语义等同于清除该键
this.delete(key, options?.namespace);
return;
}
const now = Date.now();
const ttl = options?.ttlMs ?? DEFAULT_TTL_MS;
const namespace = options?.namespace ?? "default";
const expiresAt = now + ttl;
try {
const serialized = JSON.stringify(value);
this.db.run(
`
INSERT INTO cache_entries (namespace, key, value, expires_at, updated_at)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(namespace, key) DO UPDATE SET
value = excluded.value,
expires_at = excluded.expires_at,
updated_at = excluded.updated_at
`,
[namespace, key, serialized, expiresAt, now]
);
} catch (err) {
console.error(`[cache] SqliteCache.set error for ${namespace}:${key}:`, err);
}
}
public delete(key: string, namespace = "default"): void {
try {
this.db.run(
"DELETE FROM cache_entries WHERE namespace = ? AND key = ?",
[namespace, key]
);
} catch {
// 容错
}
}
public clear(namespace?: string): void {
try {
if (namespace) {
this.db.run("DELETE FROM cache_entries WHERE namespace = ?", [namespace]);
} else {
this.db.run("DELETE FROM cache_entries");
}
} catch {
// 容错
}
}
public has(key: string, namespace = "default"): boolean {
return this.get(key, namespace) !== undefined;
}
/**
* 主动清理数据库中所有过期缓存记录
*/
public pruneExpired(): number {
try {
const result = this.db.run(
"DELETE FROM cache_entries WHERE expires_at <= ?",
[Date.now()]
);
return result.changes;
} catch {
return 0;
}
}
}
+32
View File
@@ -0,0 +1,32 @@
export interface CacheOptions {
/**
* 缓存有效时长(毫秒),默认 10 分钟 (600,000 ms)
*/
ttlMs?: number;
/**
* 命名空间,便于按业务模块隔离与批量失效(例如: 'dimensions', 'roles', 'bills')
*/
namespace?: string;
}
export interface CacheEntry<T> {
value: T;
expiresAt: number;
updatedAt: number;
namespace: string;
}
export interface ICache {
get<T>(key: string): Promise<T | undefined> | T | undefined;
set<T>(key: string, value: T, options?: CacheOptions): Promise<void> | void;
delete(key: string): Promise<void> | void;
clear(namespace?: string): Promise<void> | void;
has(key: string): Promise<boolean> | boolean;
}
export interface WithCacheOptions extends CacheOptions {
/**
* 是否强制穿透缓存刷新
*/
forceRefresh?: boolean;
}
+104
View File
@@ -0,0 +1,104 @@
import { Database } from "bun:sqlite";
import { chmodSync, existsSync, mkdirSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { runMigrations } from "./migrations.js";
import type { DatabaseConnectionOptions } from "./types.js";
export const DEFAULT_DB_PATH = join(
homedir(),
".config",
"hose-use",
"approval.db"
);
export function resolveDatabasePath(): string {
const envPath = process.env.HOSE_APPROVAL_DB?.trim();
if (envPath) {
return envPath;
}
return DEFAULT_DB_PATH;
}
let activeDb: Database | null = null;
let currentDbPath: string | null = null;
/**
* 获取或创建 SQLite 数据库连接单例,自动执行版本迁移
*/
export function getDatabase(options?: DatabaseConnectionOptions | string): Database {
const customPath = typeof options === "string" ? options : options?.customPath;
const targetPath = customPath ?? resolveDatabasePath();
if (activeDb && currentDbPath === targetPath) {
return activeDb;
}
// 若存在旧的不同路径连接,先优雅关闭释放文件句柄 (MAJ-12)
if (activeDb && currentDbPath !== targetPath) {
closeDatabase();
}
// 内存数据库无需创建物理目录
if (targetPath !== ":memory:") {
const dir = dirname(targetPath);
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true, mode: 0o700 });
}
try {
chmodSync(dir, 0o700);
} catch {}
}
const db = new Database(targetPath);
if (targetPath !== ":memory:") {
// 保护敏感业务规则、缓存、会话与审计数据 (0o600)
try {
chmodSync(targetPath, 0o600);
} catch {
// 容错处理
}
}
// 启用 WAL 模式与并发优化
db.run("PRAGMA journal_mode = WAL;");
db.run("PRAGMA foreign_keys = ON;");
// 关键:避免 0ms 锁超时崩溃,允许并发等待 5000ms (MAJ-02)
db.run("PRAGMA busy_timeout = 5000;");
db.run("PRAGMA synchronous = NORMAL;");
try {
// 自动执行结构化原子迁移
runMigrations(db);
} catch (err) {
// CRIT-03: 若迁移失败,坚决不激活单例缓存,关闭句柄并向外抛出错误
try {
db.close();
} catch {}
activeDb = null;
currentDbPath = null;
throw err;
}
// 迁移彻底成功后,才正式激活单例
currentDbPath = targetPath;
activeDb = db;
return db;
}
/**
* 关闭并清理当前活跃数据库连接
*/
export function closeDatabase(): void {
if (activeDb) {
try {
activeDb.close();
} catch {
// 容错
}
activeDb = null;
currentDbPath = null;
}
}
+72
View File
@@ -0,0 +1,72 @@
import { Database } from "bun:sqlite";
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { closeDatabase, getDatabase } from "./connection.js";
import { runMigrations } from "./migrations.js";
describe("Core DB - 数据库连接与结构化迁移机制 (加固测试)", () => {
let db: Database;
beforeEach(() => {
db = getDatabase(":memory:");
});
afterEach(() => {
closeDatabase();
});
test("数据库初始化时自动应用所有版本迁移并记录到 _schema_migrations", () => {
const rows = db.query("SELECT version, name FROM _schema_migrations ORDER BY version ASC").all() as Array<{
version: number;
name: string;
}>;
expect(rows.length).toBeGreaterThanOrEqual(1);
expect(rows[0].version).toBe(1);
expect(rows[0].name).toBe("001_core_schema_and_approval_tables");
});
test("核心数据表与新增的多级缓存表结构完备且索引有效", () => {
// 检查表是否存在
const tables = db
.query("SELECT name FROM sqlite_master WHERE type = 'table'")
.all() as Array<{ name: string }>;
const tableNames = new Set(tables.map((t) => t.name));
expect(tableNames.has("rules")).toBe(true);
expect(tableNames.has("preferences")).toBe(true);
expect(tableNames.has("approval_runs")).toBe(true);
expect(tableNames.has("approval_findings")).toBe(true);
expect(tableNames.has("aipro_logs")).toBe(true);
expect(tableNames.has("cache_entries")).toBe(true);
// 检查加固索引:UPPER(short_id)、findings(rule_id)
const indices = db
.query("SELECT name FROM sqlite_master WHERE type = 'index'")
.all() as Array<{ name: string }>;
const indexNames = new Set(indices.map((i) => i.name));
expect(indexNames.has("idx_runs_corp_id")).toBe(true);
expect(indexNames.has("idx_runs_expires_at")).toBe(true);
expect(indexNames.has("idx_runs_flow_id")).toBe(true);
expect(indexNames.has("idx_runs_short_id_upper")).toBe(true);
expect(indexNames.has("idx_findings_rule_id")).toBe(true);
expect(indexNames.has("idx_cache_namespace")).toBe(true);
expect(indexNames.has("idx_cache_expires_at")).toBe(true);
});
test("cache_entries 具备复合主键 (namespace, key) 约束", () => {
db.run(
"INSERT INTO cache_entries (namespace, key, value, expires_at, updated_at) VALUES ('n1', 'k1', 'v1', 9999, 1000)"
);
// 相同 key 但不同 namespace 可以成功插入
db.run(
"INSERT INTO cache_entries (namespace, key, value, expires_at, updated_at) VALUES ('n2', 'k1', 'v2', 9999, 1000)"
);
const countRow = db.query("SELECT COUNT(*) AS c FROM cache_entries WHERE key = 'k1'").get() as { c: number };
expect(countRow.c).toBe(2);
});
test("再次执行 runMigrations 保证幂等且不抛错", () => {
expect(() => runMigrations(db)).not.toThrow();
});
});
+3
View File
@@ -0,0 +1,3 @@
export * from "./types.js";
export * from "./connection.js";
export * from "./migrations.js";
+211
View File
@@ -0,0 +1,211 @@
import type { Database } from "bun:sqlite";
import type { DatabaseMigration } from "./types.js";
function hasColumn(db: Database, tableName: string, columnName: string): boolean {
try {
const rows = db.query(`PRAGMA table_info(${tableName})`).all() as Array<{ name: string }>;
return rows.some((r) => r.name === columnName);
} catch {
return false;
}
}
export const migrations: DatabaseMigration[] = [
{
version: 1,
name: "001_core_schema_and_approval_tables",
up(db: Database): void {
// 1. 规约主表
db.run(`
CREATE TABLE IF NOT EXISTS rules (
id TEXT PRIMARY KEY,
code INTEGER NOT NULL UNIQUE,
scope TEXT NOT NULL,
body TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'active',
version INTEGER NOT NULL DEFAULT 1,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
`);
db.run("CREATE INDEX IF NOT EXISTS idx_rules_scope ON rules(scope);");
db.run("CREATE INDEX IF NOT EXISTS idx_rules_status ON rules(status);");
// 2. 风格偏好表
db.run(`
CREATE TABLE IF NOT EXISTS preferences (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
is_default INTEGER NOT NULL DEFAULT 0,
rules_reject TEXT NOT NULL,
rules_review TEXT NOT NULL,
rules_pass_note TEXT NOT NULL,
rules_approve TEXT NOT NULL,
updated_at INTEGER NOT NULL
);
`);
// 3. 审批运行执行记录表
db.run(`
CREATE TABLE IF NOT EXISTS approval_runs (
id TEXT PRIMARY KEY,
short_id TEXT,
expires_at INTEGER,
flow_id TEXT,
document_sn TEXT NOT NULL,
corp_id TEXT,
scope TEXT,
decision TEXT NOT NULL,
decision_summary TEXT,
matched_rules_count INTEGER NOT NULL DEFAULT 0,
failed_rules_count INTEGER NOT NULL DEFAULT 0,
document_snapshot TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
`);
// 增量兼容老库缺省列
if (!hasColumn(db, "approval_runs", "scope")) {
try { db.run("ALTER TABLE approval_runs ADD COLUMN scope TEXT;"); } catch {}
}
if (!hasColumn(db, "approval_runs", "short_id")) {
try { db.run("ALTER TABLE approval_runs ADD COLUMN short_id TEXT;"); } catch {}
}
if (!hasColumn(db, "approval_runs", "expires_at")) {
try { db.run("ALTER TABLE approval_runs ADD COLUMN expires_at INTEGER;"); } catch {}
}
db.run("CREATE INDEX IF NOT EXISTS idx_runs_document_sn ON approval_runs(document_sn);");
db.run("CREATE INDEX IF NOT EXISTS idx_runs_short_id ON approval_runs(short_id);");
// MAJ-06: 支持 UPPER(short_id) 大小写不敏感快速定位
db.run("CREATE INDEX IF NOT EXISTS idx_runs_short_id_upper ON approval_runs(UPPER(short_id));");
db.run("CREATE INDEX IF NOT EXISTS idx_runs_created_at ON approval_runs(created_at);");
db.run("CREATE INDEX IF NOT EXISTS idx_runs_corp_id ON approval_runs(corp_id);");
db.run("CREATE INDEX IF NOT EXISTS idx_runs_flow_id ON approval_runs(flow_id);");
db.run("CREATE INDEX IF NOT EXISTS idx_runs_expires_at ON approval_runs(expires_at);");
// 4. 审批要点事实记录表
db.run(`
CREATE TABLE IF NOT EXISTS approval_findings (
id TEXT PRIMARY KEY,
run_id TEXT NOT NULL REFERENCES approval_runs(id) ON DELETE CASCADE,
rule_id TEXT REFERENCES rules(id) ON DELETE SET NULL,
clause_text TEXT NOT NULL,
strictness TEXT NOT NULL,
check_status TEXT NOT NULL,
evidence TEXT,
reasoning TEXT,
created_at INTEGER NOT NULL
);
`);
db.run("CREATE INDEX IF NOT EXISTS idx_findings_run_id ON approval_findings(run_id);");
// MAJ-07: 补充外键索引,防止外键删除全表扫描
db.run("CREATE INDEX IF NOT EXISTS idx_findings_rule_id ON approval_findings(rule_id);");
// 5. 全流程操作与审计流水表
db.run(`
CREATE TABLE IF NOT EXISTS aipro_logs (
id TEXT PRIMARY KEY,
run_id TEXT,
action TEXT NOT NULL,
document_sn TEXT,
operator TEXT,
args TEXT,
status TEXT NOT NULL,
decision TEXT,
summary TEXT,
created_at INTEGER NOT NULL
);
`);
if (!hasColumn(db, "aipro_logs", "run_id")) {
try { db.run("ALTER TABLE aipro_logs ADD COLUMN run_id TEXT;"); } catch {}
}
db.run("CREATE INDEX IF NOT EXISTS idx_aipro_logs_document_sn ON aipro_logs(document_sn);");
db.run("CREATE INDEX IF NOT EXISTS idx_aipro_logs_run_id ON aipro_logs(run_id);");
db.run("CREATE INDEX IF NOT EXISTS idx_aipro_logs_created_at ON aipro_logs(created_at);");
// 6. 多级缓存持久化表 (L2 Persistent Cache)
// CRIT-02: 采用复合主键 (namespace, key),彻底杜绝跨命名空间键碰撞
db.run(`
CREATE TABLE IF NOT EXISTS cache_entries (
namespace TEXT NOT NULL,
key TEXT NOT NULL,
value TEXT NOT NULL,
expires_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
PRIMARY KEY (namespace, key)
);
`);
db.run("CREATE INDEX IF NOT EXISTS idx_cache_namespace ON cache_entries(namespace);");
db.run("CREATE INDEX IF NOT EXISTS idx_cache_expires_at ON cache_entries(expires_at);");
// 种子数据:初始化默认偏好(CRIT-05: 使用 INSERT OR IGNORE 保证多进程启动绝对幂等)
seedDefaultPreference(db);
},
},
];
function seedDefaultPreference(db: Database): void {
const now = Date.now();
// CRIT-05: 使用 INSERT OR IGNORE 消除多进程并发启动 UNIQUE 冲突
db.run(
`
INSERT OR IGNORE INTO preferences (
id, name, is_default, rules_reject, rules_review, rules_pass_note, rules_approve, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
`,
[
"default",
"标准财务审批偏好",
1,
"确认触犯任何 @{硬性} 条款(刚性底线,直接阻断)",
"触发任何 @{特殊} 条款;未满足 @{弹性} 条款且单据金额 > 500 元;未满足 @{弹性} 累计达 3 处以上;单据未命中任何已有规则",
"未满足 @{弹性} 条款但单据金额 <= 500 元(企业尺度豁免放行);未满足 @{建议} 条款(倡导性要求,附温馨提示)",
"所有条款全部满足,秒级免审全自动通过",
now,
]
);
}
/**
* 执行迁移:自动检测并按序原子执行未应用的 migration (CRIT-04)
*/
export function runMigrations(db: Database): void {
// 创建迁移历史版本表
db.run(`
CREATE TABLE IF NOT EXISTS _schema_migrations (
version INTEGER PRIMARY KEY,
name TEXT NOT NULL,
applied_at INTEGER NOT NULL
);
`);
const appliedRows = db
.query("SELECT version FROM _schema_migrations ORDER BY version ASC")
.all() as Array<{ version: number }>;
const appliedVersions = new Set(appliedRows.map((r) => r.version));
// 按版本号升序排列依次执行
const sortedMigrations = [...migrations].sort((a, b) => a.version - b.version);
for (const migration of sortedMigrations) {
if (!appliedVersions.has(migration.version)) {
// CRIT-04: 使用 BEGIN IMMEDIATE 事务原子包裹
db.run("BEGIN IMMEDIATE;");
try {
migration.up(db);
db.run(
"INSERT INTO _schema_migrations (version, name, applied_at) VALUES (?, ?, ?)",
[migration.version, migration.name, Date.now()]
);
db.run("COMMIT;");
} catch (err) {
try {
db.run("ROLLBACK;");
} catch {}
throw err;
}
}
}
}
+12
View File
@@ -0,0 +1,12 @@
import type { Database } from "bun:sqlite";
export interface DatabaseMigration {
version: number;
name: string;
up: (db: Database) => void;
}
export interface DatabaseConnectionOptions {
customPath?: string;
readOnly?: boolean;
}
+6 -1
View File
@@ -9,6 +9,8 @@ export interface CreateAuthClientOptions {
prefixUrl: string;
getHeaders: () => Promise<Record<string, string>> | Record<string, string>;
onUnauthorized?: () => Promise<void> | void;
onAuthFailure?: (response: Response) => Error;
retryUnauthorized?: boolean;
}
export function createClient(options: CreateClientOptions): KyInstance {
@@ -22,7 +24,7 @@ export function createAuthClient(options: CreateAuthClientOptions): KyInstance {
return ky.create({
prefix: options.prefixUrl,
retry: {
limit: 1,
limit: options.retryUnauthorized === false ? 0 : 1,
methods: ["get", "post", "put", "delete", "patch"],
statusCodes: [401],
},
@@ -59,6 +61,9 @@ export function createAuthClient(options: CreateAuthClientOptions): KyInstance {
}
return ky(request);
}
if (isAuthError && options.onAuthFailure) {
throw options.onAuthFailure(response);
}
return response;
},
],
+1
View File
@@ -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) |
## 分层规则
+16 -181
View File
@@ -1,200 +1,35 @@
import { Database } from "bun:sqlite";
import { chmodSync, existsSync, mkdirSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import type { Database } from "bun:sqlite";
import {
DEFAULT_DB_PATH,
closeDatabase,
getDatabase,
resolveDatabasePath,
runMigrations,
} from "../../core/db/index.js";
export const DEFAULT_APPROVAL_DB_PATH = join(
homedir(),
".config",
"hose-use",
"approval.db"
);
export const DEFAULT_APPROVAL_DB_PATH = DEFAULT_DB_PATH;
export function resolveApprovalDbPath(): string {
const envPath = process.env.HOSE_APPROVAL_DB?.trim();
if (envPath) {
return envPath;
}
return DEFAULT_APPROVAL_DB_PATH;
return resolveDatabasePath();
}
let activeDb: Database | null = null;
let currentDbPath: string | null = null;
/**
* 获取或创建 SQLite 数据库连接单例
* 获取或创建 SQLite 数据库连接单例(兼容原接口,底层使用 core/db)
*/
export function getApprovalDatabase(customPath?: string): Database {
const targetPath = customPath ?? resolveApprovalDbPath();
if (activeDb && currentDbPath === targetPath) {
return activeDb;
}
// 内存数据库无需创建目录
if (targetPath !== ":memory:") {
const dir = dirname(targetPath);
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true, mode: 0o700 });
}
}
const db = new Database(targetPath);
if (targetPath !== ":memory:") {
// 规则、单据快照、审核证据和审计日志都可能包含敏感信息。
// SQLite 默认文件权限受 umask 影响,不能依赖默认值保护凭证与业务数据。
chmodSync(targetPath, 0o600);
}
currentDbPath = targetPath;
activeDb = db;
initDatabaseSchema(db);
return db;
return getDatabase(customPath);
}
/**
* 关闭并清理当前数据库连接(用于测试重置或进程退出)
* 关闭并清理当前数据库连接
*/
export function closeApprovalDatabase(): void {
if (activeDb) {
activeDb.close();
activeDb = null;
currentDbPath = null;
}
closeDatabase();
}
/**
* 初始化表结构与默认数据
* 初始化表结构与默认数据(兼容原接口,委托给 runMigrations)
*/
export function initDatabaseSchema(db: Database): void {
// 启用 WAL 模式提高并发性能与数据安全性
db.run("PRAGMA journal_mode = WAL;");
db.run("PRAGMA foreign_keys = ON;");
// 1. 规约主表
db.run(`
CREATE TABLE IF NOT EXISTS rules (
id TEXT PRIMARY KEY,
code INTEGER NOT NULL UNIQUE,
scope TEXT NOT NULL,
body TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'active',
version INTEGER NOT NULL DEFAULT 1,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
`);
db.run("CREATE INDEX IF NOT EXISTS idx_rules_scope ON rules(scope);");
db.run("CREATE INDEX IF NOT EXISTS idx_rules_status ON rules(status);");
// 2. 风格偏好表
db.run(`
CREATE TABLE IF NOT EXISTS preferences (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
is_default INTEGER NOT NULL DEFAULT 0,
rules_reject TEXT NOT NULL,
rules_review TEXT NOT NULL,
rules_pass_note TEXT NOT NULL,
rules_approve TEXT NOT NULL,
updated_at INTEGER NOT NULL
);
`);
// 3. 审批运行执行记录表
db.run(`
CREATE TABLE IF NOT EXISTS approval_runs (
id TEXT PRIMARY KEY,
short_id TEXT,
expires_at INTEGER,
flow_id TEXT,
document_sn TEXT NOT NULL,
corp_id TEXT,
scope TEXT,
decision TEXT NOT NULL,
decision_summary TEXT,
matched_rules_count INTEGER NOT NULL DEFAULT 0,
failed_rules_count INTEGER NOT NULL DEFAULT 0,
document_snapshot TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
`);
try {
db.run("ALTER TABLE approval_runs ADD COLUMN scope TEXT;");
} catch {}
try {
db.run("ALTER TABLE approval_runs ADD COLUMN short_id TEXT;");
} catch {}
try {
db.run("ALTER TABLE approval_runs ADD COLUMN expires_at INTEGER;");
} catch {}
db.run("CREATE INDEX IF NOT EXISTS idx_runs_document_sn ON approval_runs(document_sn);");
db.run("CREATE INDEX IF NOT EXISTS idx_runs_short_id ON approval_runs(short_id);");
db.run("CREATE INDEX IF NOT EXISTS idx_runs_created_at ON approval_runs(created_at);");
// 4. 审批要点事实记录表
db.run(`
CREATE TABLE IF NOT EXISTS approval_findings (
id TEXT PRIMARY KEY,
run_id TEXT NOT NULL REFERENCES approval_runs(id) ON DELETE CASCADE,
rule_id TEXT REFERENCES rules(id) ON DELETE SET NULL,
clause_text TEXT NOT NULL,
strictness TEXT NOT NULL,
check_status TEXT NOT NULL,
evidence TEXT,
reasoning TEXT,
created_at INTEGER NOT NULL
);
`);
db.run("CREATE INDEX IF NOT EXISTS idx_findings_run_id ON approval_findings(run_id);");
// 5. AI PRO 全流程操作与审计监控流水表
db.run(`
CREATE TABLE IF NOT EXISTS aipro_logs (
id TEXT PRIMARY KEY,
run_id TEXT,
action TEXT NOT NULL,
document_sn TEXT,
operator TEXT,
args TEXT,
status TEXT NOT NULL,
decision TEXT,
summary TEXT,
created_at INTEGER NOT NULL
);
`);
try {
db.run("ALTER TABLE aipro_logs ADD COLUMN run_id TEXT;");
} catch {}
db.run("CREATE INDEX IF NOT EXISTS idx_aipro_logs_document_sn ON aipro_logs(document_sn);");
db.run("CREATE INDEX IF NOT EXISTS idx_aipro_logs_run_id ON aipro_logs(run_id);");
db.run("CREATE INDEX IF NOT EXISTS idx_aipro_logs_created_at ON aipro_logs(created_at);");
// 种子数据:初始化默认偏好
seedDefaultPreference(db);
}
function seedDefaultPreference(db: Database): void {
const existing = db.query("SELECT id FROM preferences WHERE id = 'default'").get();
if (!existing) {
const now = Date.now();
db.run(
`
INSERT INTO preferences (
id, name, is_default, rules_reject, rules_review, rules_pass_note, rules_approve, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
`,
[
"default",
"标准财务审批偏好",
1,
"确认触犯任何 @{硬性} 条款(刚性底线,直接阻断)",
"触发任何 @{特殊} 条款;未满足 @{弹性} 条款且单据金额 > 500 元;未满足 @{弹性} 累计达 3 处以上;单据未命中任何已有规则",
"未满足 @{弹性} 条款但单据金额 <= 500 元(企业尺度豁免放行);未满足 @{建议} 条款(倡导性要求,附温馨提示)",
"所有条款全部满足,秒级免审全自动通过",
now
]
);
}
runMigrations(db);
}
+33
View File
@@ -210,6 +210,39 @@ describe("Bill Domain", () => {
expect(result?.history[1]?.skipped).toBe(true);
});
it("translates flow actions, states, Ebot operators and print reminders", async () => {
const client = {
post: async (path: string) => {
if (path.includes("backlogs/search")) {
return new Response(JSON.stringify({ items: [{ id: "backlog-i18n", flowId: { id: "flow-i18n", form: { code: "B26000001" } } }] }));
}
return new Response(JSON.stringify({ value: {
id: "backlog-i18n",
state: "APPROVING",
flowId: {
id: "flow-i18n",
state: "APPROVING",
form: { code: "B26000001" },
logs: [
{ action: "freeflow.submit", state: "SUBMITTED", operatorId: "staff-1", attributes: { nodeName: "提交" } },
{ action: "freeflow.autoAgree", state: "APPROVED", operatorId: "ebot", attributes: { isEbotNode: true } },
{ action: "freeflow.print", state: "COMPLETED", attributes: { isAuto: true } },
],
plan: { nodes: [{ id: "node-next", name: "财务审批", type: "APPROVAL" }] },
},
} }));
},
} as any;
const result = await getBillFlow(client, "corp-i18n", "B26000001");
expect(result?.state).toBe("审批中");
expect(result?.history.map((entry) => entry.action)).toEqual(["提交送审", "自动同意", "打印单据"]);
expect(result?.history[1]?.operator?.name).toBe("Ebot (智能审批)");
expect(result?.history[2]?.nodeName).toBe("打印提醒");
expect(result?.history[0]?.rawAction).toBe("freeflow.submit");
expect(result?.history[0]?.rawState).toBe("SUBMITTED");
});
it("builds the captured approve, reject, transfer, add-node and comment payloads", async () => {
const calls: Array<{ path: string; options: any }> = [];
const client = {
+67 -37
View File
@@ -3,6 +3,7 @@ import { KyInstance } from "ky";
import { existsSync } from "node:fs";
import { mkdir, writeFile } from "node:fs/promises";
import { basename, extname, join, resolve } from "node:path";
import { getGlobalCache } from "../../core/cache/index.js";
import {
searchRawBills,
getRawBillsByIds,
@@ -23,7 +24,12 @@ import {
type BillActionOptions,
type BillActionTarget,
} from "./api.js";
import type { TranslatorOptions } from "./translator.js";
import {
formatBillFlowOperator,
translateBillFlowAction,
translateBillFlowState,
type TranslatorOptions,
} from "./translator.js";
import {
type RawBillItem,
type FormattedBill,
@@ -93,9 +99,8 @@ const COMMON_FIELD_LABELS: Record<string, string> = {
ownerAndApproverPrintNodeFlag: "节点打印控制标识",
};
// ── 字段元数据内存缓存 ─────────────────────────────────────────────────────────
// ── 字段元数据与关联目录多级缓存 ─────────────────────────────────────────────
const schemaCache = new Map<string, { timestamp: number; dictionary: Map<string, { label: string; type: string }>; entities: EntityMeta[] }>();
const CACHE_TTL_MS = 10 * 60 * 1000; // 10 分钟缓存
type ReferenceCatalog = {
@@ -105,22 +110,20 @@ type ReferenceCatalog = {
feeTypes: Map<string, Record<string, unknown>>;
};
const referenceCatalogCache = new Map<string, ReferenceCatalog>();
export async function getFieldDictionary(
client: KyInstance,
corpId: string,
forceRefresh = false
): Promise<{ dictionary: Map<string, { label: string; type: string }>; entities: EntityMeta[] }> {
const cached = schemaCache.get(corpId);
if (!forceRefresh && cached && Date.now() - cached.timestamp < CACHE_TTL_MS) {
return cached;
}
const cache = getGlobalCache();
const rawEntities = await cache.withCache(
`bill:entities:${corpId}`,
() => listEntitySchemas(client, corpId, { start: 0, count: 100 }),
{ namespace: "bills", ttlMs: CACHE_TTL_MS, forceRefresh }
);
const entities = await listEntitySchemas(client, corpId, { start: 0, count: 100 });
const dictionary = new Map<string, { label: string; type: string }>();
for (const entity of entities) {
for (const entity of rawEntities) {
for (const field of entity.fields) {
if (field.name && field.label) {
dictionary.set(field.name, { label: field.label, type: field.type });
@@ -128,9 +131,7 @@ export async function getFieldDictionary(
}
}
const result = { timestamp: Date.now(), dictionary, entities };
schemaCache.set(corpId, result);
return result;
return { dictionary, entities: rawEntities };
}
function referenceId(value: unknown): string | undefined {
@@ -141,10 +142,14 @@ function referenceId(value: unknown): string | undefined {
}
function referenceObject(value: unknown): Record<string, unknown> | undefined {
return value && typeof value === "object" ? value as Record<string, unknown> : undefined;
return value && typeof value === "object" ? (value as Record<string, unknown>) : undefined;
}
function flattenDepartments(items: Record<string, unknown>[], parentPath = "", output = new Map<string, { item: Record<string, unknown>; path: string }>()): Map<string, { item: Record<string, unknown>; path: string }> {
function flattenDepartments(
items: Record<string, unknown>[],
parentPath = "",
output = new Map<string, { item: Record<string, unknown>; path: string }>()
): Map<string, { item: Record<string, unknown>; path: string }> {
for (const item of items) {
const name = typeof item.name === "string" ? item.name : "";
const path = name ? (parentPath ? `${parentPath}/${name}` : name) : parentPath;
@@ -158,7 +163,10 @@ function flattenDepartments(items: Record<string, unknown>[], parentPath = "", o
return output;
}
function flattenFeeTypes(items: Record<string, unknown>[], output = new Map<string, Record<string, unknown>>()): Map<string, Record<string, unknown>> {
function flattenFeeTypes(
items: Record<string, unknown>[],
output = new Map<string, Record<string, unknown>>()
): Map<string, Record<string, unknown>> {
for (const item of items) {
const feeType = referenceObject(item.feeType) ?? item;
const id = typeof feeType.id === "string" ? feeType.id : undefined;
@@ -172,29 +180,35 @@ function flattenFeeTypes(items: Record<string, unknown>[], output = new Map<stri
}
async function getReferenceCatalog(client: KyInstance, corpId: string): Promise<ReferenceCatalog> {
const cached = referenceCatalogCache.get(corpId);
if (cached && Date.now() - cached.timestamp < CACHE_TTL_MS) return cached;
const [staffs, departments, feeTypes] = await Promise.all([
listActiveStaffCatalog(client, corpId),
getDepartmentTree(client, corpId),
getFeeTypeTree(client, corpId),
]);
const cache = getGlobalCache();
const raw = await cache.withCache(
`bill:ref_raw:${corpId}`,
async () => {
const [staffs, departments, feeTypes] = await Promise.all([
listActiveStaffCatalog(client, corpId),
getDepartmentTree(client, corpId),
getFeeTypeTree(client, corpId),
]);
return { staffs, departments, feeTypes };
},
{ namespace: "bills", ttlMs: CACHE_TTL_MS }
);
const staff = new Map<string, Record<string, unknown>>();
for (const item of staffs) {
for (const item of raw.staffs) {
if (typeof item.id === "string") {
staff.set(item.id, item);
const userId = typeof item.userId === "string" ? item.userId : undefined;
if (userId) staff.set(userId, item);
}
}
const result = {
return {
timestamp: Date.now(),
staff,
departments: flattenDepartments(departments),
feeTypes: flattenFeeTypes(feeTypes),
departments: flattenDepartments(raw.departments),
feeTypes: flattenFeeTypes(raw.feeTypes),
};
referenceCatalogCache.set(corpId, result);
return result;
}
function toReference(
@@ -875,17 +889,30 @@ export async function getBillFlow(
const nextOperators = Array.isArray(log.nextOperatorIds)
? log.nextOperatorIds.map(flowPerson).filter((person): person is NonNullable<typeof person> => Boolean(person))
: [];
const operator = flowPerson(log.operatorId);
const isEbot = attributes.isEbotNode === true || `${operator?.id || ""} ${operator?.name || ""}`.toLowerCase().includes("ebot");
const labeledOperator = isEbot
? { ...(operator || { id: "ebot" }), name: "Ebot (智能审批)" }
: operator;
const rawAction = typeof log.action === "string" ? log.action : undefined;
const rawState = typeof log.state === "string" ? log.state : undefined;
return {
id: typeof log.id === "string" ? log.id : undefined,
time: currentTime,
durationMs,
state: typeof log.state === "string" ? log.state : undefined,
action: typeof log.action === "string" ? log.action : undefined,
nodeName: typeof attributes.nodeName === "string" ? attributes.nodeName : typeof attributes.nextName === "string" ? attributes.nextName : undefined,
state: translateBillFlowState(rawState),
rawState,
action: translateBillFlowAction(rawAction),
rawAction,
nodeName: typeof attributes.nodeName === "string" && attributes.nodeName
? attributes.nodeName
: typeof attributes.nextName === "string" && attributes.nextName
? attributes.nextName
: translateBillFlowAction(rawAction) === "打印单据" ? "打印提醒" : undefined,
comment: typeof attributes.comment === "string" && attributes.comment ? attributes.comment : undefined,
automatic: attributes.isEbotNode === true || attributes.isAuto === true || !log.operatorId,
skipped: attributes.isSkip === true || attributes.skipped === true || log.state === "SKIPPED",
operator: flowPerson(log.operatorId),
operator: labeledOperator,
nextOperators,
};
});
@@ -903,7 +930,7 @@ export async function getBillFlow(
id: typeof node.id === "string" ? node.id : undefined,
name: typeof node.name === "string" ? node.name : undefined,
type: typeof node.type === "string" ? node.type : undefined,
state: typeof node.id === "string" && node.id === nextNodeId || typeof node.name === "string" && node.name === currentNode ? "current" : "planned",
state: typeof node.id === "string" && node.id === nextNodeId || typeof node.name === "string" && node.name === currentNode ? "当前" : "后续",
approver,
approvers,
};
@@ -916,7 +943,7 @@ export async function getBillFlow(
flowId: typeof flow.id === "string" ? flow.id : undefined,
billCode: typeof form.code === "string" ? form.code : undefined,
title: typeof form.title === "string" ? form.title : undefined,
state: typeof raw.state === "string" ? raw.state : typeof flow.state === "string" ? flow.state : undefined,
state: translateBillFlowState(typeof raw.state === "string" ? raw.state : typeof flow.state === "string" ? flow.state : undefined),
currentNode: currentNode ?? (typeof lastAttributes.nextName === "string" ? lastAttributes.nextName : undefined),
history,
pending,
@@ -1425,6 +1452,9 @@ export async function getTranslatorContext(
export {
translateBillFlowToMarkdown,
formatBillFlowOperator,
translateBillFlowAction,
translateBillFlowState,
formatAmountValue,
formatDateValue,
formatPersonValue,
+46
View File
@@ -130,6 +130,52 @@ export interface TranslatorOptions {
datalinkCardMap?: Map<string, string>;
}
const BILL_FLOW_ACTION_LABELS: Record<string, string> = {
"freeflow.submit": "提交送审",
"freeflow.agree": "审批同意",
"freeflow.autoAgree": "自动同意",
"freeflow.reject": "审批驳回",
"freeflow.print": "打印单据",
"freeflow.retract": "单据撤回",
"freeflow.addnode": "加签/转交",
"freeflow.comment": "发表评论",
};
const BILL_FLOW_STATE_LABELS: Record<string, string> = {
APPROVING: "审批中",
APPROVED: "审批通过",
REJECTED: "审批驳回",
REVOKED: "已撤回",
CANCELED: "已取消",
CANCELLED: "已取消",
SKIPPED: "已跳过",
SUBMITTED: "已提交",
PENDING: "待审批",
WAITING: "待处理",
COMPLETED: "已完成",
DRAFT: "草稿",
};
export function translateBillFlowAction(action?: string): string | undefined {
if (!action) return undefined;
return BILL_FLOW_ACTION_LABELS[action] || action;
}
export function translateBillFlowState(state?: string): string | undefined {
if (!state) return undefined;
return BILL_FLOW_STATE_LABELS[state.toUpperCase()] || state;
}
export function formatBillFlowOperator(
operator?: { id?: string; name?: string },
automatic = false,
isEbot = false
): string {
const raw = `${operator?.id || ""} ${operator?.name || ""}`.toLowerCase();
if (isEbot || raw.includes("ebot")) return "Ebot (智能审批)";
return operator?.name || (automatic ? "系统" : "-");
}
// ── 5. 部门全路径格式化 ───────────────────────────────────────────────────────
export function formatDepartmentValue(
+2
View File
@@ -109,7 +109,9 @@ export interface BillFlowEntry {
time?: number;
durationMs?: number;
state?: string;
rawState?: string;
action?: string;
rawAction?: string;
nodeName?: string;
comment?: string;
automatic?: boolean;
+40 -20
View File
@@ -1,37 +1,53 @@
import { z } from "zod";
import type { KyInstance } from "ky";
import { getGlobalCache } from "../../core/cache/index.js";
import { listDimensionCatalogs, listDimensionItems } from "./api.js";
import type { DimensionCatalog, DimensionItem, DimensionQuery } from "./types.js";
const cache = new Map<string, { timestamp: number; catalogs: DimensionCatalog[]; items: Map<string, DimensionItem[]> }>();
const CACHE_TTL_MS = 10 * 60 * 1000;
async function getCached(client: KyInstance, corpId: string): Promise<{ catalogs: DimensionCatalog[]; items: Map<string, DimensionItem[]> }> {
const existing = cache.get(corpId);
if (existing && Date.now() - existing.timestamp < CACHE_TTL_MS) return existing;
const catalogs = await listDimensionCatalogs(client, corpId);
const result = { timestamp: Date.now(), catalogs, items: new Map<string, DimensionItem[]>() };
cache.set(corpId, result);
return result;
async function getCachedCatalogs(client: KyInstance, corpId: string): Promise<DimensionCatalog[]> {
const cache = getGlobalCache();
return cache.withCache(
`dimensions:catalogs:${corpId}`,
() => listDimensionCatalogs(client, corpId),
{ namespace: "dimensions", ttlMs: CACHE_TTL_MS }
);
}
export async function searchDimensions(client: KyInstance, corpId: string, query: DimensionQuery = {}): Promise<DimensionCatalog[]> {
const { catalogs } = await getCached(client, corpId);
export async function searchDimensions(
client: KyInstance,
corpId: string,
query: DimensionQuery = {}
): Promise<DimensionCatalog[]> {
const catalogs = await getCachedCatalogs(client, corpId);
const keyword = (query.name || query.code || query.id || "").trim().toLowerCase();
if (!keyword) return catalogs;
return catalogs.filter((item) => [item.id, item.name, item.code].some((value) => value.toLowerCase().includes(keyword)));
return catalogs.filter((item) =>
[item.id, item.name, item.code].some((value) => value.toLowerCase().includes(keyword))
);
}
export async function getDimensionItems(client: KyInstance, corpId: string, dimension: DimensionCatalog, start = 0, count = 100): Promise<DimensionItem[]> {
const catalog = await getCached(client, corpId);
const cached = catalog.items.get(dimension.id);
if (cached && start === 0 && count >= cached.length) return cached;
const items = await listDimensionItems(client, corpId, dimension.id, start, count);
if (start === 0) catalog.items.set(dimension.id, items);
return items;
export async function getDimensionItems(
client: KyInstance,
corpId: string,
dimension: DimensionCatalog,
start = 0,
count = 100
): Promise<DimensionItem[]> {
const cache = getGlobalCache();
return cache.withCache(
`dimensions:items:${corpId}:${dimension.id}:${start}:${count}`,
() => listDimensionItems(client, corpId, dimension.id, start, count),
{ namespace: "dimensions", ttlMs: CACHE_TTL_MS }
);
}
export async function resolveDimension(client: KyInstance, corpId: string, target: string): Promise<{ dimension: DimensionCatalog; items: DimensionItem[] } | undefined> {
export async function resolveDimension(
client: KyInstance,
corpId: string,
target: string
): Promise<{ dimension: DimensionCatalog; items: DimensionItem[] } | undefined> {
const matches = await searchDimensions(client, corpId, { id: target, code: target, name: target });
const dimension = matches[0];
if (!dimension) return undefined;
@@ -46,7 +62,11 @@ export const dimensionTools = [
handler: async ({ corpContext }: any, params: { keyword?: string; count?: number }) => {
const corp = corpContext.getCurrent();
if (!corp) throw new Error("未配置活跃企业上下文");
const items = await searchDimensions(await import("../../core/auth/ekb.js").then((m) => m.createEkbClient(corp)), corp.corpId || corp.id, { name: params.keyword });
const items = await searchDimensions(
await import("../../core/auth/ekb.js").then((m) => m.createEkbClient(corp)),
corp.corpId || corp.id,
{ name: params.keyword }
);
return { count: items.length, dimensions: items.slice(0, params.count ?? 100) };
},
},
+63 -22
View File
@@ -1,40 +1,81 @@
import { z } from "zod";
import type { KyInstance } from "ky";
import { getGlobalCache } from "../../core/cache/index.js";
import { listRoleGroups, listRoleMembers, listRoles } from "./api.js";
import type { Role, RoleGroup, RoleMemberReport, RoleQuery } from "./types.js";
const cache = new Map<string, { timestamp: number; roles: Role[]; groups: RoleGroup[] }>();
const CACHE_TTL_MS = 10 * 60 * 1000;
async function getCatalog(client: KyInstance, corpId: string): Promise<{ roles: Role[]; groups: RoleGroup[] }> {
const existing = cache.get(corpId);
if (existing && Date.now() - existing.timestamp < CACHE_TTL_MS) return existing;
const [roles, groups] = await Promise.all([listRoles(client, corpId), listRoleGroups(client, corpId)]);
const result = { timestamp: Date.now(), roles, groups }; cache.set(corpId, result); return result;
async function getCatalog(
client: KyInstance,
corpId: string
): Promise<{ roles: Role[]; groups: RoleGroup[] }> {
const cache = getGlobalCache();
return cache.withCache(
`roles:catalog:${corpId}`,
async () => {
const [roles, groups] = await Promise.all([
listRoles(client, corpId),
listRoleGroups(client, corpId),
]);
return { roles, groups };
},
{ namespace: "roles", ttlMs: CACHE_TTL_MS }
);
}
export async function searchRoles(client: KyInstance, corpId: string, query: RoleQuery = {}): Promise<Role[]> {
export async function searchRoles(
client: KyInstance,
corpId: string,
query: RoleQuery = {}
): Promise<Role[]> {
const { roles } = await getCatalog(client, corpId);
const keyword = (query.keyword || query.id || query.code || query.name || "").trim().toLowerCase();
if (!keyword) return roles;
return roles.filter((role) => [role.id, role.name, role.code, role.purposeName, role.scope.name].some((value) => value.toLowerCase().includes(keyword)));
return roles.filter((role) =>
[role.id, role.name, role.code, role.purposeName, role.scope.name].some((value) =>
value.toLowerCase().includes(keyword)
)
);
}
export async function getRoleGroups(client: KyInstance, corpId: string): Promise<RoleGroup[]> { return (await getCatalog(client, corpId)).groups; }
export async function resolveRole(client: KyInstance, corpId: string, target: string): Promise<Role | undefined> {
export async function getRoleGroups(client: KyInstance, corpId: string): Promise<RoleGroup[]> {
return (await getCatalog(client, corpId)).groups;
}
export async function resolveRole(
client: KyInstance,
corpId: string,
target: string
): Promise<Role | undefined> {
const matches = await searchRoles(client, corpId, { keyword: target });
return matches.find((role) => role.id === target || role.code === target || role.name === target) || matches[0];
return (
matches.find((role) => role.id === target || role.code === target || role.name === target) ||
matches[0]
);
}
export async function getRoleMembers(client: KyInstance, corpId: string, target: string): Promise<RoleMemberReport | undefined> {
const role = await resolveRole(client, corpId, target); if (!role) return undefined;
export async function getRoleMembers(
client: KyInstance,
corpId: string,
target: string
): Promise<RoleMemberReport | undefined> {
const role = await resolveRole(client, corpId, target);
if (!role) return undefined;
return { role, members: await listRoleMembers(client, corpId, role.id) };
}
export const roleTools = [{
name: "role_list", description: "列出当前企业角色定义与角色组",
parameters: z.object({ keyword: z.string().optional(), count: z.number().optional() }),
handler: async ({ corpContext }: any, params: { keyword?: string; count?: number }) => {
const corp = corpContext.getCurrent(); if (!corp) throw new Error("未配置活跃企业上下文");
const client = await import("../../core/auth/ekb.js").then((m) => m.createEkbClient(corp));
const roles = await searchRoles(client, corp.corpId || corp.id, { keyword: params.keyword });
return { count: roles.length, roles: roles.slice(0, params.count ?? 100) };
export const roleTools = [
{
name: "role_list",
description: "列出当前企业角色定义与角色组",
parameters: z.object({ keyword: z.string().optional(), count: z.number().optional() }),
handler: async ({ corpContext }: any, params: { keyword?: string; count?: number }) => {
const corp = corpContext.getCurrent();
if (!corp) throw new Error("未配置活跃企业上下文");
const client = await import("../../core/auth/ekb.js").then((m) => m.createEkbClient(corp));
const roles = await searchRoles(client, corp.corpId || corp.id, { keyword: params.keyword });
return { count: roles.length, roles: roles.slice(0, params.count ?? 100) };
},
},
}];
];
+17
View File
@@ -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`: 获取指定应用的详细信息、套餐与规格
+145
View File
@@ -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");
});
});
+98
View File
@@ -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<OpenApiKey[]> {
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<OpenConfig> {
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<ClientGoods[]> {
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<GoodsDetail> {
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 ?? {});
}
+74
View File
@@ -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<OpenApiKey[]> {
const ekbClient = await createEkbClient(corp);
const corpId = corp.corpId || corp.credentials.corpId;
return listOpenApiKeys(ekbClient, corpId);
}
export async function fetchOpenConfig(corp: CorpConfig): Promise<OpenConfig> {
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<ClientGoods[]> {
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<GoodsDetail> {
const { client: unityClient } = await getUnityClient(corp);
const corpId = corp.corpId || corp.credentials.corpId;
return getGoodsDetail(unityClient, corpId, goodsId);
}
+112
View File
@@ -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<typeof OpenApiKeySchema>;
// ── 免登重定向配置模型 ───────────────────────────────────────────────────────
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<typeof OpenConfigSchema>;
// ── 商店与应用模型 ───────────────────────────────────────────────────────────
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<typeof GoodsPowerSchema>;
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<typeof ClientGoodsSchema>;
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<typeof StoreGoodsItemSchema>;
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<typeof GoodsDetailSchema>;
+1 -1
View File
@@ -1 +1 @@
export const VERSION = "0.7.4";
export const VERSION = "0.8.1";