Compare commits

...
3 Commits
Author SHA1 Message Date
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
19 changed files with 248 additions and 30 deletions

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "hose-use",
"version": "0.7.4",
"version": "0.7.5",
"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.7.5)
合思/易快报(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.7.5",
"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.7.5
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.7.5",
"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.7.5: 合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号 API 登录、租户切换、单据检索与审批动作、工作流跨域扫描、内置 HTTP 交互文档与常驻守护进程。"
metadata:
version: 0.7.4
short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.7.4)
version: 0.7.5
short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.7.5)
---
# hose-use (v0.7.4)
# hose-use (v0.7.5)
在具备 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) {
+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 {
+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;
},
],
+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 = {
+28 -7
View File
@@ -23,7 +23,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,
@@ -875,17 +880,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 +921,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 +934,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 +1443,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;
+1 -1
View File
@@ -1 +1 @@
export const VERSION = "0.7.4";
export const VERSION = "0.7.5";