feat(cli): 支持大输出防爆保护、本地文件转储与敏感凭证全链路脱敏并发布 v0.4.2
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled

This commit is contained in:
gitea committed 2026-09-03 11:40:32 +08:00
1 parent cf44c7dcdf
commit ba30c1a6cb
16 files changed
+251 -51

No files matched your search

+4 -2
View File
@@ -1,4 +1,4 @@
# hose-use (v0.4.1)
# hose-use (v0.4.2)
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
@@ -45,8 +45,10 @@ hose-use workflow find --task=code-js2 # 搜索包含特定节点类型
hose-use workflow toggle <pipelineId> --state=1 # 启用/停用工作流
hose-use platform list # 查看企业下所有启用的自建应用
# 5. 单据与费用明细管理 (DataLink 字典自动还原)
# 5. 单据与费用明细管理 (DataLink 字典自动还原 & 200KB 防爆拦截)
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 schema # 查看企业全部单据实体与数据模型字典
+1 -1
View File
@@ -1,7 +1,7 @@
openapi: 3.1.0
info:
title: hose-use API & MCP Tools Specification
version: 0.4.1
version: 0.4.2
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.4.1",
"version": "0.4.2",
"module": "src/server.ts",
"type": "module",
"bin": {
+5
View File
@@ -120,6 +120,11 @@ hose-use platform list
hose-use bill list
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 字典自动还原)
hose-use bill get n0GMIM0dkQmKbS
hose-use bill get ID01TRzg7HMLcb
+28 -19
View File
@@ -43,13 +43,16 @@ export async function handleBillCommand(
if (runtime.jsonMode) {
return {
stdout: printJson({
corpId,
corpName: corp.name,
total: result.total,
returned: result.returned,
items: result.items,
}),
stdout: printJson(
{
corpId,
corpName: corp.name,
total: result.total,
returned: result.returned,
items: result.items,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
@@ -104,12 +107,15 @@ export async function handleBillCommand(
if (runtime.jsonMode) {
return {
stdout: printJson({
corpId,
corpName: corp.name,
count: bills.length,
bills,
}),
stdout: printJson(
{
corpId,
corpName: corp.name,
count: bills.length,
bills,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
@@ -157,12 +163,15 @@ export async function handleBillCommand(
if (runtime.jsonMode) {
return {
stdout: printJson({
corpId,
corpName: corp.name,
totalEntities: entities.length,
entities,
}),
stdout: printJson(
{
corpId,
corpName: corp.name,
totalEntities: entities.length,
entities,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
+9 -6
View File
@@ -29,10 +29,13 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
if (runtime.jsonMode) {
return {
stdout: printJson({
activeCorpId: runtime.selectedCorp?.id,
corporations: corps,
}),
stdout: printJson(
{
activeCorpId: runtime.selectedCorp?.id,
corporations: corps,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
@@ -81,7 +84,7 @@ async function handleSwitch(parsed: CliParsedArgs, runtime: CliRuntime): Promise
const current = runtime.corpContext.getCurrent();
if (runtime.jsonMode) {
return { stdout: printJson(current), stderr: "", exitCode: 0 };
return { stdout: printJson(current, runtime.outputOptions), stderr: "", exitCode: 0 };
}
return {
@@ -98,7 +101,7 @@ async function handleCurrent(parsed: CliParsedArgs, runtime: CliRuntime): Promis
}
if (runtime.jsonMode) {
return { stdout: printJson(current), stderr: "", exitCode: 0 };
return { stdout: printJson(current, runtime.outputOptions), stderr: "", exitCode: 0 };
}
const pairs: Record<string, unknown> = {
+1 -1
View File
@@ -36,7 +36,7 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
const platforms = await api.listPlatforms(clients.ekbClient, runtime.selectedCorp!.credentials.corpId);
if (runtime.jsonMode) {
return { stdout: printJson(platforms), stderr: "", exitCode: 0 };
return { stdout: printJson(platforms, runtime.outputOptions), stderr: "", exitCode: 0 };
}
if (platforms.length === 0) {
+4 -4
View File
@@ -54,7 +54,7 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
const result = await listAllWorkflows(clients, { page, pageSize });
if (runtime.jsonMode) {
return { stdout: printJson(result), stderr: "", exitCode: 0 };
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 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);
if (runtime.jsonMode) {
return { stdout: printJson(detail), stderr: "", exitCode: 0 };
return { stdout: printJson(detail, runtime.outputOptions), stderr: "", exitCode: 0 };
}
const summary = printKeyValue({
@@ -148,7 +148,7 @@ async function handleFind(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
});
if (runtime.jsonMode) {
return { stdout: printJson(result), stderr: "", exitCode: 0 };
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 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);
if (runtime.jsonMode) {
return { stdout: printJson(result), stderr: "", exitCode: 0 };
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
}
return {
+3 -1
View File
@@ -4,7 +4,7 @@ import { CorpContext, resolveCorpConfig } from "../core/config/manager.js";
import { CorpConfig } from "../core/config/types.js";
import { createEkbClient } from "../core/auth/ekb.js";
import { getEasoClient } from "../core/auth/easo.js";
import { CliRuntime } from "./types.js";
import { CliRuntime, OutputOptions } from "./types.js";
export function initCorpRuntime(
options: {
@@ -12,6 +12,7 @@ export function initCorpRuntime(
stateless?: boolean;
stateful?: boolean;
jsonMode?: boolean;
outputOptions?: OutputOptions;
} = {}
): CliRuntime {
const corps = loadCorpConfigs();
@@ -40,6 +41,7 @@ export function initCorpRuntime(
corpContext,
selectedCorp,
jsonMode: options.jsonMode ?? false,
outputOptions: options.outputOptions,
};
}
+24 -2
View File
@@ -1,4 +1,4 @@
import type { CliParsedArgs } from "./types.js";
import type { CliParsedArgs, OutputOptions } from "./types.js";
const KNOWN_BOOLEAN_FLAGS = new Set([
"raw",
@@ -19,6 +19,10 @@ const KNOWN_BOOLEAN_FLAGS = new Set([
"local",
"workspace",
"external",
"full",
"allow-full",
"allowFull",
"summary",
]);
export function parseArgs(rawArgs: string[]): CliParsedArgs {
@@ -61,7 +65,17 @@ export function parseArgs(rawArgs: string[]): CliParsedArgs {
if (flag === "h") options.help = true;
else if (flag === "j") options.json = 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;
}
@@ -121,3 +135,11 @@ export function numberOption(
}
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"]),
};
}
+108
View File
@@ -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
View File
@@ -1,7 +1,41 @@
import { writeFileSync } from "node:fs";
import { VERSION } from "../version.js";
import type { OutputOptions } from "./types.js";
export function printJson(data: unknown): string {
return JSON.stringify(data, null, 2);
export const DEFAULT_OUTPUT_BYTES_LIMIT = 200_000;
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 {
@@ -83,7 +117,7 @@ export function printHelp(): string {
核心命令域:
auth 认证与凭证管理 (login, status, refresh, import, accounts)
corps 多企业租户管理 (list, switch, current)
config 全局运行模式 (show, mode <stateful|stateless>, set)
config 全局运行模式与路径诊断 (show, paths, mode <stateful|stateless>, set)
workflow 工作流管理 (list, get, find, toggle)
bill 单据与费用明细检索 (list, get <单号|ID>, schema)
platform 自建应用管理 (list)
@@ -95,21 +129,25 @@ export function printHelp(): string {
version 查看版本信息
全局选项:
--corp=<id> 临时指定操作的企业/身份 ID (覆盖默认企业)
--json, -j 以 JSON 结构化输出结果 (适合脚本/流水线集成)
--stateless 单次强制以无状态模式执行
--stateful 单次强制以有状态模式执行
--help, -h 查看帮助信息
--corp=<id> 临时指定操作的企业/身份 ID (覆盖默认企业)
--json, -j 以 JSON 结构化输出结果 (适合脚本/流水线集成)
--output-file, -o 将大体积结果直接转储至本地文件并输出精简摘要
--full 允许全量输出大体积 JSON (绕过 200KB 防爆拦截)
--stateless 单次强制以无状态模式执行
--stateful 单次强制以有状态模式执行
--help, -h 查看帮助信息
常用示例:
hose-use auth login --phone=177... --password=... # 纯 API 账密自动登录
hose-use auth status # 查看当前登录状态与活跃企业
hose-use config paths # 查看多级企业配置目录链
hose-use config mode stateless # 切换为无状态模式 (防止 Agent 误操作)
hose-use corps list # 列出名下所有企业
hose-use corps switch uzU7pcWfScck00 # 切换工作企业
hose-use workflow list # 汇总查看全部工作流
hose-use workflow find --task=code-js2 # 搜索包含自定义脚本的工作流
hose-use bill list # 查看当前企业单据与报销列表
hose-use bill list --json -o /tmp/bills.json # 导出单据报文到本地磁盘并防爆
hose-use bill get n0GMIM0dkQmKbS # 根据单号精准查询单据结构化详情
hose-use probe # 诊断当前企业鉴权连通性
hose-use skill install # 安装 Agent 技能到用户目录
+7 -5
View File
@@ -1,6 +1,6 @@
import { VERSION } from "../version.js";
import { parseArgs, stringOption, booleanOption } from "./parser.js";
import { printHelp, printJson } from "./printer.js";
import { parseArgs, stringOption, booleanOption, outputOptions } from "./parser.js";
import { printHelp, printJson, redactSensitiveText } from "./printer.js";
import { initCorpRuntime } from "./helpers.js";
import { handleAuthCommand } from "./commands/auth.js";
import { handleCorpsCommand } from "./commands/corps.js";
@@ -50,8 +50,8 @@ async function runCliOnce(
const extraStdout = stdoutChunks.length ? `${stdoutChunks.join("\n")}\n` : "";
const extraStderr = stderrChunks.length ? `${stderrChunks.join("\n")}\n` : "";
return {
stdout: extraStdout + (result.stdout || ""),
stderr: extraStderr + (result.stderr || ""),
stdout: redactSensitiveText(extraStdout + (result.stdout || "")),
stderr: redactSensitiveText(extraStderr + (result.stderr || "")),
exitCode: result.exitCode,
};
} finally {
@@ -78,12 +78,14 @@ async function dispatchCli(
const corpIdOption = stringOption(parsed.options, ["corp", "c"]);
const statelessOption = booleanOption(parsed.options, ["stateless"]);
const statefulOption = booleanOption(parsed.options, ["stateful"]);
const outputOpts = outputOptions(parsed.options);
const runtime = initCorpRuntime({
corpId: corpIdOption,
stateless: statelessOption,
stateful: statefulOption,
jsonMode,
outputOptions: outputOpts,
});
try {
@@ -141,7 +143,7 @@ async function dispatchCli(
};
}
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
const errorMsg = redactSensitiveText(error instanceof Error ? error.message : String(error));
if (jsonMode) {
return {
stdout: printJson({ error: true, message: errorMsg }),
+7
View File
@@ -21,8 +21,15 @@ export interface CliResult {
exitCode: number;
}
export interface OutputOptions {
allowFull?: boolean;
outputFile?: string;
summary?: boolean;
}
export interface CliRuntime {
corpContext: CorpContext;
selectedCorp: CorpConfig | null;
jsonMode: boolean;
outputOptions?: OutputOptions;
}
+2
View File
@@ -16,6 +16,7 @@ import { authTools } from "./core/auth/tools.js";
import { platformTools } from "./domains/platform/tools.js";
import { billTools } from "./domains/bill/tools.js";
import { runCli } from "./cli/runner.js";
import { redactSensitiveText } from "./cli/printer.js";
import { VERSION } from "./version.js";
import type { CliResult } from "./cli/types.js";
@@ -114,6 +115,7 @@ export function cliResult(result: CliResult): {
} {
const isError = result.exitCode !== 0;
let text = isError ? (result.stderr || result.stdout || "Command failed") : (result.stdout || result.stderr || "Success");
text = redactSensitiveText(text);
return {
content: [
{
+1 -1
View File
@@ -1 +1 @@
export const VERSION = "0.4.1";
export const VERSION = "0.4.2";