Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
07b4e14e59 | ||
|
|
ba30c1a6cb | ||
|
|
cf44c7dcdf |
No files matched your search
@@ -1,4 +1,4 @@
|
|||||||
# hose-use (v0.4.0)
|
# hose-use (v0.4.2)
|
||||||
|
|
||||||
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
|
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
|
||||||
|
|
||||||
@@ -32,8 +32,9 @@ hose-use corps list # 列出名下所有已配置企
|
|||||||
hose-use corps switch <corpId> # 切换工作企业
|
hose-use corps switch <corpId> # 切换工作企业
|
||||||
hose-use corps current # 查看当前激活企业
|
hose-use corps current # 查看当前激活企业
|
||||||
|
|
||||||
# 3. 运行模式管理 (有状态 vs 无状态)
|
# 3. 运行模式与多级配置路径管理 (有状态 vs 无状态)
|
||||||
hose-use config show # 查看当前运行模式
|
hose-use config show # 查看当前运行模式与默认企业
|
||||||
|
hose-use config paths # 查看多级企业目录发现链与配置文件位置
|
||||||
hose-use config mode stateless # 切换为无状态模式 (防止 Agent 误操作)
|
hose-use config mode stateless # 切换为无状态模式 (防止 Agent 误操作)
|
||||||
hose-use config mode stateful # 切换为有状态模式 (记忆默认企业)
|
hose-use config mode stateful # 切换为有状态模式 (记忆默认企业)
|
||||||
|
|
||||||
@@ -44,8 +45,10 @@ hose-use workflow find --task=code-js2 # 搜索包含特定节点类型
|
|||||||
hose-use workflow toggle <pipelineId> --state=1 # 启用/停用工作流
|
hose-use workflow toggle <pipelineId> --state=1 # 启用/停用工作流
|
||||||
hose-use platform list # 查看企业下所有启用的自建应用
|
hose-use platform list # 查看企业下所有启用的自建应用
|
||||||
|
|
||||||
# 5. 单据与费用明细管理 (DataLink 字典自动还原)
|
# 5. 单据与费用明细管理 (DataLink 字典自动还原 & 200KB 防爆拦截)
|
||||||
hose-use bill list # 查看当前企业单据与报销列表 (支持分页/阶段/状态过滤)
|
hose-use bill list # 查看当前企业单据与报销列表 (支持分页/阶段/状态过滤)
|
||||||
|
hose-use bill list --json -o /tmp/bills.json # 自动转储大报文至本地文件,防止打爆上下文
|
||||||
|
hose-use bill list --json --full # 确需完整原始数据时跳过 200KB 限制
|
||||||
hose-use bill get <单号|ID> # 根据单号或 ID 查询单据结构化详情
|
hose-use bill get <单号|ID> # 根据单号或 ID 查询单据结构化详情
|
||||||
hose-use bill schema # 查看企业全部单据实体与数据模型字典
|
hose-use bill schema # 查看企业全部单据实体与数据模型字典
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
openapi: 3.1.0
|
openapi: 3.1.0
|
||||||
info:
|
info:
|
||||||
title: hose-use API & MCP Tools Specification
|
title: hose-use API & MCP Tools Specification
|
||||||
version: 0.4.0
|
version: 0.4.2
|
||||||
description: >-
|
description: >-
|
||||||
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
|
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
|
||||||
servers:
|
servers:
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "hose-use",
|
"name": "hose-use",
|
||||||
"version": "0.4.0",
|
"version": "0.4.2",
|
||||||
"module": "src/server.ts",
|
"module": "src/server.ts",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"bin": {
|
"bin": {
|
||||||
|
|||||||
@@ -84,6 +84,9 @@ hose-use corps current
|
|||||||
# 查看全局运行模式与配置文件路径
|
# 查看全局运行模式与配置文件路径
|
||||||
hose-use config show
|
hose-use config show
|
||||||
|
|
||||||
|
# 查看多级企业目录发现路径与诊断
|
||||||
|
hose-use config paths
|
||||||
|
|
||||||
# 切换为无状态模式 (Stateless)
|
# 切换为无状态模式 (Stateless)
|
||||||
hose-use config mode stateless
|
hose-use config mode stateless
|
||||||
|
|
||||||
@@ -117,6 +120,11 @@ hose-use platform list
|
|||||||
hose-use bill list
|
hose-use bill list
|
||||||
hose-use bill list --stage=expense --state=paid --count=10
|
hose-use bill list --stage=expense --state=paid --count=10
|
||||||
|
|
||||||
|
# 大数据量防爆落盘: 使用 -o / --output-file 将完整 JSON 转储至本地文件 (推荐 Agent 处理海量数据时使用)
|
||||||
|
hose-use bill list --json -o /tmp/bills.json
|
||||||
|
# 确需向终端输出完整大报文时附加 --full (跳过 200KB 防爆限制)
|
||||||
|
hose-use bill list --json --full
|
||||||
|
|
||||||
# 根据单号或 ID 精确查询单据结构化详情 (DataLink 字典自动还原)
|
# 根据单号或 ID 精确查询单据结构化详情 (DataLink 字典自动还原)
|
||||||
hose-use bill get n0GMIM0dkQmKbS
|
hose-use bill get n0GMIM0dkQmKbS
|
||||||
hose-use bill get ID01TRzg7HMLcb
|
hose-use bill get ID01TRzg7HMLcb
|
||||||
|
|||||||
+28
-19
@@ -43,13 +43,16 @@ export async function handleBillCommand(
|
|||||||
|
|
||||||
if (runtime.jsonMode) {
|
if (runtime.jsonMode) {
|
||||||
return {
|
return {
|
||||||
stdout: printJson({
|
stdout: printJson(
|
||||||
corpId,
|
{
|
||||||
corpName: corp.name,
|
corpId,
|
||||||
total: result.total,
|
corpName: corp.name,
|
||||||
returned: result.returned,
|
total: result.total,
|
||||||
items: result.items,
|
returned: result.returned,
|
||||||
}),
|
items: result.items,
|
||||||
|
},
|
||||||
|
runtime.outputOptions
|
||||||
|
),
|
||||||
stderr: "",
|
stderr: "",
|
||||||
exitCode: 0,
|
exitCode: 0,
|
||||||
};
|
};
|
||||||
@@ -104,12 +107,15 @@ export async function handleBillCommand(
|
|||||||
|
|
||||||
if (runtime.jsonMode) {
|
if (runtime.jsonMode) {
|
||||||
return {
|
return {
|
||||||
stdout: printJson({
|
stdout: printJson(
|
||||||
corpId,
|
{
|
||||||
corpName: corp.name,
|
corpId,
|
||||||
count: bills.length,
|
corpName: corp.name,
|
||||||
bills,
|
count: bills.length,
|
||||||
}),
|
bills,
|
||||||
|
},
|
||||||
|
runtime.outputOptions
|
||||||
|
),
|
||||||
stderr: "",
|
stderr: "",
|
||||||
exitCode: 0,
|
exitCode: 0,
|
||||||
};
|
};
|
||||||
@@ -157,12 +163,15 @@ export async function handleBillCommand(
|
|||||||
|
|
||||||
if (runtime.jsonMode) {
|
if (runtime.jsonMode) {
|
||||||
return {
|
return {
|
||||||
stdout: printJson({
|
stdout: printJson(
|
||||||
corpId,
|
{
|
||||||
corpName: corp.name,
|
corpId,
|
||||||
totalEntities: entities.length,
|
corpName: corp.name,
|
||||||
entities,
|
totalEntities: entities.length,
|
||||||
}),
|
entities,
|
||||||
|
},
|
||||||
|
runtime.outputOptions
|
||||||
|
),
|
||||||
stderr: "",
|
stderr: "",
|
||||||
exitCode: 0,
|
exitCode: 0,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -2,6 +2,9 @@ import {
|
|||||||
loadGlobalConfig,
|
loadGlobalConfig,
|
||||||
saveGlobalConfig,
|
saveGlobalConfig,
|
||||||
resolveGlobalConfigFile,
|
resolveGlobalConfigFile,
|
||||||
|
resolveEnterprisesDirs,
|
||||||
|
resolveWritableEnterprisesDir,
|
||||||
|
getEnterprisesDirCandidates,
|
||||||
} from "../../core/config/loader.js";
|
} from "../../core/config/loader.js";
|
||||||
import { printJson, printKeyValue } from "../printer.js";
|
import { printJson, printKeyValue } from "../printer.js";
|
||||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||||
@@ -17,6 +20,10 @@ export async function handleConfigCommand(
|
|||||||
case "get":
|
case "get":
|
||||||
case "list":
|
case "list":
|
||||||
return handleShow(parsed, runtime);
|
return handleShow(parsed, runtime);
|
||||||
|
case "paths":
|
||||||
|
case "path":
|
||||||
|
case "dirs":
|
||||||
|
return handlePaths(parsed, runtime);
|
||||||
case "mode":
|
case "mode":
|
||||||
return handleMode(parsed, runtime);
|
return handleMode(parsed, runtime);
|
||||||
case "set":
|
case "set":
|
||||||
@@ -24,7 +31,7 @@ export async function handleConfigCommand(
|
|||||||
default:
|
default:
|
||||||
return {
|
return {
|
||||||
stdout: "",
|
stdout: "",
|
||||||
stderr: `未知 config 子命令: ${action}。支持: show, mode <stateful|stateless>, set <key> <val>\n`,
|
stderr: `未知 config 子命令: ${action}。支持: show, paths, mode <stateful|stateless>, set <key> <val>\n`,
|
||||||
exitCode: 1,
|
exitCode: 1,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -125,3 +132,43 @@ async function handleSet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<Cl
|
|||||||
exitCode: 0,
|
exitCode: 0,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function handlePaths(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||||
|
const envDir = process.env.HOSE_ENTERPRISES_DIR;
|
||||||
|
const envUserDir = process.env.HOSE_USER_ENTERPRISES_DIR;
|
||||||
|
const envConfigFile = process.env.HOSE_CONFIG_FILE;
|
||||||
|
const existingDirs = resolveEnterprisesDirs();
|
||||||
|
const writableDir = resolveWritableEnterprisesDir();
|
||||||
|
const configFile = resolveGlobalConfigFile();
|
||||||
|
const candidates = getEnterprisesDirCandidates();
|
||||||
|
|
||||||
|
const data = {
|
||||||
|
configFile,
|
||||||
|
writableDir,
|
||||||
|
existingDirs,
|
||||||
|
env: {
|
||||||
|
HOSE_ENTERPRISES_DIR: envDir || null,
|
||||||
|
HOSE_USER_ENTERPRISES_DIR: envUserDir || null,
|
||||||
|
HOSE_CONFIG_FILE: envConfigFile || null,
|
||||||
|
},
|
||||||
|
candidates,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (runtime.jsonMode) {
|
||||||
|
return { stdout: printJson(data), stderr: "", exitCode: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
const output = printKeyValue({
|
||||||
|
"当前生效配置文件": configFile,
|
||||||
|
"凭证保存写入目录": writableDir,
|
||||||
|
"已发现企业目录": existingDirs.length ? existingDirs.join("\n ") : "无 (未发现任何有效企业目录)",
|
||||||
|
"环境变量指定目录": envDir || "未设置 (HOSE_ENTERPRISES_DIR)",
|
||||||
|
"全部目录候选链": candidates.join("\n "),
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
stdout: `====== 配置路径诊断 (Config Paths) ======\n${output}\n`,
|
||||||
|
stderr: "",
|
||||||
|
exitCode: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -29,10 +29,13 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
|
|||||||
|
|
||||||
if (runtime.jsonMode) {
|
if (runtime.jsonMode) {
|
||||||
return {
|
return {
|
||||||
stdout: printJson({
|
stdout: printJson(
|
||||||
activeCorpId: runtime.selectedCorp?.id,
|
{
|
||||||
corporations: corps,
|
activeCorpId: runtime.selectedCorp?.id,
|
||||||
}),
|
corporations: corps,
|
||||||
|
},
|
||||||
|
runtime.outputOptions
|
||||||
|
),
|
||||||
stderr: "",
|
stderr: "",
|
||||||
exitCode: 0,
|
exitCode: 0,
|
||||||
};
|
};
|
||||||
@@ -81,7 +84,7 @@ async function handleSwitch(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
|||||||
|
|
||||||
const current = runtime.corpContext.getCurrent();
|
const current = runtime.corpContext.getCurrent();
|
||||||
if (runtime.jsonMode) {
|
if (runtime.jsonMode) {
|
||||||
return { stdout: printJson(current), stderr: "", exitCode: 0 };
|
return { stdout: printJson(current, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -98,7 +101,7 @@ async function handleCurrent(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (runtime.jsonMode) {
|
if (runtime.jsonMode) {
|
||||||
return { stdout: printJson(current), stderr: "", exitCode: 0 };
|
return { stdout: printJson(current, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
const pairs: Record<string, unknown> = {
|
const pairs: Record<string, unknown> = {
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
|
|||||||
const platforms = await api.listPlatforms(clients.ekbClient, runtime.selectedCorp!.credentials.corpId);
|
const platforms = await api.listPlatforms(clients.ekbClient, runtime.selectedCorp!.credentials.corpId);
|
||||||
|
|
||||||
if (runtime.jsonMode) {
|
if (runtime.jsonMode) {
|
||||||
return { stdout: printJson(platforms), stderr: "", exitCode: 0 };
|
return { stdout: printJson(platforms, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
if (platforms.length === 0) {
|
if (platforms.length === 0) {
|
||||||
|
|||||||
@@ -54,7 +54,7 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
|
|||||||
const result = await listAllWorkflows(clients, { page, pageSize });
|
const result = await listAllWorkflows(clients, { page, pageSize });
|
||||||
|
|
||||||
if (runtime.jsonMode) {
|
if (runtime.jsonMode) {
|
||||||
return { stdout: printJson(result), stderr: "", exitCode: 0 };
|
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
if (result.workflows.length === 0) {
|
if (result.workflows.length === 0) {
|
||||||
@@ -96,7 +96,7 @@ async function handleGet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<Cl
|
|||||||
const detail = await api.getWorkflowDetail(clients.easoClient, pipelineId);
|
const detail = await api.getWorkflowDetail(clients.easoClient, pipelineId);
|
||||||
|
|
||||||
if (runtime.jsonMode) {
|
if (runtime.jsonMode) {
|
||||||
return { stdout: printJson(detail), stderr: "", exitCode: 0 };
|
return { stdout: printJson(detail, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
const summary = printKeyValue({
|
const summary = printKeyValue({
|
||||||
@@ -148,7 +148,7 @@ async function handleFind(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (runtime.jsonMode) {
|
if (runtime.jsonMode) {
|
||||||
return { stdout: printJson(result), stderr: "", exitCode: 0 };
|
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
if (result.workflows.length === 0) {
|
if (result.workflows.length === 0) {
|
||||||
@@ -196,7 +196,7 @@ async function handleToggle(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
|||||||
const result = await api.toggleWorkflow(clients.easoClient, pipelineId, state);
|
const result = await api.toggleWorkflow(clients.easoClient, pipelineId, state);
|
||||||
|
|
||||||
if (runtime.jsonMode) {
|
if (runtime.jsonMode) {
|
||||||
return { stdout: printJson(result), stderr: "", exitCode: 0 };
|
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
+5
-3
@@ -1,10 +1,10 @@
|
|||||||
import readline from "readline";
|
import readline from "readline";
|
||||||
import { loadCorpConfigs, loadGlobalConfig } from "../core/config/loader.js";
|
import { loadCorpConfigs, loadGlobalConfig, getEnterprisesDirCandidates } from "../core/config/loader.js";
|
||||||
import { CorpContext, resolveCorpConfig } from "../core/config/manager.js";
|
import { CorpContext, resolveCorpConfig } from "../core/config/manager.js";
|
||||||
import { CorpConfig } from "../core/config/types.js";
|
import { CorpConfig } from "../core/config/types.js";
|
||||||
import { createEkbClient } from "../core/auth/ekb.js";
|
import { createEkbClient } from "../core/auth/ekb.js";
|
||||||
import { getEasoClient } from "../core/auth/easo.js";
|
import { getEasoClient } from "../core/auth/easo.js";
|
||||||
import { CliRuntime } from "./types.js";
|
import { CliRuntime, OutputOptions } from "./types.js";
|
||||||
|
|
||||||
export function initCorpRuntime(
|
export function initCorpRuntime(
|
||||||
options: {
|
options: {
|
||||||
@@ -12,6 +12,7 @@ export function initCorpRuntime(
|
|||||||
stateless?: boolean;
|
stateless?: boolean;
|
||||||
stateful?: boolean;
|
stateful?: boolean;
|
||||||
jsonMode?: boolean;
|
jsonMode?: boolean;
|
||||||
|
outputOptions?: OutputOptions;
|
||||||
} = {}
|
} = {}
|
||||||
): CliRuntime {
|
): CliRuntime {
|
||||||
const corps = loadCorpConfigs();
|
const corps = loadCorpConfigs();
|
||||||
@@ -31,7 +32,7 @@ export function initCorpRuntime(
|
|||||||
|
|
||||||
let selectedCorp: CorpConfig | null = null;
|
let selectedCorp: CorpConfig | null = null;
|
||||||
try {
|
try {
|
||||||
selectedCorp = corpContext.resolve(options.corpId);
|
selectedCorp = corpContext.resolve(options.corpId, getEnterprisesDirCandidates());
|
||||||
} catch {
|
} catch {
|
||||||
selectedCorp = null;
|
selectedCorp = null;
|
||||||
}
|
}
|
||||||
@@ -40,6 +41,7 @@ export function initCorpRuntime(
|
|||||||
corpContext,
|
corpContext,
|
||||||
selectedCorp,
|
selectedCorp,
|
||||||
jsonMode: options.jsonMode ?? false,
|
jsonMode: options.jsonMode ?? false,
|
||||||
|
outputOptions: options.outputOptions,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+24
-2
@@ -1,4 +1,4 @@
|
|||||||
import type { CliParsedArgs } from "./types.js";
|
import type { CliParsedArgs, OutputOptions } from "./types.js";
|
||||||
|
|
||||||
const KNOWN_BOOLEAN_FLAGS = new Set([
|
const KNOWN_BOOLEAN_FLAGS = new Set([
|
||||||
"raw",
|
"raw",
|
||||||
@@ -19,6 +19,10 @@ const KNOWN_BOOLEAN_FLAGS = new Set([
|
|||||||
"local",
|
"local",
|
||||||
"workspace",
|
"workspace",
|
||||||
"external",
|
"external",
|
||||||
|
"full",
|
||||||
|
"allow-full",
|
||||||
|
"allowFull",
|
||||||
|
"summary",
|
||||||
]);
|
]);
|
||||||
|
|
||||||
export function parseArgs(rawArgs: string[]): CliParsedArgs {
|
export function parseArgs(rawArgs: string[]): CliParsedArgs {
|
||||||
@@ -61,7 +65,17 @@ export function parseArgs(rawArgs: string[]): CliParsedArgs {
|
|||||||
if (flag === "h") options.help = true;
|
if (flag === "h") options.help = true;
|
||||||
else if (flag === "j") options.json = true;
|
else if (flag === "j") options.json = true;
|
||||||
else if (flag === "v") options.version = true;
|
else if (flag === "v") options.version = true;
|
||||||
else options[flag] = true;
|
else if (flag === "o") {
|
||||||
|
const next = rawArgs[i + 1];
|
||||||
|
if (next && !next.startsWith("-")) {
|
||||||
|
options.outputFile = next;
|
||||||
|
i++;
|
||||||
|
} else {
|
||||||
|
options.o = true;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
options[flag] = true;
|
||||||
|
}
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -121,3 +135,11 @@ export function numberOption(
|
|||||||
}
|
}
|
||||||
return fallback;
|
return fallback;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function outputOptions(options: Record<string, unknown>): OutputOptions {
|
||||||
|
return {
|
||||||
|
allowFull: booleanOption(options, ["full", "allow-full", "allowFull"]),
|
||||||
|
outputFile: stringOption(options, ["output-file", "outputFile", "o"]),
|
||||||
|
summary: booleanOption(options, ["summary"]),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
import { describe, expect, test, beforeEach, afterEach } from "bun:test";
|
||||||
|
import { mkdtempSync, rmSync, existsSync, readFileSync } from "node:fs";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import {
|
||||||
|
DEFAULT_OUTPUT_BYTES_LIMIT,
|
||||||
|
protectLargeOutput,
|
||||||
|
printJson,
|
||||||
|
redactSensitiveText,
|
||||||
|
} from "./printer.js";
|
||||||
|
|
||||||
|
describe("cli/printer - 上下文防爆与敏感脱敏", () => {
|
||||||
|
describe("redactSensitiveText 脱敏处理", () => {
|
||||||
|
test("脱敏 URL Query 中的 accessToken / token / returnToken", () => {
|
||||||
|
const input = "https://app.ekuaibao.com/api/test?accessToken=sec_123456&corpId=corpxx&returnToken=ret_789";
|
||||||
|
const redacted = redactSensitiveText(input);
|
||||||
|
expect(redacted).not.toContain("sec_123456");
|
||||||
|
expect(redacted).not.toContain("ret_789");
|
||||||
|
expect(redacted).toContain("accessToken=<redacted>");
|
||||||
|
expect(redacted).toContain("returnToken=<redacted>");
|
||||||
|
expect(redacted).toContain("corpId=corpxx");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("脱敏 Authorization Bearer token", () => {
|
||||||
|
const input = "Request headers: Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.xyz";
|
||||||
|
const redacted = redactSensitiveText(input);
|
||||||
|
expect(redacted).not.toContain("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.xyz");
|
||||||
|
expect(redacted).toContain("Bearer <redacted>");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("脱敏 password、secret、appSecurity 等键值", () => {
|
||||||
|
const input = '{"username": "admin", "password": "super_secret_password_123", "appSecurity": "sec_key"}';
|
||||||
|
const redacted = redactSensitiveText(input);
|
||||||
|
expect(redacted).not.toContain("super_secret_password_123");
|
||||||
|
expect(redacted).not.toContain("sec_key");
|
||||||
|
expect(redacted).toContain('"password": "<redacted>"');
|
||||||
|
expect(redacted).toContain('"appSecurity": "<redacted>"');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("protectLargeOutput 与 printJson 体积熔断保护", () => {
|
||||||
|
let tempDir: string;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
tempDir = mkdtempSync(join(tmpdir(), "hose-printer-test-"));
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
try {
|
||||||
|
rmSync(tempDir, { recursive: true, force: true });
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("正常体积的数据可以直接输出 JSON", () => {
|
||||||
|
const normalData = { hello: "world", numbers: [1, 2, 3] };
|
||||||
|
expect(() => protectLargeOutput(normalData)).not.toThrow();
|
||||||
|
const output = printJson(normalData);
|
||||||
|
expect(JSON.parse(output)).toEqual(normalData);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("超过 200KB 的巨型数据默认抛出熔断错误", () => {
|
||||||
|
// 构造超过 200KB 的大数组
|
||||||
|
const bigArray = Array.from({ length: 1500 }, (_, i) => ({
|
||||||
|
id: `id-${i}`,
|
||||||
|
description: "这是一个用于测试大报文熔断拦截的测试长字段内容,模拟企业级海量单据与工作流节点拓扑",
|
||||||
|
nested: { count: i, payload: "x".repeat(120) },
|
||||||
|
}));
|
||||||
|
|
||||||
|
expect(() => protectLargeOutput(bigArray)).toThrow(
|
||||||
|
/输出体积过大.*超过安全阈值.*--output-file.*--full/
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(() => printJson(bigArray)).toThrow(/输出体积过大/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("显式指定 allowFull 时允许全量输出大报文", () => {
|
||||||
|
const bigArray = Array.from({ length: 1500 }, (_, i) => ({
|
||||||
|
id: `id-${i}`,
|
||||||
|
payload: "y".repeat(150),
|
||||||
|
}));
|
||||||
|
|
||||||
|
expect(() => protectLargeOutput(bigArray, { allowFull: true })).not.toThrow();
|
||||||
|
const output = printJson(bigArray, { allowFull: true });
|
||||||
|
expect(output.length).toBeGreaterThan(DEFAULT_OUTPUT_BYTES_LIMIT);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("指定 outputFile 时大报文直接落盘并返回精简摘要", () => {
|
||||||
|
const targetFile = join(tempDir, "exported-bills.json");
|
||||||
|
const bigArray = Array.from({ length: 1500 }, (_, i) => ({
|
||||||
|
id: `id-${i}`,
|
||||||
|
payload: "z".repeat(150),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const resultJson = printJson(bigArray, { outputFile: targetFile });
|
||||||
|
const summary = JSON.parse(resultJson);
|
||||||
|
|
||||||
|
expect(summary.outputFile).toBe(targetFile);
|
||||||
|
expect(summary.bytes).toBeGreaterThan(DEFAULT_OUTPUT_BYTES_LIMIT);
|
||||||
|
expect(existsSync(targetFile)).toBe(true);
|
||||||
|
|
||||||
|
const savedContent = JSON.parse(readFileSync(targetFile, "utf-8"));
|
||||||
|
expect(savedContent).toHaveLength(1500);
|
||||||
|
expect(savedContent[0].id).toBe("id-0");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
+46
-8
@@ -1,7 +1,41 @@
|
|||||||
|
import { writeFileSync } from "node:fs";
|
||||||
import { VERSION } from "../version.js";
|
import { VERSION } from "../version.js";
|
||||||
|
import type { OutputOptions } from "./types.js";
|
||||||
|
|
||||||
export function printJson(data: unknown): string {
|
export const DEFAULT_OUTPUT_BYTES_LIMIT = 200_000;
|
||||||
return JSON.stringify(data, null, 2);
|
|
||||||
|
export function redactSensitiveText(value: string): string {
|
||||||
|
return value
|
||||||
|
.replace(/([?&](?:accessToken|token|returnToken)=)[^&\s"']+/gi, "$1<redacted>")
|
||||||
|
.replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi, "$1<redacted>")
|
||||||
|
.replace(/((?:password|passwd|secret|appSecurity)["']?\s*[:=]\s*["']?)[^"',\s}]+/gi, "$1<redacted>");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function protectLargeOutput(result: unknown, options: OutputOptions = {}) {
|
||||||
|
if (options.allowFull || options.outputFile) return;
|
||||||
|
const bodyBytes = Buffer.byteLength(JSON.stringify(result), "utf-8");
|
||||||
|
if (bodyBytes > DEFAULT_OUTPUT_BYTES_LIMIT) {
|
||||||
|
throw new Error(
|
||||||
|
`输出体积过大 (${bodyBytes} 字节,超过安全阈值 ${DEFAULT_OUTPUT_BYTES_LIMIT} 字节)。请使用 --output-file <路径> (或 -o <路径>) 转储到本地文件;若确需完整大报文请附加 --full 参数。`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function printJson(data: unknown, options: OutputOptions = {}): string {
|
||||||
|
protectLargeOutput(data, options);
|
||||||
|
const json = JSON.stringify(data, null, 2);
|
||||||
|
if (options.outputFile) {
|
||||||
|
writeFileSync(options.outputFile, json, "utf-8");
|
||||||
|
return JSON.stringify(
|
||||||
|
{
|
||||||
|
outputFile: options.outputFile,
|
||||||
|
bytes: Buffer.byteLength(json, "utf-8"),
|
||||||
|
},
|
||||||
|
null,
|
||||||
|
2
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return json;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function formatSourceLabel(source?: string): string {
|
export function formatSourceLabel(source?: string): string {
|
||||||
@@ -83,7 +117,7 @@ export function printHelp(): string {
|
|||||||
核心命令域:
|
核心命令域:
|
||||||
auth 认证与凭证管理 (login, status, refresh, import, accounts)
|
auth 认证与凭证管理 (login, status, refresh, import, accounts)
|
||||||
corps 多企业租户管理 (list, switch, current)
|
corps 多企业租户管理 (list, switch, current)
|
||||||
config 全局运行模式 (show, mode <stateful|stateless>, set)
|
config 全局运行模式与路径诊断 (show, paths, mode <stateful|stateless>, set)
|
||||||
workflow 工作流管理 (list, get, find, toggle)
|
workflow 工作流管理 (list, get, find, toggle)
|
||||||
bill 单据与费用明细检索 (list, get <单号|ID>, schema)
|
bill 单据与费用明细检索 (list, get <单号|ID>, schema)
|
||||||
platform 自建应用管理 (list)
|
platform 自建应用管理 (list)
|
||||||
@@ -95,21 +129,25 @@ export function printHelp(): string {
|
|||||||
version 查看版本信息
|
version 查看版本信息
|
||||||
|
|
||||||
全局选项:
|
全局选项:
|
||||||
--corp=<id> 临时指定操作的企业/身份 ID (覆盖默认企业)
|
--corp=<id> 临时指定操作的企业/身份 ID (覆盖默认企业)
|
||||||
--json, -j 以 JSON 结构化输出结果 (适合脚本/流水线集成)
|
--json, -j 以 JSON 结构化输出结果 (适合脚本/流水线集成)
|
||||||
--stateless 单次强制以无状态模式执行
|
--output-file, -o 将大体积结果直接转储至本地文件并输出精简摘要
|
||||||
--stateful 单次强制以有状态模式执行
|
--full 允许全量输出大体积 JSON (绕过 200KB 防爆拦截)
|
||||||
--help, -h 查看帮助信息
|
--stateless 单次强制以无状态模式执行
|
||||||
|
--stateful 单次强制以有状态模式执行
|
||||||
|
--help, -h 查看帮助信息
|
||||||
|
|
||||||
常用示例:
|
常用示例:
|
||||||
hose-use auth login --phone=177... --password=... # 纯 API 账密自动登录
|
hose-use auth login --phone=177... --password=... # 纯 API 账密自动登录
|
||||||
hose-use auth status # 查看当前登录状态与活跃企业
|
hose-use auth status # 查看当前登录状态与活跃企业
|
||||||
|
hose-use config paths # 查看多级企业配置目录链
|
||||||
hose-use config mode stateless # 切换为无状态模式 (防止 Agent 误操作)
|
hose-use config mode stateless # 切换为无状态模式 (防止 Agent 误操作)
|
||||||
hose-use corps list # 列出名下所有企业
|
hose-use corps list # 列出名下所有企业
|
||||||
hose-use corps switch uzU7pcWfScck00 # 切换工作企业
|
hose-use corps switch uzU7pcWfScck00 # 切换工作企业
|
||||||
hose-use workflow list # 汇总查看全部工作流
|
hose-use workflow list # 汇总查看全部工作流
|
||||||
hose-use workflow find --task=code-js2 # 搜索包含自定义脚本的工作流
|
hose-use workflow find --task=code-js2 # 搜索包含自定义脚本的工作流
|
||||||
hose-use bill list # 查看当前企业单据与报销列表
|
hose-use bill list # 查看当前企业单据与报销列表
|
||||||
|
hose-use bill list --json -o /tmp/bills.json # 导出单据报文到本地磁盘并防爆
|
||||||
hose-use bill get n0GMIM0dkQmKbS # 根据单号精准查询单据结构化详情
|
hose-use bill get n0GMIM0dkQmKbS # 根据单号精准查询单据结构化详情
|
||||||
hose-use probe # 诊断当前企业鉴权连通性
|
hose-use probe # 诊断当前企业鉴权连通性
|
||||||
hose-use skill install # 安装 Agent 技能到用户目录
|
hose-use skill install # 安装 Agent 技能到用户目录
|
||||||
|
|||||||
+7
-5
@@ -1,6 +1,6 @@
|
|||||||
import { VERSION } from "../version.js";
|
import { VERSION } from "../version.js";
|
||||||
import { parseArgs, stringOption, booleanOption } from "./parser.js";
|
import { parseArgs, stringOption, booleanOption, outputOptions } from "./parser.js";
|
||||||
import { printHelp, printJson } from "./printer.js";
|
import { printHelp, printJson, redactSensitiveText } from "./printer.js";
|
||||||
import { initCorpRuntime } from "./helpers.js";
|
import { initCorpRuntime } from "./helpers.js";
|
||||||
import { handleAuthCommand } from "./commands/auth.js";
|
import { handleAuthCommand } from "./commands/auth.js";
|
||||||
import { handleCorpsCommand } from "./commands/corps.js";
|
import { handleCorpsCommand } from "./commands/corps.js";
|
||||||
@@ -50,8 +50,8 @@ async function runCliOnce(
|
|||||||
const extraStdout = stdoutChunks.length ? `${stdoutChunks.join("\n")}\n` : "";
|
const extraStdout = stdoutChunks.length ? `${stdoutChunks.join("\n")}\n` : "";
|
||||||
const extraStderr = stderrChunks.length ? `${stderrChunks.join("\n")}\n` : "";
|
const extraStderr = stderrChunks.length ? `${stderrChunks.join("\n")}\n` : "";
|
||||||
return {
|
return {
|
||||||
stdout: extraStdout + (result.stdout || ""),
|
stdout: redactSensitiveText(extraStdout + (result.stdout || "")),
|
||||||
stderr: extraStderr + (result.stderr || ""),
|
stderr: redactSensitiveText(extraStderr + (result.stderr || "")),
|
||||||
exitCode: result.exitCode,
|
exitCode: result.exitCode,
|
||||||
};
|
};
|
||||||
} finally {
|
} finally {
|
||||||
@@ -78,12 +78,14 @@ async function dispatchCli(
|
|||||||
const corpIdOption = stringOption(parsed.options, ["corp", "c"]);
|
const corpIdOption = stringOption(parsed.options, ["corp", "c"]);
|
||||||
const statelessOption = booleanOption(parsed.options, ["stateless"]);
|
const statelessOption = booleanOption(parsed.options, ["stateless"]);
|
||||||
const statefulOption = booleanOption(parsed.options, ["stateful"]);
|
const statefulOption = booleanOption(parsed.options, ["stateful"]);
|
||||||
|
const outputOpts = outputOptions(parsed.options);
|
||||||
|
|
||||||
const runtime = initCorpRuntime({
|
const runtime = initCorpRuntime({
|
||||||
corpId: corpIdOption,
|
corpId: corpIdOption,
|
||||||
stateless: statelessOption,
|
stateless: statelessOption,
|
||||||
stateful: statefulOption,
|
stateful: statefulOption,
|
||||||
jsonMode,
|
jsonMode,
|
||||||
|
outputOptions: outputOpts,
|
||||||
});
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -141,7 +143,7 @@ async function dispatchCli(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const errorMsg = error instanceof Error ? error.message : String(error);
|
const errorMsg = redactSensitiveText(error instanceof Error ? error.message : String(error));
|
||||||
if (jsonMode) {
|
if (jsonMode) {
|
||||||
return {
|
return {
|
||||||
stdout: printJson({ error: true, message: errorMsg }),
|
stdout: printJson({ error: true, message: errorMsg }),
|
||||||
|
|||||||
@@ -21,8 +21,15 @@ export interface CliResult {
|
|||||||
exitCode: number;
|
exitCode: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface OutputOptions {
|
||||||
|
allowFull?: boolean;
|
||||||
|
outputFile?: string;
|
||||||
|
summary?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
export interface CliRuntime {
|
export interface CliRuntime {
|
||||||
corpContext: CorpContext;
|
corpContext: CorpContext;
|
||||||
selectedCorp: CorpConfig | null;
|
selectedCorp: CorpConfig | null;
|
||||||
jsonMode: boolean;
|
jsonMode: boolean;
|
||||||
|
outputOptions?: OutputOptions;
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||||
|
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readFileSync } from "node:fs";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import {
|
||||||
|
loadCorpConfigs,
|
||||||
|
saveCorpConfig,
|
||||||
|
resolveEnterprisesDirs,
|
||||||
|
resolveWritableEnterprisesDir,
|
||||||
|
loadGlobalConfig,
|
||||||
|
saveGlobalConfig,
|
||||||
|
resolveGlobalConfigFile,
|
||||||
|
} from "./loader.js";
|
||||||
|
import type { CorpConfig } from "./types.js";
|
||||||
|
|
||||||
|
describe("core/config/loader", () => {
|
||||||
|
let tempDir: string;
|
||||||
|
const originalEnv = { ...process.env };
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
tempDir = mkdtempSync(join(tmpdir(), "hose-config-test-"));
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
process.env = { ...originalEnv };
|
||||||
|
try {
|
||||||
|
rmSync(tempDir, { recursive: true, force: true });
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("resolveEnterprisesDirs prioritizes HOSE_ENTERPRISES_DIR environment variable", () => {
|
||||||
|
const customDir = join(tempDir, "custom-enterprises");
|
||||||
|
mkdirSync(customDir, { recursive: true });
|
||||||
|
process.env.HOSE_ENTERPRISES_DIR = customDir;
|
||||||
|
|
||||||
|
const dirs = resolveEnterprisesDirs();
|
||||||
|
expect(dirs).toEqual([customDir]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("resolveWritableEnterprisesDir respects HOSE_ENTERPRISES_DIR", () => {
|
||||||
|
const customDir = join(tempDir, "writable-enterprises");
|
||||||
|
mkdirSync(customDir, { recursive: true });
|
||||||
|
process.env.HOSE_ENTERPRISES_DIR = customDir;
|
||||||
|
|
||||||
|
expect(resolveWritableEnterprisesDir()).toBe(customDir);
|
||||||
|
});
|
||||||
|
|
||||||
|
const createMockCorp = (id: string, name: string, overrides: Partial<CorpConfig> = {}): CorpConfig => ({
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
baseUrl: "https://app.ekuaibao.com",
|
||||||
|
source: "manual",
|
||||||
|
credentials: {
|
||||||
|
accessToken: `token-${id}`,
|
||||||
|
corpId: id,
|
||||||
|
staffId: `staff-${id}`,
|
||||||
|
},
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
test("loadCorpConfigs loads valid configs and skips example files", () => {
|
||||||
|
const dirA = join(tempDir, "dirA");
|
||||||
|
mkdirSync(dirA, { recursive: true });
|
||||||
|
|
||||||
|
const validCorp = createMockCorp("corp-1", "企业1");
|
||||||
|
|
||||||
|
// Save valid corp
|
||||||
|
writeFileSync(join(dirA, "corp-1.json"), JSON.stringify(validCorp));
|
||||||
|
// Save example corp
|
||||||
|
writeFileSync(
|
||||||
|
join(dirA, "example.json"),
|
||||||
|
JSON.stringify(createMockCorp("example-corp", "模板企业"))
|
||||||
|
);
|
||||||
|
|
||||||
|
const loaded = loadCorpConfigs([dirA]);
|
||||||
|
expect(loaded).toHaveLength(1);
|
||||||
|
expect(loaded[0]?.id).toBe("corp-1");
|
||||||
|
expect(loaded[0]?.name).toBe("企业1");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("loadCorpConfigs merges multiple directories with earlier directory taking precedence", () => {
|
||||||
|
const dirA = join(tempDir, "dirA");
|
||||||
|
const dirB = join(tempDir, "dirB");
|
||||||
|
mkdirSync(dirA, { recursive: true });
|
||||||
|
mkdirSync(dirB, { recursive: true });
|
||||||
|
|
||||||
|
const corpInA = createMockCorp("corp-common", "本地优先企业", {
|
||||||
|
credentials: { accessToken: "token-a", corpId: "corp-common", staffId: "staff-a" },
|
||||||
|
});
|
||||||
|
|
||||||
|
const corpInB = createMockCorp("corp-common", "全局覆盖企业", {
|
||||||
|
credentials: { accessToken: "token-b", corpId: "corp-common", staffId: "staff-b" },
|
||||||
|
});
|
||||||
|
|
||||||
|
const corpOnlyB = createMockCorp("corp-b-only", "仅在B的企业", {
|
||||||
|
credentials: { accessToken: "token-b2", corpId: "corp-b-only", staffId: "staff-b2" },
|
||||||
|
});
|
||||||
|
|
||||||
|
writeFileSync(join(dirA, "corp-common.json"), JSON.stringify(corpInA));
|
||||||
|
writeFileSync(join(dirB, "corp-common.json"), JSON.stringify(corpInB));
|
||||||
|
writeFileSync(join(dirB, "corp-b-only.json"), JSON.stringify(corpOnlyB));
|
||||||
|
|
||||||
|
const loaded = loadCorpConfigs([dirA, dirB]);
|
||||||
|
expect(loaded).toHaveLength(2);
|
||||||
|
|
||||||
|
const common = loaded.find((c) => c.id === "corp-common");
|
||||||
|
expect(common?.name).toBe("本地优先企业");
|
||||||
|
|
||||||
|
const bOnly = loaded.find((c) => c.id === "corp-b-only");
|
||||||
|
expect(bOnly?.name).toBe("仅在B的企业");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("saveCorpConfig writes validated JSON to target directory", () => {
|
||||||
|
const targetDir = join(tempDir, "save-target");
|
||||||
|
const corp = createMockCorp("corp-save-test", "保存测试企业", {
|
||||||
|
credentials: { accessToken: "tok-123", corpId: "corp-save-test", staffId: "stf-1" },
|
||||||
|
});
|
||||||
|
|
||||||
|
const filePath = saveCorpConfig(corp, targetDir);
|
||||||
|
expect(existsSync(filePath)).toBe(true);
|
||||||
|
|
||||||
|
const saved = JSON.parse(readFileSync(filePath, "utf-8"));
|
||||||
|
expect(saved.id).toBe("corp-save-test");
|
||||||
|
expect(saved.credentials.accessToken).toBe("tok-123");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("loadGlobalConfig and saveGlobalConfig respect HOSE_CONFIG_FILE", () => {
|
||||||
|
const customConfigFile = join(tempDir, "config.json");
|
||||||
|
process.env.HOSE_CONFIG_FILE = customConfigFile;
|
||||||
|
|
||||||
|
expect(resolveGlobalConfigFile()).toBe(customConfigFile);
|
||||||
|
|
||||||
|
const initial = loadGlobalConfig();
|
||||||
|
expect(initial.stateful).toBe(true);
|
||||||
|
|
||||||
|
saveGlobalConfig({ stateful: false, defaultCorpId: "test-corp-123" });
|
||||||
|
const updated = loadGlobalConfig();
|
||||||
|
expect(updated.stateful).toBe(false);
|
||||||
|
expect(updated.defaultCorpId).toBe("test-corp-123");
|
||||||
|
});
|
||||||
|
});
|
||||||
+114
-37
@@ -1,30 +1,96 @@
|
|||||||
import { readFileSync, readdirSync, writeFileSync, mkdirSync } from "fs";
|
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
|
||||||
import { join, dirname } from "path";
|
import { homedir } from "node:os";
|
||||||
import { homedir } from "os";
|
import { dirname, join } from "node:path";
|
||||||
import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigSchema } from "./types.js";
|
import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigSchema } from "./types.js";
|
||||||
|
|
||||||
const ENTERPRISES_DIR = "./enterprises";
|
const ENTERPRISES_DIR = "enterprises";
|
||||||
const GLOBAL_CONFIG_PATH = join(homedir(), ".cache", "ekb-mcp", "config.json");
|
const CONFIG_ENV = "HOSE_ENTERPRISES_DIR";
|
||||||
|
const USER_DIR_ENV = "HOSE_USER_ENTERPRISES_DIR";
|
||||||
|
const GLOBAL_CONFIG_ENV = "HOSE_CONFIG_FILE";
|
||||||
|
|
||||||
|
export const PRIMARY_USER_ENTERPRISES_DIR = join(homedir(), ".config", "hose-use", "enterprises");
|
||||||
|
export const LEGACY_USER_ENTERPRISES_DIR = join(homedir(), ".cache", "ekb-mcp", "enterprises");
|
||||||
|
export const USER_ENTERPRISES_DIR = PRIMARY_USER_ENTERPRISES_DIR;
|
||||||
|
|
||||||
|
export const PRIMARY_GLOBAL_CONFIG_FILE = join(homedir(), ".config", "hose-use", "config.json");
|
||||||
|
export const LEGACY_GLOBAL_CONFIG_FILE = join(homedir(), ".cache", "ekb-mcp", "config.json");
|
||||||
|
|
||||||
function ensureDir(dir: string): void {
|
function ensureDir(dir: string): void {
|
||||||
mkdirSync(dir, { recursive: true });
|
mkdirSync(dir, { recursive: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function resolveEnterprisesDirs(): string[] {
|
||||||
|
const configured = process.env[CONFIG_ENV]?.trim();
|
||||||
|
if (configured) {
|
||||||
|
return existsSync(configured) ? [configured] : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const configuredUserDir = process.env[USER_DIR_ENV]?.trim();
|
||||||
|
if (configuredUserDir) {
|
||||||
|
return [ENTERPRISES_DIR, configuredUserDir].filter((dir) => existsSync(dir));
|
||||||
|
}
|
||||||
|
|
||||||
|
const dirs = [ENTERPRISES_DIR, PRIMARY_USER_ENTERPRISES_DIR, LEGACY_USER_ENTERPRISES_DIR];
|
||||||
|
const uniqueExisting: string[] = [];
|
||||||
|
for (const d of dirs) {
|
||||||
|
if (existsSync(d) && !uniqueExisting.includes(d)) {
|
||||||
|
uniqueExisting.push(d);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return uniqueExisting;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolvePrimaryEnterprisesDir(): string | undefined {
|
||||||
|
const configured = process.env[CONFIG_ENV]?.trim();
|
||||||
|
if (configured) return existsSync(configured) ? configured : undefined;
|
||||||
|
if (existsSync(ENTERPRISES_DIR)) return ENTERPRISES_DIR;
|
||||||
|
if (existsSync(PRIMARY_USER_ENTERPRISES_DIR)) return PRIMARY_USER_ENTERPRISES_DIR;
|
||||||
|
if (existsSync(LEGACY_USER_ENTERPRISES_DIR)) return LEGACY_USER_ENTERPRISES_DIR;
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveWritableEnterprisesDir(): string {
|
||||||
|
const configured = process.env[CONFIG_ENV]?.trim();
|
||||||
|
if (configured) return configured;
|
||||||
|
const configuredUserDir = process.env[USER_DIR_ENV]?.trim();
|
||||||
|
if (configuredUserDir) return configuredUserDir;
|
||||||
|
if (existsSync(ENTERPRISES_DIR)) return ENTERPRISES_DIR;
|
||||||
|
return PRIMARY_USER_ENTERPRISES_DIR;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getEnterprisesDirCandidates(): string[] {
|
||||||
|
return [
|
||||||
|
`${CONFIG_ENV}=<path>`,
|
||||||
|
ENTERPRISES_DIR,
|
||||||
|
PRIMARY_USER_ENTERPRISES_DIR,
|
||||||
|
LEGACY_USER_ENTERPRISES_DIR,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
export function resolveGlobalConfigFile(): string {
|
export function resolveGlobalConfigFile(): string {
|
||||||
return GLOBAL_CONFIG_PATH;
|
const configured = process.env[GLOBAL_CONFIG_ENV]?.trim();
|
||||||
|
if (configured) return configured;
|
||||||
|
if (existsSync(PRIMARY_GLOBAL_CONFIG_FILE)) return PRIMARY_GLOBAL_CONFIG_FILE;
|
||||||
|
if (existsSync(LEGACY_GLOBAL_CONFIG_FILE)) return LEGACY_GLOBAL_CONFIG_FILE;
|
||||||
|
return PRIMARY_GLOBAL_CONFIG_FILE;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function loadGlobalConfig(): GlobalConfig {
|
export function loadGlobalConfig(): GlobalConfig {
|
||||||
|
const file = resolveGlobalConfigFile();
|
||||||
try {
|
try {
|
||||||
const content = readFileSync(GLOBAL_CONFIG_PATH, "utf-8");
|
if (existsSync(file)) {
|
||||||
return GlobalConfigSchema.parse(JSON.parse(content));
|
const content = readFileSync(file, "utf-8");
|
||||||
|
return GlobalConfigSchema.parse(JSON.parse(content));
|
||||||
|
}
|
||||||
} catch {
|
} catch {
|
||||||
return {
|
// 容错返回默认
|
||||||
stateful: true,
|
|
||||||
defaultCorpId: undefined,
|
|
||||||
defaultAccountId: undefined,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
stateful: true,
|
||||||
|
defaultCorpId: undefined,
|
||||||
|
defaultAccountId: undefined,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function saveGlobalConfig(config: Partial<GlobalConfig>): GlobalConfig {
|
export function saveGlobalConfig(config: Partial<GlobalConfig>): GlobalConfig {
|
||||||
@@ -33,50 +99,61 @@ export function saveGlobalConfig(config: Partial<GlobalConfig>): GlobalConfig {
|
|||||||
...current,
|
...current,
|
||||||
...config,
|
...config,
|
||||||
});
|
});
|
||||||
ensureDir(dirname(GLOBAL_CONFIG_PATH));
|
|
||||||
writeFileSync(GLOBAL_CONFIG_PATH, JSON.stringify(updated, null, 2), "utf-8");
|
const configured = process.env[GLOBAL_CONFIG_ENV]?.trim();
|
||||||
|
const targetFile = configured || PRIMARY_GLOBAL_CONFIG_FILE;
|
||||||
|
ensureDir(dirname(targetFile));
|
||||||
|
writeFileSync(targetFile, JSON.stringify(updated, null, 2), "utf-8");
|
||||||
return updated;
|
return updated;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function loadCorpConfigs(dir: string = ENTERPRISES_DIR): CorpConfig[] {
|
export function loadCorpConfigs(overrideDirs?: string[]): CorpConfig[] {
|
||||||
let files: string[];
|
const dirs = overrideDirs ? overrideDirs.filter(existsSync) : resolveEnterprisesDirs();
|
||||||
try {
|
const byId = new Map<string, CorpConfig>();
|
||||||
ensureDir(dir);
|
|
||||||
files = readdirSync(dir).filter((f) => f.endsWith(".json"));
|
|
||||||
} catch (error) {
|
|
||||||
console.error(
|
|
||||||
`[config] failed to read enterprises directory: ${error instanceof Error ? error.message : String(error)}`
|
|
||||||
);
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
const configs: CorpConfig[] = [];
|
for (const dir of dirs) {
|
||||||
for (const file of files) {
|
|
||||||
try {
|
try {
|
||||||
const content = readFileSync(join(dir, file), "utf-8");
|
const files = readdirSync(dir)
|
||||||
const parsed = JSON.parse(content);
|
.filter((item) => item.endsWith(".json"))
|
||||||
configs.push(CorpConfigSchema.parse(parsed));
|
.filter((item) => !item.startsWith("example."));
|
||||||
|
|
||||||
|
for (const file of files) {
|
||||||
|
try {
|
||||||
|
const content = readFileSync(join(dir, file), "utf-8");
|
||||||
|
const parsed = JSON.parse(content);
|
||||||
|
const corp = CorpConfigSchema.parse(parsed);
|
||||||
|
// 相同企业 ID 以先出现的为准(工作区优先于全局,全局优先于历史)
|
||||||
|
if (!byId.has(corp.id)) {
|
||||||
|
byId.set(corp.id, corp);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error(
|
||||||
|
`[config] failed to load ${file} from ${dir}: ${error instanceof Error ? error.message : String(error)}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(
|
console.error(
|
||||||
`[config] failed to load ${file}: ${error instanceof Error ? error.message : String(error)}`
|
`[config] failed to read enterprises directory ${dir}: ${error instanceof Error ? error.message : String(error)}`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return configs;
|
return Array.from(byId.values());
|
||||||
}
|
}
|
||||||
|
|
||||||
export function saveCorpConfig(config: CorpConfig, dir: string = ENTERPRISES_DIR): string {
|
export function saveCorpConfig(config: CorpConfig, dir?: string): string {
|
||||||
ensureDir(dir);
|
const targetDir = dir || resolveWritableEnterprisesDir();
|
||||||
|
ensureDir(targetDir);
|
||||||
const validated = CorpConfigSchema.parse(config);
|
const validated = CorpConfigSchema.parse(config);
|
||||||
const filePath = join(dir, `${validated.id}.json`);
|
const filePath = join(targetDir, `${validated.id}.json`);
|
||||||
writeFileSync(filePath, JSON.stringify(validated, null, 2), "utf-8");
|
writeFileSync(filePath, JSON.stringify(validated, null, 2), "utf-8");
|
||||||
return filePath;
|
return filePath;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function saveMultipleCorpConfigs(
|
export function saveMultipleCorpConfigs(
|
||||||
configs: CorpConfig[],
|
configs: CorpConfig[],
|
||||||
dir: string = ENTERPRISES_DIR
|
dir?: string
|
||||||
): string[] {
|
): string[] {
|
||||||
return configs.map((config) => saveCorpConfig(config, dir));
|
return configs.map((config) => saveCorpConfig(config, dir));
|
||||||
}
|
}
|
||||||
@@ -18,7 +18,8 @@ export function resolveCorpConfig(
|
|||||||
stateful: boolean;
|
stateful: boolean;
|
||||||
defaultCorpId?: string;
|
defaultCorpId?: string;
|
||||||
corpId?: string;
|
corpId?: string;
|
||||||
}
|
},
|
||||||
|
candidateDirs?: string[]
|
||||||
): CorpConfig {
|
): CorpConfig {
|
||||||
const requestedCorpId = options.corpId?.trim() || undefined;
|
const requestedCorpId = options.corpId?.trim() || undefined;
|
||||||
const configuredCorpId = options.stateful
|
const configuredCorpId = options.stateful
|
||||||
@@ -51,7 +52,8 @@ export function resolveCorpConfig(
|
|||||||
const firstCorp = corps[0];
|
const firstCorp = corps[0];
|
||||||
if (firstCorp) return firstCorp;
|
if (firstCorp) return firstCorp;
|
||||||
|
|
||||||
throw new Error("未找到任何企业配置。请先运行 `hose auth login` 或在 enterprises/ 目录下添加配置。");
|
const hintDirs = candidateDirs?.length ? ` (已检索路径: ${candidateDirs.join(", ")})` : "";
|
||||||
|
throw new Error(`未找到任何企业配置。请先运行 'hose auth login' 登录或添加企业配置${hintDirs}。`);
|
||||||
}
|
}
|
||||||
|
|
||||||
export class CorpContext {
|
export class CorpContext {
|
||||||
@@ -110,12 +112,16 @@ export class CorpContext {
|
|||||||
return this.corps.get(corpId);
|
return this.corps.get(corpId);
|
||||||
}
|
}
|
||||||
|
|
||||||
resolve(corpId?: string): CorpConfig {
|
resolve(corpId?: string, candidateDirs?: string[]): CorpConfig {
|
||||||
return resolveCorpConfig(Array.from(this.corps.values()), {
|
return resolveCorpConfig(
|
||||||
stateful: this.stateful,
|
Array.from(this.corps.values()),
|
||||||
defaultCorpId: this.defaultCorpId,
|
{
|
||||||
corpId,
|
stateful: this.stateful,
|
||||||
});
|
defaultCorpId: this.defaultCorpId,
|
||||||
|
corpId,
|
||||||
|
},
|
||||||
|
candidateDirs
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
upsertCorp(corp: CorpConfig, setCurrent: boolean = false): void {
|
upsertCorp(corp: CorpConfig, setCurrent: boolean = false): void {
|
||||||
|
|||||||
+2
-1
@@ -94,7 +94,8 @@ describe("hose-use MCP server & hose_cli single-gate pattern", () => {
|
|||||||
});
|
});
|
||||||
expect(corpsResult.isError).not.toBe(true);
|
expect(corpsResult.isError).not.toBe(true);
|
||||||
const corpsContent = corpsResult.content as Array<{ type: "text"; text: string }>;
|
const corpsContent = corpsResult.content as Array<{ type: "text"; text: string }>;
|
||||||
expect(corpsContent[0]?.text).toContain("已配置企业列表");
|
const text = corpsContent[0]?.text || "";
|
||||||
|
expect(text.includes("已配置企业列表") || text.includes("未找到任何企业配置")).toBe(true);
|
||||||
|
|
||||||
// Execute invalid command
|
// Execute invalid command
|
||||||
const invalidResult = await client.callTool({
|
const invalidResult = await client.callTool({
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import { authTools } from "./core/auth/tools.js";
|
|||||||
import { platformTools } from "./domains/platform/tools.js";
|
import { platformTools } from "./domains/platform/tools.js";
|
||||||
import { billTools } from "./domains/bill/tools.js";
|
import { billTools } from "./domains/bill/tools.js";
|
||||||
import { runCli } from "./cli/runner.js";
|
import { runCli } from "./cli/runner.js";
|
||||||
|
import { redactSensitiveText } from "./cli/printer.js";
|
||||||
import { VERSION } from "./version.js";
|
import { VERSION } from "./version.js";
|
||||||
import type { CliResult } from "./cli/types.js";
|
import type { CliResult } from "./cli/types.js";
|
||||||
|
|
||||||
@@ -114,6 +115,7 @@ export function cliResult(result: CliResult): {
|
|||||||
} {
|
} {
|
||||||
const isError = result.exitCode !== 0;
|
const isError = result.exitCode !== 0;
|
||||||
let text = isError ? (result.stderr || result.stdout || "Command failed") : (result.stdout || result.stderr || "Success");
|
let text = isError ? (result.stderr || result.stdout || "Command failed") : (result.stdout || result.stderr || "Success");
|
||||||
|
text = redactSensitiveText(text);
|
||||||
return {
|
return {
|
||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
|
|||||||
+1
-1
@@ -1 +1 @@
|
|||||||
export const VERSION = "0.4.0";
|
export const VERSION = "0.4.2";
|
||||||
Reference in new issue
Block a user