From 3f015d8e2250b855a99188a4ffa59433390f950c Mon Sep 17 00:00:00 2001 From: yunyingk Date: Tue, 8 Sep 2026 12:08:12 +0800 Subject: [PATCH] fix(auth): guard temporary token refresh and translate bill flow --- skills/hose-use/references/auth.md | 6 ++++ src/cli/commands/auth.ts | 4 +++ src/cli/commands/bill.ts | 3 +- src/cli/commands/corps.ts | 6 +++- src/core/auth/ekb.test.ts | 52 ++++++++++++++++++++++++++++++ src/core/auth/ekb.ts | 22 +++++++++---- src/core/auth/login.ts | 42 +++++++++++++++++++++--- src/core/http/factory.ts | 7 +++- src/domains/bill/bill.test.ts | 33 +++++++++++++++++++ src/domains/bill/tools.ts | 35 ++++++++++++++++---- src/domains/bill/translator.ts | 46 ++++++++++++++++++++++++++ src/domains/bill/types.ts | 2 ++ 12 files changed, 238 insertions(+), 20 deletions(-) create mode 100644 src/core/auth/ekb.test.ts diff --git a/skills/hose-use/references/auth.md b/skills/hose-use/references/auth.md index bc2d0b6..74cb2b3 100644 --- a/skills/hose-use/references/auth.md +++ b/skills/hose-use/references/auth.md @@ -49,11 +49,17 @@ hose-use corps add-link "https://wx2.ekuaibao.com/web/thirdparty.html?accessToke # 可选附加别名与覆盖参数 hose-use corps add-link "" --name="客户企业别名" --overwrite + +# 未提供服务端 expTime 时,可显式指定本地有效期 +hose-use corps add-link "" --ttl 3d +hose-use corps add-link "" --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 diff --git a/src/cli/commands/auth.ts b/src/cli/commands/auth.ts index 2896f83..341adea 100644 --- a/src/cli/commands/auth.ts +++ b/src/cli/commands/auth.ts @@ -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, }); diff --git a/src/cli/commands/bill.ts b/src/cli/commands/bill.ts index 57644ae..9161394 100644 --- a/src/cli/commands/bill.ts +++ b/src/cli/commands/bill.ts @@ -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 || "-", diff --git a/src/cli/commands/corps.ts b/src/cli/commands/corps.ts index d9001f9..341ef56 100644 --- a/src/cli/commands/corps.ts +++ b/src/cli/commands/corps.ts @@ -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 [--name <企业别名>] [--overwrite]\n", + stderr: "错误:必须提供协助/免密链接 URL!用法: hose-use corps add-link [--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) { diff --git a/src/core/auth/ekb.test.ts b/src/core/auth/ekb.test.ts new file mode 100644 index 0000000..a3d3e80 --- /dev/null +++ b/src/core/auth/ekb.test.ts @@ -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 { + 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(); + }); +}); diff --git a/src/core/auth/ekb.ts b/src/core/auth/ekb.ts index c105158..bb8fc53 100644 --- a/src/core/auth/ekb.ts +++ b/src/core/auth/ekb.ts @@ -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 { return { @@ -11,20 +12,29 @@ export function getEkbHeaders(corp: CorpConfig): Record { } 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 重新导入"), + }), }); } diff --git a/src/core/auth/login.ts b/src/core/auth/login.ts index 85fe886..4e27168 100644 --- a/src/core/auth/login.ts +++ b/src/core/auth/login.ts @@ -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 = { @@ -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 { - const account = corp.accountId ? getAccount(corp.accountId) : getActiveAccount(); + if (!canRefreshCorpAccessToken(corp)) return false; + + const account = getAccount(corp.accountId!); if (!account?.cloudAuthToken) return false; try { diff --git a/src/core/http/factory.ts b/src/core/http/factory.ts index 335e821..38a77a6 100644 --- a/src/core/http/factory.ts +++ b/src/core/http/factory.ts @@ -9,6 +9,8 @@ export interface CreateAuthClientOptions { prefixUrl: string; getHeaders: () => Promise> | Record; onUnauthorized?: () => Promise | 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; }, ], diff --git a/src/domains/bill/bill.test.ts b/src/domains/bill/bill.test.ts index a908337..34caa11 100644 --- a/src/domains/bill/bill.test.ts +++ b/src/domains/bill/bill.test.ts @@ -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 = { diff --git a/src/domains/bill/tools.ts b/src/domains/bill/tools.ts index 223f16f..a0bc763 100644 --- a/src/domains/bill/tools.ts +++ b/src/domains/bill/tools.ts @@ -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 => 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, diff --git a/src/domains/bill/translator.ts b/src/domains/bill/translator.ts index 1a65e83..06b6bf6 100644 --- a/src/domains/bill/translator.ts +++ b/src/domains/bill/translator.ts @@ -130,6 +130,52 @@ export interface TranslatorOptions { datalinkCardMap?: Map; } +const BILL_FLOW_ACTION_LABELS: Record = { + "freeflow.submit": "提交送审", + "freeflow.agree": "审批同意", + "freeflow.autoAgree": "自动同意", + "freeflow.reject": "审批驳回", + "freeflow.print": "打印单据", + "freeflow.retract": "单据撤回", + "freeflow.addnode": "加签/转交", + "freeflow.comment": "发表评论", +}; + +const BILL_FLOW_STATE_LABELS: Record = { + 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( diff --git a/src/domains/bill/types.ts b/src/domains/bill/types.ts index aa126dc..f36c6ad 100644 --- a/src/domains/bill/types.ts +++ b/src/domains/bill/types.ts @@ -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;