diff --git a/README.md b/README.md index cfe9ee6..ca5d535 100644 --- a/README.md +++ b/README.md @@ -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 --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 # 查看企业全部单据实体与数据模型字典 diff --git a/openapi/openapi.yaml b/openapi/openapi.yaml index bd7aea0..10b4b8f 100644 --- a/openapi/openapi.yaml +++ b/openapi/openapi.yaml @@ -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: diff --git a/package.json b/package.json index 9d4aa28..dae89c6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hose-use", - "version": "0.4.1", + "version": "0.4.2", "module": "src/server.ts", "type": "module", "bin": { diff --git a/skills/hose-use/SKILL.md b/skills/hose-use/SKILL.md index f521275..55fc3cf 100644 --- a/skills/hose-use/SKILL.md +++ b/skills/hose-use/SKILL.md @@ -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 diff --git a/src/cli/commands/bill.ts b/src/cli/commands/bill.ts index d750f37..c8483d5 100644 --- a/src/cli/commands/bill.ts +++ b/src/cli/commands/bill.ts @@ -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, }; diff --git a/src/cli/commands/corps.ts b/src/cli/commands/corps.ts index f301ebb..4fbd2fb 100644 --- a/src/cli/commands/corps.ts +++ b/src/cli/commands/corps.ts @@ -29,10 +29,13 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise = { diff --git a/src/cli/commands/platform.ts b/src/cli/commands/platform.ts index a3c4a78..a0b10bd 100644 --- a/src/cli/commands/platform.ts +++ b/src/cli/commands/platform.ts @@ -36,7 +36,7 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise): OutputOptions { + return { + allowFull: booleanOption(options, ["full", "allow-full", "allowFull"]), + outputFile: stringOption(options, ["output-file", "outputFile", "o"]), + summary: booleanOption(options, ["summary"]), + }; +} diff --git a/src/cli/printer.test.ts b/src/cli/printer.test.ts new file mode 100644 index 0000000..b3828bb --- /dev/null +++ b/src/cli/printer.test.ts @@ -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="); + expect(redacted).toContain("returnToken="); + 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 "); + }); + + 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": ""'); + expect(redacted).toContain('"appSecurity": ""'); + }); + }); + + 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"); + }); + }); +}); diff --git a/src/cli/printer.ts b/src/cli/printer.ts index d60bb48..d85d98f 100644 --- a/src/cli/printer.ts +++ b/src/cli/printer.ts @@ -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") + .replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi, "$1") + .replace(/((?:password|passwd|secret|appSecurity)["']?\s*[:=]\s*["']?)[^"',\s}]+/gi, "$1"); +} + +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 , set) + config 全局运行模式与路径诊断 (show, paths, mode , set) workflow 工作流管理 (list, get, find, toggle) bill 单据与费用明细检索 (list, get <单号|ID>, schema) platform 自建应用管理 (list) @@ -95,21 +129,25 @@ export function printHelp(): string { version 查看版本信息 全局选项: - --corp= 临时指定操作的企业/身份 ID (覆盖默认企业) - --json, -j 以 JSON 结构化输出结果 (适合脚本/流水线集成) - --stateless 单次强制以无状态模式执行 - --stateful 单次强制以有状态模式执行 - --help, -h 查看帮助信息 + --corp= 临时指定操作的企业/身份 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 技能到用户目录 diff --git a/src/cli/runner.ts b/src/cli/runner.ts index 89c1b5e..8aa443f 100644 --- a/src/cli/runner.ts +++ b/src/cli/runner.ts @@ -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 }), diff --git a/src/cli/types.ts b/src/cli/types.ts index eaa05d1..75b4307 100644 --- a/src/cli/types.ts +++ b/src/cli/types.ts @@ -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; } diff --git a/src/server.ts b/src/server.ts index 1e496d0..a154e07 100644 --- a/src/server.ts +++ b/src/server.ts @@ -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: [ { diff --git a/src/version.ts b/src/version.ts index de04e98..2391cca 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1 +1 @@ -export const VERSION = "0.4.1"; +export const VERSION = "0.4.2";