Merge pull request #89 from yunyingk/feat/openapi-persistent-auth
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
feat(auth): support OpenAPI persistent credentials, auto-refresh, and Web login link generation (v0.8.10)
This commit is contained in:
27 files changed
+2994
-583
No files matched your search
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.8.9",
|
||||
"version": "0.8.10",
|
||||
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# hose-use (v0.8.9)
|
||||
# hose-use (v0.8.10)
|
||||
|
||||
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
|
||||
|
||||
|
||||
Vendored
+501
-455
File diff suppressed because it is too large.
Load diff
Vendored
+1
-1
@@ -2,7 +2,7 @@
|
||||
"openapi": "3.1.0",
|
||||
"info": {
|
||||
"title": "hose-use API & MCP Tools Specification",
|
||||
"version": "0.8.9",
|
||||
"version": "0.8.10",
|
||||
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
|
||||
},
|
||||
"servers": [
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
title: hose-use API & MCP Tools Specification
|
||||
version: 0.8.9
|
||||
version: 0.8.10
|
||||
description: >-
|
||||
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
|
||||
servers:
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.8.9",
|
||||
"version": "0.8.10",
|
||||
"module": "src/server.ts",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
name: hose-use
|
||||
description: "合思/易快报(Ekuaibao)企业级 SaaS 一站式能力:hose-use CLI/SDK 多账号登录、租户切换、单据检索与审批动作、自建应用与工作流扫描、密钥与应用中心、常驻守护进程与 HTTP 文档/OpenAPI,以及工作流 MVEL 代码节点脚本生成调试、节点批量开通。用于一切合思/易快报相关请求。"
|
||||
metadata:
|
||||
version: 0.8.9
|
||||
version: 0.8.10
|
||||
short-description: 合思/易快报 企业级 CLI 与工作流 skill 套件(含 MVEL 代码节点)
|
||||
---
|
||||
|
||||
# hose-use (v0.8.9)
|
||||
# hose-use (v0.8.10)
|
||||
|
||||
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
|
||||
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
|
||||
@@ -65,7 +65,9 @@ metadata:
|
||||
| AI PRO 确定性审批仲裁全流程 (核验/仲裁) | `hose-aipro bind`, `hose-aipro review`, `hose-aipro decide` | [references/approval.md](references/approval.md) |
|
||||
| 本地 AI 审批规约与规则增删改查 | `hose-use rule scopes`, `hose-use rule add --dry-run/--yes`, `hose-use rule list` | [references/approval.md](references/approval.md) |
|
||||
| 首次登录 / 账密认证 / Token过期 / 多账号 | `hose-use auth login`, `hose-use auth status`, `hose-use auth refresh` | [references/auth.md](references/auth.md) |
|
||||
| 第三方免密/协助链接一键秒级导入 | `hose-use corps add-link <url>`, `hose-use auth add-link <url>` | [references/auth.md](references/auth.md) |
|
||||
| 生成企业合思 Web 免密登录直达链接 (`thirdparty.html`) | `hose-use corps link [企业ID|名称]`, `hose-use auth hose-link` | [references/auth.md](references/auth.md) |
|
||||
| 第三方免密/协助链接一键导入(自动提取持久化密钥) | `hose-use corps add-link <url> --yes`, `hose-use corps elevate [企业ID] --yes` | [references/auth.md](references/auth.md) |
|
||||
| OpenAPI 密钥持久化接入 / 从链接提取密钥 | `hose-use corps add-persistent`, `hose-use corps extract-keys <url>` | [references/auth.md](references/auth.md) |
|
||||
| 代客协助凭证导入 / 探针连通性诊断 | `hose-use auth import`, `hose-use probe` | [references/auth.md](references/auth.md) |
|
||||
| 企业租户切换 / 查看当前企业 | `hose-use corps list`, `hose-use corps switch <id>` | [references/auth.md](references/auth.md) |
|
||||
| 报销单据检索 / 费用明细下钻 / 中文字典 | `hose-use bill list [--since=7d] [--code=<单号>]`, `hose-use bill get <单号|ID> [--risk]` | [references/bill.md](references/bill.md) |
|
||||
|
||||
@@ -42,24 +42,47 @@ hose-use auth refresh
|
||||
```
|
||||
- 主动调用主站会话刷新接口,续期当前企业凭据的 AccessToken。
|
||||
|
||||
### 第三方免密/协助链接一键导入 (`corps add-link` / `auth add-link`)
|
||||
### 第三方免密/协助链接一键导入与自动提权持久化 (`corps add-link` / `auth add-link`)
|
||||
```bash
|
||||
# 直接粘贴企业微信免密、合思代客或协助 thirdparty.html 链接
|
||||
hose-use corps add-link "https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=...&ekbCorpId=..."
|
||||
# 直接粘贴企业微信免密、合思代客或协助 thirdparty.html 链接(默认自动探测并持久化保存 OpenAPI appKey + appSecurity)
|
||||
hose-use corps add-link "https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=...&ekbCorpId=..." --yes
|
||||
|
||||
# 可选附加别名与覆盖参数
|
||||
hose-use corps add-link "<url>" --name="客户企业别名" --overwrite
|
||||
# 显式强制要求提取 OpenAPI 持久化密钥(多套密钥时可附加 --app-key 或 --force)
|
||||
hose-use corps add-link "<url>" --elevate --force --overwrite --yes
|
||||
|
||||
# 未提供服务端 expTime 时,可显式指定本地有效期
|
||||
hose-use corps add-link "<url>" --ttl 3d
|
||||
hose-use corps add-link "<url>" --expires 3 # 等价于 3 天;--days 3 也可以
|
||||
hose-use corps add-link "<url>" --ttl 3d --yes
|
||||
```
|
||||
- **全自动识别与身份探测**:
|
||||
- **全自动识别与双通道持久化**:
|
||||
- 自动从 URL 提取服务节点 `baseUrl`、集群环境 `cluster`(如 `wx2`、`app`)、`accessToken` 与 `corpId`;
|
||||
- 自动向 `$UNITY` JWT 与主站 Session 反查员工工号 (`staffId`)、员工姓名、绑定手机、企业全称与是否企业管理员,无需手动寻找工号;
|
||||
- 动态自适应多集群环境换票,确保主站单据审批与 EASO 低代码工作流平台权限全绿连通。
|
||||
- 非账号来源(link/browser/assist/curl/manual)不会触发账号换票;Token 失效时提示重新导入链接。
|
||||
- 服务端返回的 expTime 优先;未返回时不再强制套用 2 小时,可使用 `--ttl` / `--expires` 指定有效期。
|
||||
- 自动向 `$UNITY` JWT 与主站 Session 反查员工工号 (`staffId`)、员工姓名、绑定手机、企业全称与是否企业管理员;
|
||||
- **自动提取 OpenAPI 持久化密钥**:导入链接或账密登录时,自动尝试调用 `/api/innerapi/v1/key` 提取企业启用状态的 `appKey + appSecurity` 并写入 `enterprises/<corpId>.json`;
|
||||
- **双通道无感自动续期**:当会话 `accessToken` 过期时,客户端优先尝试用户级主账号 (`cloudAuthToken`) 换票,或自动通过企业级 OpenAPI 持久化密钥调用 `/api/openapi/v1/auth/getAccessToken` + `/api/openapi/v1.1/provisional/getProvisionalAuth` 签发全新会话令牌并落盘,彻底告别临时链接过期失效。
|
||||
|
||||
### 生成企业合思 Web 免密登录直达链接 (`corps link` / `auth hose-link`)
|
||||
```bash
|
||||
# 为已配置企业生成 2 小时有效期的 Web 免密直达链接 (thirdparty.html)
|
||||
hose-use corps link 新转转集团
|
||||
hose-use corps link ID01PH4Q5CJboX --json
|
||||
hose-use auth hose-link --corp=ID01PH4Q5CJboX
|
||||
```
|
||||
- 若企业已配置 OpenAPI `appKey + appSecurity`,直接调用 `getProvisionalAuth` 动态签发全新的 `thirdparty.html` 免密登录链接;
|
||||
- 若企业尚未持久化密钥,会先尝试利用当前有效会话自动提权提取 `appKey + appSecurity`,再签发直达链接。
|
||||
|
||||
### OpenAPI 持久化密钥直接接入与存量提权 (`add-persistent` / `extract-keys` / `elevate`)
|
||||
```bash
|
||||
# 1. 直接使用 appKey + appSecurity 持久化接入企业(自动探测 6 大合思域名与主管理员)
|
||||
hose-use corps add-persistent --app-key=<key> --app-security=<secret> --force --yes
|
||||
|
||||
# 2. 从协助链接中提取查看 OpenAPI 密钥(附加 --save --yes 可直接持久化落盘)
|
||||
hose-use corps extract-keys "<url>"
|
||||
hose-use corps extract-keys "<url>" --save --yes
|
||||
|
||||
# 3. 为本地已配置企业(或 --all 全部企业)提取并持久化保存 OpenAPI 密钥
|
||||
hose-use corps elevate ID01PH4Q5CJboX --yes
|
||||
hose-use corps elevate --all --yes
|
||||
hose-use keys --corp=ID01PH4Q5CJboX --save --yes
|
||||
```
|
||||
|
||||
### 代客协助凭证导入
|
||||
```bash
|
||||
@@ -67,7 +90,8 @@ hose-use auth import \
|
||||
--name="CSM代客" \
|
||||
--corp-id="Cxa3oOtQi2eS$g" \
|
||||
--staff-id="Cxa3oOtQi2eS$g:2HQbkGx2DgnM00" \
|
||||
--token="1361c470-3d7c-4a3a-a1fb-e946aee5723b"
|
||||
--token="1361c470-3d7c-4a3a-a1fb-e946aee5723b" \
|
||||
--yes
|
||||
```
|
||||
- **智能探测机制**:若 `corp-id` 包含 `$UNITY` 或特殊字符,系统会自动探测代客服务会话接口,解析 13 位过期毫秒时间戳并正确建立凭证映射。也可直接传入抓包 cURL 或包含 URL 的文本。
|
||||
|
||||
|
||||
@@ -64,4 +64,20 @@ describe("cli/commands/auth > aliases and subcommands", () => {
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("当前登录与企业状态");
|
||||
});
|
||||
|
||||
it("supports auth sync-seal --dry-run", async () => {
|
||||
const res = await handleAuthCommand(
|
||||
{
|
||||
area: "auth",
|
||||
action: "sync-seal",
|
||||
args: [],
|
||||
options: { "dry-run": true },
|
||||
raw: ["auth", "sync-seal", "--dry-run"],
|
||||
},
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("从 seal-use 同步企业 OpenAPI 持久化密钥");
|
||||
});
|
||||
});
|
||||
+119
-6
@@ -1,13 +1,16 @@
|
||||
import {
|
||||
canRefreshCorpAccessToken,
|
||||
fullPasswordLogin,
|
||||
fullSmsLogin,
|
||||
fullBrowserSyncLogin,
|
||||
hasOpenApiPersistentCredentials,
|
||||
sendSmsVerificationCode,
|
||||
importCredentials,
|
||||
importF12Credentials,
|
||||
importFromLink,
|
||||
parseHeadersOrCurl,
|
||||
refreshAccountCorporations,
|
||||
refreshSingleCorpAccessToken,
|
||||
} from "../../core/auth/login.js";
|
||||
import {
|
||||
listAccounts,
|
||||
@@ -19,8 +22,20 @@ import { stringOption, booleanOption } from "../parser.js";
|
||||
import { printJson, printKeyValue, printTable, formatSourceLabel, formatExpiresAt } from "../printer.js";
|
||||
import { prompt } from "../helpers.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
|
||||
import {
|
||||
handleAddPersistent,
|
||||
handleElevateCorp,
|
||||
handleExtractKeys,
|
||||
handleGenerateCorpLink,
|
||||
handleSyncFromSeal,
|
||||
resolveTargetCorpByArgOrContext,
|
||||
} from "./corps.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
|
||||
function isHttpUrl(val?: string): boolean {
|
||||
return Boolean(val && /^https?:\/\//i.test(val.trim()));
|
||||
}
|
||||
|
||||
export async function handleAuthCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
@@ -41,9 +56,36 @@ export async function handleAuthCommand(
|
||||
case "add":
|
||||
return handleImport(parsed, runtime);
|
||||
case "add-link":
|
||||
case "link":
|
||||
case "import-link":
|
||||
return handleAddLink(parsed, runtime);
|
||||
case "link": {
|
||||
const maybeUrl = parsed.args[0] || stringOption(parsed.options, ["url", "link"]);
|
||||
if (isHttpUrl(maybeUrl)) {
|
||||
return handleAddLink(parsed, runtime);
|
||||
}
|
||||
return handleGenerateCorpLink(parsed, runtime);
|
||||
}
|
||||
case "hose-link":
|
||||
case "auth-link":
|
||||
case "login-link":
|
||||
return handleGenerateCorpLink(parsed, runtime);
|
||||
case "add-persistent":
|
||||
case "add-hose-persistent":
|
||||
case "add-openapi":
|
||||
case "add-hose":
|
||||
return handleAddPersistent(parsed, runtime);
|
||||
case "extract-keys":
|
||||
case "extract-key":
|
||||
case "hose-extract-keys":
|
||||
case "extract-hose-keys":
|
||||
return handleExtractKeys(parsed, runtime);
|
||||
case "elevate":
|
||||
case "elevate-hose":
|
||||
return handleElevateCorp(parsed, runtime);
|
||||
case "sync-seal":
|
||||
case "sync-from-seal":
|
||||
case "import-seal":
|
||||
return handleSyncFromSeal(parsed, runtime);
|
||||
case "accounts":
|
||||
case "list":
|
||||
case "account":
|
||||
@@ -56,7 +98,7 @@ export async function handleAuthCommand(
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 auth 子命令: ${action}。支持: login, status, refresh, import, add-link, accounts, switch-account\n`,
|
||||
stderr: `未知 auth 子命令: ${action}。支持: login, status, refresh, import, link, add-link, add-persistent, extract-keys, elevate, sync-seal, accounts, switch-account\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
@@ -175,6 +217,9 @@ async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
}
|
||||
}
|
||||
|
||||
const hasOpenApi = hasOpenApiPersistentCredentials(currentCorp);
|
||||
const isPersistent = canRefreshCorpAccessToken(currentCorp);
|
||||
|
||||
const statusObj = {
|
||||
activeAccount: activeAccount?.accountId || null,
|
||||
currentCorp: currentCorp
|
||||
@@ -184,6 +229,8 @@ async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
staffId: currentCorp.credentials.staffId,
|
||||
source: currentCorp.source,
|
||||
accountId: currentCorp.accountId,
|
||||
persistent: isPersistent,
|
||||
hasOpenApiKey: hasOpenApi,
|
||||
tokenValid: sessionValid,
|
||||
}
|
||||
: null,
|
||||
@@ -199,9 +246,14 @@ async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
"当前激活企业": currentCorp ? `${currentCorp.name} (${currentCorp.id})` : "未配置",
|
||||
"当前员工工号": currentCorp?.credentials.staffId || "-",
|
||||
"员工真实姓名": currentCorp?.staffName || currentCorp?.session?.staffName || "-",
|
||||
"凭证来源类型": formatSourceLabel(currentCorp?.source),
|
||||
"凭证来源类型": formatSourceLabel(currentCorp?.source, hasOpenApi),
|
||||
"持久化状态": isPersistent
|
||||
? hasOpenApi
|
||||
? `✅ OpenAPI 持久化密钥 (${currentCorp?.credentials.appKey})`
|
||||
: "✅ 统一认证主账号自动换票"
|
||||
: "⚪ 短期会话",
|
||||
"Token 有效性": sessionValid ? "✅ 有效 (已通过 Session 验证)" : "❌ 无效或未连接",
|
||||
"Token 过期时间": formatExpiresAt(currentCorp?.auth?.expiresAt || currentCorp?.session?.expTime),
|
||||
"Token 过期时间": formatExpiresAt(currentCorp?.auth?.expiresAt || currentCorp?.session?.expTime, isPersistent),
|
||||
};
|
||||
|
||||
if (currentCorp?.session) {
|
||||
@@ -239,6 +291,53 @@ async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
|
||||
async function handleRefresh(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const accountId = stringOption(parsed.options, ["account", "a"]);
|
||||
const explicitCorp = parsed.args[0] || stringOption(parsed.options, ["corp"]);
|
||||
const targetCorp = explicitCorp
|
||||
? resolveTargetCorpByArgOrContext(explicitCorp, runtime)
|
||||
: !accountId && !getActiveAccount() && runtime.selectedCorp && canRefreshCorpAccessToken(runtime.selectedCorp)
|
||||
? runtime.selectedCorp
|
||||
: null;
|
||||
|
||||
if (targetCorp && !accountId) {
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "刷新单企业凭证", `${targetCorp.name} (${targetCorp.id})`, {
|
||||
corpId: targetCorp.id,
|
||||
hasOpenApiKey: hasOpenApiPersistentCredentials(targetCorp),
|
||||
});
|
||||
}
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"刷新单企业凭证",
|
||||
`hose-use auth refresh ${targetCorp.id} --yes`
|
||||
);
|
||||
const newToken = await refreshSingleCorpAccessToken(targetCorp);
|
||||
if (!newToken) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `刷新企业 [${targetCorp.name} (${targetCorp.id})] AccessToken 失败:缺少可用的账号凭证或 OpenAPI 持久化密钥\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({
|
||||
corpId: targetCorp.id,
|
||||
corpName: targetCorp.name,
|
||||
refreshed: true,
|
||||
expiresAt: targetCorp.auth?.expiresAt,
|
||||
}),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: `[SUCCESS] 成功刷新企业 [${targetCorp.name} (${targetCorp.id})] 的 AccessToken!\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "刷新账号下企业凭证", accountId || "当前账号", { saveAll: true });
|
||||
}
|
||||
@@ -265,10 +364,16 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
const overwrite = booleanOption(parsed.options, ["overwrite", "force", "f"], false);
|
||||
const ttl = stringOption(parsed.options, ["ttl"]);
|
||||
const expires = stringOption(parsed.options, ["expires", "days"]);
|
||||
const elevate = booleanOption(parsed.options, ["elevate", "elevate-hose", "as-hose"], false);
|
||||
const noElevate = booleanOption(parsed.options, ["no-elevate"], false);
|
||||
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
|
||||
const keyId = stringOption(parsed.options, ["key-id", "keyId"]);
|
||||
const force = booleanOption(parsed.options, ["force", "f"], false);
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "导入并保存企业凭证", corpId || "待解析企业", {
|
||||
source: raw ? "captured-input" : "manual-input",
|
||||
elevate: elevate ? "required" : noElevate ? "disabled" : "auto-best-effort",
|
||||
overwrite,
|
||||
ttl: ttl || null,
|
||||
expires: expires || null,
|
||||
@@ -307,6 +412,11 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
overwrite,
|
||||
ttl,
|
||||
expires,
|
||||
appKey,
|
||||
keyId,
|
||||
elevate: elevate ? true : noElevate ? false : undefined,
|
||||
autoElevate: !noElevate,
|
||||
force,
|
||||
source: raw && (raw.startsWith("http://") || raw.startsWith("https://")) ? "link" : undefined,
|
||||
});
|
||||
|
||||
@@ -314,6 +424,8 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
return { stdout: printJson(imported, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const hasOpenApi = hasOpenApiPersistentCredentials(imported);
|
||||
|
||||
const summaryPairs: Record<string, unknown> = {
|
||||
"企业名称": imported.name,
|
||||
"企业 ID": imported.id,
|
||||
@@ -322,9 +434,10 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
"员工姓名": imported.staffName || imported.session?.staffName || "-",
|
||||
"手机号码": imported.session?.cellphone || "-",
|
||||
"是否管理": imported.session?.isAdmin ? "是" : "否",
|
||||
"凭证来源": formatSourceLabel(imported.source),
|
||||
"凭证来源": formatSourceLabel(imported.source, hasOpenApi),
|
||||
"持久化密钥": hasOpenApi ? `✅ 已自动提权持久化 (appKey: ${imported.credentials.appKey})` : "⚪ 未提取到 OpenAPI 密钥 (短期会话)",
|
||||
"服务节点": imported.baseUrl,
|
||||
"过期时间": formatExpiresAt(imported.auth?.expiresAt || imported.session?.expTime),
|
||||
"过期时间": formatExpiresAt(imported.auth?.expiresAt || imported.session?.expTime, hasOpenApi),
|
||||
"保存路径": `enterprises/${imported.id}.json`,
|
||||
};
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { getActiveAccount } from "../../core/auth/account-store.js";
|
||||
import { canRefreshCorpAccessToken, hasOpenApiPersistentCredentials } from "../../core/auth/login.js";
|
||||
import {
|
||||
resolveGlobalConfigFile,
|
||||
resolvePrimaryEnterprisesDir,
|
||||
@@ -47,8 +48,9 @@ export async function handleContextCommand(
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const validCorps = allCorps.filter((c) => !c.expiresAt || c.expiresAt > now);
|
||||
const expiredCorps = allCorps.filter((c) => c.expiresAt && c.expiresAt <= now);
|
||||
const validCorps = allCorps.filter((c) => c.persistent || !c.expiresAt || c.expiresAt > now);
|
||||
const expiredCorps = allCorps.filter((c) => !c.persistent && c.expiresAt && c.expiresAt <= now);
|
||||
const currentPersistent = currentCorp ? canRefreshCorpAccessToken(currentCorp) : false;
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
@@ -76,11 +78,13 @@ export async function handleContextCommand(
|
||||
staffId: currentCorp.credentials?.staffId || currentCorp.staffId,
|
||||
userName: currentCorp.staffName || currentCorp.session?.staffName || null,
|
||||
source: currentCorp.source,
|
||||
persistent: currentPersistent,
|
||||
expiresAt: currentCorp.auth?.expiresAt || currentCorp.session?.expTime,
|
||||
expired:
|
||||
(currentCorp.auth?.expiresAt || currentCorp.session?.expTime)
|
||||
? (currentCorp.auth?.expiresAt || currentCorp.session?.expTime)! <= now
|
||||
: false,
|
||||
expired: currentPersistent
|
||||
? false
|
||||
: (currentCorp.auth?.expiresAt || currentCorp.session?.expTime)
|
||||
? (currentCorp.auth?.expiresAt || currentCorp.session?.expTime)! <= now
|
||||
: false,
|
||||
baseUrl: currentCorp.baseUrl,
|
||||
accountId: currentCorp.accountId || null,
|
||||
}
|
||||
@@ -130,8 +134,8 @@ export async function handleContextCommand(
|
||||
` 当前激活企业 : ${currentCorp ? `${currentCorp.name} (${currentCorp.id})` : "⚠️ 未激活任何企业"}`,
|
||||
` 当前操作员工 : ${corpStaffId}`,
|
||||
` 员工真实姓名 : ${corpStaffName}`,
|
||||
` 凭证来源类型 : ${currentCorp ? formatSourceLabel(currentCorp.source) : "-"}`,
|
||||
` 凭证有效状态 : ${currentCorp ? formatExpiresAt(corpExpiresAt) : "-"}`,
|
||||
` 凭证来源类型 : ${currentCorp ? formatSourceLabel(currentCorp.source, hasOpenApiPersistentCredentials(currentCorp)) : "-"}`,
|
||||
` 凭证有效状态 : ${currentCorp ? formatExpiresAt(corpExpiresAt, currentPersistent) : "-"}`,
|
||||
` 主站 BaseURL : ${currentCorp?.baseUrl || "-"}`,
|
||||
` 已配置企业总数: ${allCorps.length} 家 (有效: ${validCorps.length} 家, 已过期: ${expiredCorps.length} 家)`,
|
||||
` AI PRO 规约库 : ${scopesStr}`,
|
||||
|
||||
@@ -315,4 +315,52 @@ describe("cli/commands/corps > handleCorpsCommand search & aliases", () => {
|
||||
expect(res.stdout).toContain("search <关键词>");
|
||||
expect(res.stdout).toContain("find");
|
||||
});
|
||||
|
||||
it("generates login link via corps link [corp] with preserveSensitiveStdout=true", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = (async () =>
|
||||
new Response(JSON.stringify({ items: [] }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
})) as unknown as typeof fetch;
|
||||
|
||||
try {
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "link",
|
||||
args: ["corpAlpha"],
|
||||
options: {},
|
||||
raw: ["corps", "link", "corpAlpha"],
|
||||
},
|
||||
searchRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.preserveSensitiveStdout).toBe(true);
|
||||
expect(res.stdout).toContain("thirdparty.html?accessToken=token-alpha&ekbCorpId=alphaPhysicalId");
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
it("supports corps add-persistent --dry-run", async () => {
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "add-persistent",
|
||||
args: [],
|
||||
options: {
|
||||
"app-key": "key-1",
|
||||
"app-security": "sec-1",
|
||||
"dry-run": true,
|
||||
},
|
||||
raw: ["corps", "add-persistent", "--app-key=key-1", "--app-security=sec-1", "--dry-run"],
|
||||
},
|
||||
searchRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("通过 OpenAPI 持久化密钥接入企业");
|
||||
});
|
||||
});
|
||||
+626
-13
@@ -1,8 +1,22 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { importFromLink } from "../../core/auth/login.js";
|
||||
import {
|
||||
canRefreshCorpAccessToken,
|
||||
elevateCorpWithOpenApiKey,
|
||||
extractOpenApiKeysFromLink,
|
||||
fetchHoseRoleDefGroups,
|
||||
getCorpProvisionalAuthLink,
|
||||
hasOpenApiPersistentCredentials,
|
||||
importFromLink,
|
||||
listHoseStaffsByOpenApi,
|
||||
maskOpenApiSecurity,
|
||||
onboardHosePersistent,
|
||||
probeHoseDomain,
|
||||
syncOpenApiFromSealUse,
|
||||
} from "../../core/auth/login.js";
|
||||
import { resolveWritableEnterprisesDir } from "../../core/config/loader.js";
|
||||
import { stringOption, booleanOption } from "../parser.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import { stringOption, booleanOption, numberOption } from "../parser.js";
|
||||
import { prompt } from "../helpers.js";
|
||||
import { printJson, printKeyValue, printTable, formatSourceLabel, formatExpiresAt } from "../printer.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
|
||||
@@ -17,6 +31,34 @@ const FIELD_LABEL_MAP: Record<string, string> = {
|
||||
accountId: "所属账号",
|
||||
};
|
||||
|
||||
function isHttpUrl(val?: string): boolean {
|
||||
return Boolean(val && /^https?:\/\//i.test(val.trim()));
|
||||
}
|
||||
|
||||
export function resolveTargetCorpByArgOrContext(
|
||||
targetArg: string | undefined,
|
||||
runtime: CliRuntime
|
||||
): CorpConfig | null {
|
||||
if (targetArg && !isHttpUrl(targetArg)) {
|
||||
try {
|
||||
return runtime.corpContext.resolve(targetArg);
|
||||
} catch {
|
||||
const allCorps = typeof runtime.corpContext.getAllCorps === "function"
|
||||
? runtime.corpContext.getAllCorps()
|
||||
: [];
|
||||
const kw = targetArg.trim().toLowerCase();
|
||||
const matched = allCorps.find(
|
||||
(c) =>
|
||||
c.id.toLowerCase() === kw ||
|
||||
(c.corpId && c.corpId.toLowerCase() === kw) ||
|
||||
c.name.toLowerCase().includes(kw)
|
||||
);
|
||||
if (matched) return matched;
|
||||
}
|
||||
}
|
||||
return runtime.selectedCorp;
|
||||
}
|
||||
|
||||
export async function handleCorpsCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
@@ -41,15 +83,46 @@ export async function handleCorpsCommand(
|
||||
case "active":
|
||||
return handleCurrent(parsed, runtime);
|
||||
case "add-link":
|
||||
case "link":
|
||||
case "import-link":
|
||||
return handleAddLink(parsed, runtime);
|
||||
case "link": {
|
||||
const maybeUrl = parsed.args[0] || stringOption(parsed.options, ["url", "link"]);
|
||||
if (isHttpUrl(maybeUrl)) {
|
||||
return handleAddLink(parsed, runtime);
|
||||
}
|
||||
return handleGenerateCorpLink(parsed, runtime);
|
||||
}
|
||||
case "hose-link":
|
||||
case "auth-link":
|
||||
case "login-link":
|
||||
return handleGenerateCorpLink(parsed, runtime);
|
||||
case "add-persistent":
|
||||
case "add-hose-persistent":
|
||||
case "add-openapi":
|
||||
case "add-hose":
|
||||
return handleAddPersistent(parsed, runtime);
|
||||
case "extract-keys":
|
||||
case "extract-key":
|
||||
case "hose-extract-keys":
|
||||
case "extract-hose-keys":
|
||||
return handleExtractKeys(parsed, runtime);
|
||||
case "elevate":
|
||||
case "elevate-hose":
|
||||
return handleElevateCorp(parsed, runtime);
|
||||
case "sync-seal":
|
||||
case "sync-from-seal":
|
||||
case "import-seal":
|
||||
return handleSyncFromSeal(parsed, runtime);
|
||||
case "probe-hose":
|
||||
return handleProbeHose(parsed, runtime);
|
||||
case "hose-staffs":
|
||||
return handleHoseStaffs(parsed, runtime);
|
||||
case "help":
|
||||
return handleCorpsHelp();
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 corps 子命令: ${action}。支持: list, search, switch, current, add-link\n`,
|
||||
stderr: `未知 corps 子命令: ${action}。支持: list, search, switch, current, link, add-link, add-persistent, extract-keys, elevate, sync-seal\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
@@ -65,7 +138,12 @@ export function printCorpsHelp(): string {
|
||||
search <关键词> 根据关键词模糊搜索企业(支持 id, name, corpId, staffId, staffName, accountId,别名: find)
|
||||
switch <企业ID> 切换当前激活的工作企业 (别名: use)
|
||||
current 查看当前激活的企业配置与凭证详情
|
||||
add-link <URL> 从第三方协助/免密链接导入企业凭证
|
||||
link [企业ID|名称] 生成企业合思 Web 免密登录直达链接 (别名: hose-link)
|
||||
add-link <URL> 从第三方协助/免密链接导入企业凭证(默认自动探测并持久化 OpenAPI 密钥)
|
||||
add-persistent 通过 OpenAPI 密钥 (appKey + appSecurity) 持久化接入企业 (别名: add-hose-persistent)
|
||||
extract-keys <URL> 从协助链接提取企业 OpenAPI 密钥(附加 --save 可直接持久化保存)
|
||||
elevate [企业ID] 为已登录/已导入的企业提取并持久化保存 OpenAPI 密钥
|
||||
sync-seal [关键词] 从本机 seal-use 配置目录同步企业级 OpenAPI 持久化密钥
|
||||
|
||||
选项:
|
||||
--json, -j 以 JSON 格式输出
|
||||
@@ -76,6 +154,9 @@ export function printCorpsHelp(): string {
|
||||
hose-use corps search 某企业
|
||||
hose-use corps search 17718556446
|
||||
hose-use corps switch ID01MCcOgJl1td
|
||||
hose-use corps link 新转转集团
|
||||
hose-use corps add-link "<url>" --elevate --yes
|
||||
hose-use corps add-persistent --app-key=... --app-security=... --yes
|
||||
`.trim();
|
||||
}
|
||||
|
||||
@@ -116,6 +197,7 @@ async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
baseUrl: c.baseUrl,
|
||||
current: c.id === runtime.selectedCorp?.id,
|
||||
expiresAt: c.auth?.expiresAt || (c.session?.expTime ?? undefined),
|
||||
persistent: canRefreshCorpAccessToken(c),
|
||||
}))
|
||||
: runtime.corpContext.listCorps().map((c) => ({
|
||||
id: c.id,
|
||||
@@ -128,6 +210,7 @@ async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
baseUrl: c.baseUrl,
|
||||
current: c.current || c.id === runtime.selectedCorp?.id,
|
||||
expiresAt: c.expiresAt,
|
||||
persistent: c.persistent,
|
||||
}));
|
||||
|
||||
const matches: Array<typeof normalizedCorps[number] & { matchedFields: string[] }> = [];
|
||||
@@ -177,6 +260,7 @@ async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
baseUrl: m.baseUrl,
|
||||
current: m.current,
|
||||
expiresAt: m.expiresAt,
|
||||
persistent: m.persistent,
|
||||
matchedFields: m.matchedFields,
|
||||
})),
|
||||
},
|
||||
@@ -206,7 +290,7 @@ async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
m.staffName ? (m.matchedFields.includes("staffName") ? `[${m.staffName}]` : m.staffName) : "-",
|
||||
m.accountId ? (m.matchedFields.includes("accountId") ? `[${m.accountId}]` : m.accountId) : "-",
|
||||
matchLabels.map((l) => `命中${l}`).join(", "),
|
||||
formatExpiresAt(m.expiresAt),
|
||||
formatExpiresAt(m.expiresAt, m.persistent),
|
||||
];
|
||||
});
|
||||
|
||||
@@ -249,7 +333,7 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
|
||||
c.name,
|
||||
c.staffId,
|
||||
c.source || "manual",
|
||||
formatExpiresAt(c.expiresAt),
|
||||
formatExpiresAt(c.expiresAt, c.persistent),
|
||||
c.accountId || "-",
|
||||
]);
|
||||
|
||||
@@ -307,13 +391,17 @@ async function handleCurrent(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
return { stdout: printJson(current, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const hasOpenApi = hasOpenApiPersistentCredentials(current);
|
||||
const isPersistent = canRefreshCorpAccessToken(current);
|
||||
|
||||
const pairs: Record<string, unknown> = {
|
||||
"企业 ID": current.id,
|
||||
"企业名称": current.name,
|
||||
"员工工号": current.credentials.staffId,
|
||||
"员工姓名": current.staffName || current.session?.staffName || "-",
|
||||
"凭证来源": formatSourceLabel(current.source),
|
||||
"Token 过期时间": formatExpiresAt(current.auth?.expiresAt || current.session?.expTime),
|
||||
"凭证来源": formatSourceLabel(current.source, hasOpenApi),
|
||||
"持久化状态": isPersistent ? (hasOpenApi ? `✅ 已配置 OpenAPI 持久化密钥 (${current.credentials.appKey})` : "✅ 已绑定统一认证主账号") : "⚪ 短期临时会话",
|
||||
"Token 过期时间": formatExpiresAt(current.auth?.expiresAt || current.session?.expTime, isPersistent),
|
||||
"所属账号": current.accountId || "-",
|
||||
"主站地址": current.baseUrl || "https://app.ekuaibao.com",
|
||||
"适用上下文": "同时作为 hose-use 与 hose-aipro 的统一执行环境",
|
||||
@@ -352,12 +440,84 @@ async function handleCurrent(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleGenerateCorpLink(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const targetArg = parsed.args[0];
|
||||
const targetCorp = resolveTargetCorpByArgOrContext(targetArg, runtime);
|
||||
if (!targetCorp) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未找到目标企业${targetArg ? ` [${targetArg}]` : ""}。请通过 --corp=<id> 或参数指定已配置的企业。\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const expiresIn = numberOption(parsed.options, ["expire", "expires", "ttl"]) ?? 7200;
|
||||
const pageType = stringOption(parsed.options, ["page-type", "pageType"]) || "home";
|
||||
const force = booleanOption(parsed.options, ["force", "refresh", "f"]);
|
||||
|
||||
const linkRes = await getCorpProvisionalAuthLink(targetCorp, {
|
||||
expiresIn,
|
||||
pageType,
|
||||
force,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId: linkRes.corpId,
|
||||
corpName: linkRes.corpName,
|
||||
staffId: linkRes.staffId,
|
||||
...(linkRes.staffName ? { staffName: linkRes.staffName } : {}),
|
||||
link: linkRes.url,
|
||||
expiresAt: linkRes.expiresAt,
|
||||
expiresIn: linkRes.expiresIn,
|
||||
token: linkRes.token,
|
||||
persistent: linkRes.persistent,
|
||||
method: linkRes.method,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
preserveSensitiveStdout: true,
|
||||
};
|
||||
}
|
||||
|
||||
const lines = [
|
||||
`====== 合思企业 Web 免密登录直达链接 ======`,
|
||||
` 企业名称 : ${linkRes.corpName} (${linkRes.corpId})`,
|
||||
` 操作人身份: ${linkRes.staffName ? `${linkRes.staffName} (${linkRes.staffId})` : linkRes.staffId}`,
|
||||
` 签发通道 : ${linkRes.method === "provisional-openapi" ? "OpenAPI 持久化密钥动态签发 (getProvisionalAuth)" : "当前有效会话令牌拼装 (session-token)"}`,
|
||||
` 过期时间 : ${linkRes.expiresAt}`,
|
||||
` 直达链接 :`,
|
||||
` ${linkRes.url}`,
|
||||
``,
|
||||
`Markdown 链接: [打开 ${linkRes.corpName} 合思后台](${linkRes.url})`,
|
||||
];
|
||||
|
||||
return {
|
||||
stdout: `${lines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
preserveSensitiveStdout: true,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
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"]);
|
||||
const elevate = booleanOption(parsed.options, ["elevate", "elevate-hose", "as-hose"], false);
|
||||
const noElevate = booleanOption(parsed.options, ["no-elevate"], false);
|
||||
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
|
||||
const keyId = stringOption(parsed.options, ["key-id", "keyId"]);
|
||||
const force = booleanOption(parsed.options, ["force", "f"], false);
|
||||
|
||||
if (!linkUrl && process.stdin.isTTY && !process.env.CI && process.env.NODE_ENV !== "test") {
|
||||
linkUrl = await prompt("请输入第三方协助/免密登录链接 URL: ");
|
||||
@@ -366,7 +526,7 @@ async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
if (!linkUrl) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "错误:必须提供协助/免密链接 URL!用法: hose-use corps add-link <url> [--name <企业别名>] [--ttl 3d|--expires 3] [--overwrite]\n",
|
||||
stderr: "错误:必须提供协助/免密链接 URL!用法: hose-use corps add-link <url> [--name <企业别名>] [--elevate] [--ttl 3d|--expires 3] [--overwrite]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
@@ -388,6 +548,7 @@ async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
name || (targetCorpId ? `企业 [${targetCorpId}]` : "待解析企业"),
|
||||
{
|
||||
source: "assistance-link",
|
||||
elevate: elevate ? "required" : noElevate ? "disabled" : "auto-best-effort",
|
||||
overwrite,
|
||||
alreadyExists: existsAlready,
|
||||
ttl: ttl || null,
|
||||
@@ -413,14 +574,19 @@ async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
overwrite,
|
||||
ttl,
|
||||
expires,
|
||||
appKey,
|
||||
keyId,
|
||||
elevate: elevate ? true : noElevate ? false : undefined,
|
||||
autoElevate: !noElevate,
|
||||
force,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(corp, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const targetDir = resolveWritableEnterprisesDir();
|
||||
const savedPath = join(targetDir, `${corp.id}.json`);
|
||||
const hasOpenApi = hasOpenApiPersistentCredentials(corp);
|
||||
|
||||
const summaryPairs: Record<string, unknown> = {
|
||||
"企业名称": corp.name,
|
||||
@@ -430,9 +596,10 @@ async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
"员工姓名": corp.staffName || corp.session?.staffName || "-",
|
||||
"手机号码": corp.session?.cellphone || "-",
|
||||
"是否管理": corp.session?.isAdmin ? "是" : "否",
|
||||
"凭证来源": formatSourceLabel(corp.source),
|
||||
"凭证来源": formatSourceLabel(corp.source, hasOpenApi),
|
||||
"持久化密钥": hasOpenApi ? `✅ 已自动提权持久化 (appKey: ${corp.credentials.appKey})` : "⚪ 未提取到 OpenAPI 密钥 (短期会话)",
|
||||
"服务节点": corp.baseUrl,
|
||||
"过期时间": formatExpiresAt(corp.auth?.expiresAt || corp.session?.expTime),
|
||||
"过期时间": formatExpiresAt(corp.auth?.expiresAt || corp.session?.expTime, hasOpenApi),
|
||||
"保存路径": savedPath,
|
||||
};
|
||||
|
||||
@@ -461,3 +628,449 @@ async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function handleAddPersistent(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
let jsonPayload: Record<string, unknown> = {};
|
||||
const rawJsonArg = stringOption(parsed.options, ["data"]) || (parsed.args[0]?.trim().startsWith("{") ? parsed.args[0] : undefined);
|
||||
if (rawJsonArg) {
|
||||
try {
|
||||
jsonPayload = JSON.parse(rawJsonArg);
|
||||
} catch {
|
||||
return { stdout: "", stderr: "错误:提供的 JSON 参数无法解析\n", exitCode: 1 };
|
||||
}
|
||||
}
|
||||
|
||||
const appKey =
|
||||
stringOption(parsed.options, ["app-key", "appKey", "key"]) ||
|
||||
(typeof jsonPayload.appKey === "string" ? jsonPayload.appKey : undefined);
|
||||
const appSecurity =
|
||||
stringOption(parsed.options, ["app-security", "appSecurity", "secret", "password"]) ||
|
||||
(typeof jsonPayload.appSecurity === "string" ? jsonPayload.appSecurity : undefined);
|
||||
const domain =
|
||||
stringOption(parsed.options, ["domain", "base-url", "baseUrl"]) ||
|
||||
(typeof jsonPayload.domain === "string" ? jsonPayload.domain : undefined);
|
||||
const corpId =
|
||||
stringOption(parsed.options, ["corp-id", "corpId", "corp"]) ||
|
||||
(typeof jsonPayload.corpId === "string" ? jsonPayload.corpId : undefined);
|
||||
const staffId =
|
||||
stringOption(parsed.options, ["staff-id", "staffId", "proxyStaffBizId"]) ||
|
||||
(typeof jsonPayload.staffId === "string" ? jsonPayload.staffId : undefined);
|
||||
const staffName =
|
||||
stringOption(parsed.options, ["staff-name", "staffName"]) ||
|
||||
(typeof jsonPayload.staffName === "string" ? jsonPayload.staffName : undefined);
|
||||
const staffPhone =
|
||||
stringOption(parsed.options, ["staff-phone", "staffPhone"]) ||
|
||||
(typeof jsonPayload.staffPhone === "string" ? jsonPayload.staffPhone : undefined);
|
||||
const role =
|
||||
stringOption(parsed.options, ["role"]) ||
|
||||
(typeof jsonPayload.role === "string" ? jsonPayload.role : undefined);
|
||||
const name =
|
||||
stringOption(parsed.options, ["name"]) ||
|
||||
(typeof jsonPayload.name === "string" ? jsonPayload.name : undefined);
|
||||
const overwrite = booleanOption(parsed.options, ["overwrite"], Boolean(jsonPayload.overwrite));
|
||||
const force = booleanOption(parsed.options, ["force", "f"], Boolean(jsonPayload.force));
|
||||
|
||||
if (!appKey || !appSecurity) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "错误:必须提供 appKey 与 appSecurity!用法: hose-use corps add-persistent --app-key=<key> --app-security=<secret> [--staff-id=<id>] [--force] [--overwrite] --yes\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "通过 OpenAPI 持久化密钥接入企业", name || corpId || appKey, {
|
||||
source: "openapi",
|
||||
appKey,
|
||||
domain: domain || "auto-probe",
|
||||
staffId: staffId || "auto-discover",
|
||||
overwrite,
|
||||
});
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"通过 OpenAPI 持久化密钥接入企业",
|
||||
`hose-use corps add-persistent --app-key=${appKey} --app-security=<redacted> --yes`
|
||||
);
|
||||
|
||||
const saved = await onboardHosePersistent({
|
||||
name,
|
||||
appKey,
|
||||
appSecurity,
|
||||
domain,
|
||||
corpId,
|
||||
staffId,
|
||||
staffName,
|
||||
staffPhone,
|
||||
role,
|
||||
force,
|
||||
overwrite,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(saved, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const targetDir = resolveWritableEnterprisesDir();
|
||||
const savedPath = join(targetDir, `${saved.id}.json`);
|
||||
const summaryText = printKeyValue({
|
||||
"企业名称": saved.name,
|
||||
"企业 ID": saved.id,
|
||||
"服务节点": saved.baseUrl,
|
||||
"员工工号": saved.credentials.staffId,
|
||||
"员工姓名": saved.staffName || saved.session?.staffName || "-",
|
||||
"接入账号 (appKey)": saved.credentials.appKey,
|
||||
"凭证来源": formatSourceLabel(saved.source, true),
|
||||
"保存路径": savedPath,
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 成功接入并持久化企业 OpenAPI 凭证!\n${summaryText}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleExtractKeys(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const linkUrl = parsed.args[0] || stringOption(parsed.options, ["url", "link"]);
|
||||
if (!linkUrl) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use corps extract-keys <https://.../web/thirdparty.html?...> [--reveal] [--save] [--app-key <key>] [--key-id <id>] [--overwrite]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const reveal = booleanOption(parsed.options, ["reveal", "r", "plain"], false);
|
||||
const save = booleanOption(parsed.options, ["save", "add", "persist"], false);
|
||||
const name = stringOption(parsed.options, ["name"]);
|
||||
const overwrite = booleanOption(parsed.options, ["overwrite"], true);
|
||||
const force = booleanOption(parsed.options, ["force", "f"], false);
|
||||
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
|
||||
const keyId = stringOption(parsed.options, ["key-id", "keyId"]);
|
||||
|
||||
if (save) {
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "从协助链接提取并持久化 OpenAPI 密钥", name || "待解析企业", {
|
||||
save: true,
|
||||
overwrite,
|
||||
appKey: appKey || "auto-select",
|
||||
});
|
||||
}
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"从协助链接提取并持久化 OpenAPI 密钥",
|
||||
`hose-use corps extract-keys "<url>" --save --yes`
|
||||
);
|
||||
}
|
||||
|
||||
const extracted = await extractOpenApiKeysFromLink(linkUrl, {
|
||||
save,
|
||||
name,
|
||||
overwrite,
|
||||
force,
|
||||
appKey,
|
||||
keyId,
|
||||
});
|
||||
|
||||
const formattedKeys = extracted.keys.map((k) => ({
|
||||
id: k.id,
|
||||
name: k.name || "-",
|
||||
appKey: k.appKey,
|
||||
appSecurity: reveal ? k.appSecurity : maskOpenApiSecurity(k.appSecurity),
|
||||
active: k.active,
|
||||
createTime: k.createTime,
|
||||
updateTime: k.updateTime,
|
||||
}));
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId: extracted.corpId,
|
||||
corpName: extracted.corpName || extracted.corpId,
|
||||
baseUrl: extracted.baseUrl,
|
||||
staffId: extracted.staffId,
|
||||
keyCount: formattedKeys.length,
|
||||
keys: formattedKeys,
|
||||
...(extracted.savedCorp ? { saved: true, savedCorpId: extracted.savedCorp.id } : {}),
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
preserveSensitiveStdout: reveal,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = formattedKeys.map((k, i) => [
|
||||
i + 1,
|
||||
k.name,
|
||||
k.appKey,
|
||||
k.appSecurity,
|
||||
k.active ? "🟢 启用" : "⚪ 停用",
|
||||
]);
|
||||
const table = printTable(["#", "应用名称", "appKey", "appSecurity", "状态"], rows);
|
||||
const savedNotice = extracted.savedCorp
|
||||
? `\n[SUCCESS] 已将密钥 (${extracted.selectedKey?.appKey}) 持久化保存至企业 [${extracted.savedCorp.name} (${extracted.savedCorp.id})]`
|
||||
: "";
|
||||
|
||||
return {
|
||||
stdout: `====== 协助链接 OpenAPI 密钥提取结果 (${extracted.corpName || extracted.corpId}) ======\n${table}${savedNotice}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
preserveSensitiveStdout: reveal,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleElevateCorp(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const elevateAll = booleanOption(parsed.options, ["all", "a"], false);
|
||||
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
|
||||
const keyId = stringOption(parsed.options, ["key-id", "keyId"]);
|
||||
const force = booleanOption(parsed.options, ["force", "f"], true);
|
||||
|
||||
if (elevateAll) {
|
||||
const allCorps = typeof runtime.corpContext.getAllCorps === "function"
|
||||
? runtime.corpContext.getAllCorps()
|
||||
: [];
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "批量提取并持久化全部企业 OpenAPI 密钥", `共 ${allCorps.length} 家企业`, {
|
||||
count: allCorps.length,
|
||||
});
|
||||
}
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"批量提取并持久化全部企业 OpenAPI 密钥",
|
||||
`hose-use corps elevate --all --yes`
|
||||
);
|
||||
|
||||
const results: Array<{ corpId: string; name: string; appKey?: string; status: string }> = [];
|
||||
for (const corp of allCorps) {
|
||||
if (hasOpenApiPersistentCredentials(corp)) {
|
||||
results.push({ corpId: corp.id, name: corp.name, appKey: corp.credentials.appKey, status: "✅ 已持久化" });
|
||||
continue;
|
||||
}
|
||||
const selected = await elevateCorpWithOpenApiKey(corp, { force: true, silent: true });
|
||||
if (selected) {
|
||||
results.push({ corpId: corp.id, name: corp.name, appKey: selected.appKey, status: "✨ 新提权成功" });
|
||||
} else {
|
||||
results.push({ corpId: corp.id, name: corp.name, status: "⚪ 无密钥或会话过期" });
|
||||
}
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ results }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const rows = results.map((r, i) => [i + 1, r.corpId, r.name, r.appKey || "-", r.status]);
|
||||
return {
|
||||
stdout: `====== 批量提权企业 OpenAPI 持久化密钥结果 ======\n${printTable(["#", "企业 ID", "企业名称", "appKey", "状态"], rows)}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const targetCorp = resolveTargetCorpByArgOrContext(parsed.args[0], runtime);
|
||||
if (!targetCorp) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "未找到目标企业,请通过 --corp=<id> 或参数指定企业,或使用 --all 批量提权\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "提取并持久化企业 OpenAPI 密钥", `${targetCorp.name} (${targetCorp.id})`, {
|
||||
corpId: targetCorp.id,
|
||||
appKey: appKey || "auto-select",
|
||||
});
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"提取并持久化企业 OpenAPI 密钥",
|
||||
`hose-use corps elevate ${targetCorp.id} --yes`
|
||||
);
|
||||
|
||||
const selected = await elevateCorpWithOpenApiKey(targetCorp, {
|
||||
appKey,
|
||||
keyId,
|
||||
force,
|
||||
});
|
||||
|
||||
if (!selected) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未能为企业 [${targetCorp.name}] 提取到可用的 OpenAPI 密钥\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId: targetCorp.id,
|
||||
corpName: targetCorp.name,
|
||||
appKey: selected.appKey,
|
||||
appSecurity: maskOpenApiSecurity(selected.appSecurity),
|
||||
keyName: selected.name || "-",
|
||||
persistent: true,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 已将企业 [${targetCorp.name} (${targetCorp.id})] 提权为 OpenAPI 持久化配置 (appKey: ${selected.appKey})!\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleProbeHose(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
|
||||
const appSecurity = stringOption(parsed.options, ["app-security", "appSecurity", "secret"]);
|
||||
const domain = stringOption(parsed.options, ["domain", "base-url"]);
|
||||
|
||||
if (!appKey || !appSecurity) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use corps probe-hose --app-key=<key> --app-security=<secret> [--domain=<url>]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const probe = await probeHoseDomain(appKey, appSecurity, domain);
|
||||
const roleGroups = await fetchHoseRoleDefGroups(probe.domain, probe.openapiToken).catch(() => []);
|
||||
const payload = {
|
||||
domain: probe.domain,
|
||||
corpId: probe.corpId,
|
||||
name: probe.corpName || probe.corpId,
|
||||
roleCount: roleGroups.reduce((acc, g) => acc + g.roleDefs.length, 0),
|
||||
roleGroups,
|
||||
};
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(payload, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `====== OpenAPI 域名与企业探测结果 ======\n${printKeyValue({
|
||||
"企业 ID": payload.corpId,
|
||||
"企业名称": payload.name,
|
||||
"服务节点": payload.domain,
|
||||
"角色数量": payload.roleCount,
|
||||
})}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleHoseStaffs(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
|
||||
const appSecurity = stringOption(parsed.options, ["app-security", "appSecurity", "secret"]);
|
||||
const domain = stringOption(parsed.options, ["domain", "base-url"]);
|
||||
const role = stringOption(parsed.options, ["role", "roleDefId"]);
|
||||
|
||||
if (!appKey || !appSecurity) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use corps hose-staffs --app-key=<key> --app-security=<secret> [--role=admin]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const res = await listHoseStaffsByOpenApi({ appKey, appSecurity, domain, role });
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(res, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const rows = res.staffs.map((s, i) => [i + 1, s.id, s.name, s.cellphone || "-", s.active ? "在职" : "离职"]);
|
||||
return {
|
||||
stdout: `====== 角色成员列表 (${res.roleName || res.roleId}) ======\n${printTable(["#", "员工 ID", "姓名", "手机号", "状态"], rows)}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleSyncFromSeal(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const filter = parsed.args[0] || stringOption(parsed.options, ["corp", "filter", "keyword"]);
|
||||
const sealDir = stringOption(parsed.options, ["seal-dir", "sealDir"]);
|
||||
const verify = booleanOption(parsed.options, ["verify"], false);
|
||||
const overwrite = booleanOption(parsed.options, ["overwrite", "force", "f"], true);
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "从 seal-use 同步企业 OpenAPI 持久化密钥", filter || "全部合思企业", {
|
||||
filter: filter || null,
|
||||
verify,
|
||||
overwrite,
|
||||
});
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"从 seal-use 同步企业 OpenAPI 持久化密钥",
|
||||
`hose-use corps sync-seal${filter ? ` ${filter}` : ""} --yes`
|
||||
);
|
||||
|
||||
const synced = await syncOpenApiFromSealUse({
|
||||
filter,
|
||||
sealEnterprisesDir: sealDir,
|
||||
verify,
|
||||
overwrite,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(synced, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (synced.items.length === 0) {
|
||||
return {
|
||||
stdout: `未在 ${synced.sealDir} 中找到可同步的合思 OpenAPI 持久化密钥配置${filter ? ` (过滤条件: ${filter})` : ""}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = synced.items.map((item, idx) => [
|
||||
idx + 1,
|
||||
item.corpId,
|
||||
item.name,
|
||||
item.appKey,
|
||||
item.staffId,
|
||||
item.action === "merged" ? "🔄 合并增强" : item.action === "created" ? "✨ 新增企业" : "⏭️ 跳过",
|
||||
]);
|
||||
const table = printTable(["#", "企业 ID", "企业名称", "appKey", "默认工号", "同步动作"], rows);
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 已从 seal-use 同步 ${synced.items.length} 家企业的 OpenAPI 持久化凭证!\n${table}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
import { fetchOpenApiKeys } from "../../domains/store/tools.js";
|
||||
import { booleanOption } from "../parser.js";
|
||||
import { selectOpenApiKey } from "../../core/auth/login.js";
|
||||
import { saveCorpConfig } from "../../core/config/loader.js";
|
||||
import { booleanOption, stringOption } from "../parser.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
|
||||
function formatDate(ts: number): string {
|
||||
@@ -39,9 +42,80 @@ export async function handleKeysCommand(
|
||||
parsed.action === "reveal" ||
|
||||
parsed.args[0] === "reveal";
|
||||
|
||||
const save =
|
||||
booleanOption(parsed.options, ["save", "persist", "elevate"]) ||
|
||||
parsed.action === "save" ||
|
||||
parsed.args[0] === "save";
|
||||
|
||||
const appKeyOpt = stringOption(parsed.options, ["app-key", "appKey"]);
|
||||
const keyIdOpt = stringOption(parsed.options, ["key-id", "keyId"]);
|
||||
const force = booleanOption(parsed.options, ["force", "f"]);
|
||||
|
||||
if (save) {
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "提取并持久化企业 OpenAPI 密钥", `${currentCorp.name} (${currentCorp.id})`, {
|
||||
corpId: currentCorp.id,
|
||||
appKey: appKeyOpt || "auto-select",
|
||||
keyId: keyIdOpt || null,
|
||||
});
|
||||
}
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"提取并持久化企业 OpenAPI 密钥",
|
||||
`hose-use keys --corp=${currentCorp.id} --save --yes`
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const keys = await fetchOpenApiKeys(currentCorp);
|
||||
|
||||
if (save) {
|
||||
const selected = selectOpenApiKey(
|
||||
keys.map((k) => ({
|
||||
id: k.id,
|
||||
name: k.name || undefined,
|
||||
appKey: k.appKey,
|
||||
appSecurity: k.appSecurity,
|
||||
active: k.active,
|
||||
createTime: k.createTime,
|
||||
updateTime: k.updateTime,
|
||||
})),
|
||||
currentCorp.id,
|
||||
{ appKey: appKeyOpt, keyId: keyIdOpt, force }
|
||||
);
|
||||
currentCorp.credentials.appKey = selected.appKey;
|
||||
currentCorp.credentials.appSecurity = selected.appSecurity;
|
||||
const savedPath = saveCorpConfig(currentCorp);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
saved: true,
|
||||
corpId: currentCorp.id,
|
||||
corpName: currentCorp.name,
|
||||
appKey: selected.appKey,
|
||||
appSecurity: reveal ? selected.appSecurity : maskSecret(selected.appSecurity),
|
||||
keyName: selected.name || "-",
|
||||
path: savedPath,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
preserveSensitiveStdout: reveal,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 已为企业 [${currentCorp.name}] 持久化保存 OpenAPI 密钥 (appKey: ${selected.appKey})!\n保存路径: ${savedPath}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
preserveSensitiveStdout: reveal,
|
||||
};
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
const outputData = reveal
|
||||
? keys
|
||||
@@ -53,6 +127,7 @@ export async function handleKeysCommand(
|
||||
stdout: printJson(outputData, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
preserveSensitiveStdout: reveal,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -81,12 +156,13 @@ export async function handleKeysCommand(
|
||||
const title = `====== [${currentCorp.name}] 企业 OpenAPI 接入密钥列表 (共 ${keys.length} 个) ======`;
|
||||
const hint = reveal
|
||||
? ""
|
||||
: "\n提示: 接入密码默认脱敏,附加 --reveal (或 -r) 可查看完整明文;使用 --json 可输出完整结构。\n";
|
||||
: "\n提示: 接入密码默认脱敏,附加 --reveal (或 -r) 可查看完整明文;附加 --save --yes 可持久化到当前企业配置;使用 --json 可输出完整结构。\n";
|
||||
|
||||
return {
|
||||
stdout: `${title}\n\n${table}\n${hint}`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
preserveSensitiveStdout: reveal,
|
||||
};
|
||||
} catch (err: any) {
|
||||
return {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { canRefreshCorpAccessToken, hasOpenApiPersistentCredentials } from "../../core/auth/login.js";
|
||||
import { createSessionClient, getEasoClient } from "../../core/http/index.js";
|
||||
import * as api from "../../domains/platform/api.js";
|
||||
import { printJson, printKeyValue, formatSourceLabel, formatExpiresAt } from "../printer.js";
|
||||
@@ -16,6 +17,9 @@ export async function handleProbeCommand(
|
||||
};
|
||||
}
|
||||
|
||||
const hasOpenApi = hasOpenApiPersistentCredentials(currentCorp);
|
||||
const isPersistent = canRefreshCorpAccessToken(currentCorp);
|
||||
|
||||
const results: Record<string, unknown> = {
|
||||
enterprise: {
|
||||
id: currentCorp.id,
|
||||
@@ -24,6 +28,8 @@ export async function handleProbeCommand(
|
||||
baseUrl: currentCorp.baseUrl,
|
||||
source: currentCorp.source,
|
||||
accountId: currentCorp.accountId,
|
||||
persistent: isPersistent,
|
||||
hasOpenApiKey: hasOpenApi,
|
||||
},
|
||||
ekbSession: { status: "pending" },
|
||||
easoToken: { status: "pending" },
|
||||
@@ -98,8 +104,13 @@ export async function handleProbeCommand(
|
||||
"企业 ID": currentCorp.id,
|
||||
"员工工号": currentCorp.credentials.staffId,
|
||||
"员工姓名": currentCorp.staffName || currentCorp.session?.staffName || "-",
|
||||
"凭证来源": formatSourceLabel(currentCorp.source),
|
||||
"Token 过期时间": formatExpiresAt(currentCorp.auth?.expiresAt || currentCorp.session?.expTime),
|
||||
"凭证来源": formatSourceLabel(currentCorp.source, hasOpenApi),
|
||||
"持久化状态": isPersistent
|
||||
? hasOpenApi
|
||||
? `✅ OpenAPI 持久化密钥 (${currentCorp.credentials.appKey})`
|
||||
: "✅ 统一认证主账号自动换票"
|
||||
: "⚪ 短期会话",
|
||||
"Token 过期时间": formatExpiresAt(currentCorp.auth?.expiresAt || currentCorp.session?.expTime, isPersistent),
|
||||
"主站 Session 连通": (results.ekbSession as any).status === "ok" ? "🟢 正常" : "🔴 异常",
|
||||
"EASO 引擎鉴权换票": (results.easoToken as any).status === "ok" ? "🟢 握手成功" : "🔴 失败",
|
||||
"自建应用扫描": (results.platformAccess as any).status === "ok" ? `🟢 可访问 (${(results.platformAccess as any).totalPlatforms} 个自建应用)` : "🔴 失败",
|
||||
|
||||
+32
-3
@@ -7,8 +7,37 @@ export interface HelpTopic {
|
||||
|
||||
export const HELP_REGISTRY: Record<string, HelpTopic> = {
|
||||
context: { summary: "全局运行上下文与身份诊断", usage: "hose-use context [--json]", commands: { context: "输出当前企业、账号、运行模式与认证状态" } },
|
||||
auth: { summary: "认证与凭证管理", usage: "hose-use auth <子命令>", commands: { login: "登录并保存企业凭证", status: "查看当前认证状态", accounts: "列出已保存账号", "switch-account": "切换默认账号" } },
|
||||
corps: { summary: "多企业租户管理", usage: "hose-use corps <子命令>", commands: { list: "列出本地企业配置", search: "搜索企业与员工", switch: "切换当前工作企业", current: "查看当前企业", "add-link": "从链接导入企业凭证" } },
|
||||
auth: {
|
||||
summary: "认证与凭证管理(支持主账号登录与企业级 OpenAPI 持久化)",
|
||||
usage: "hose-use auth <子命令>",
|
||||
commands: {
|
||||
login: "登录并保存企业凭证",
|
||||
status: "查看当前认证状态",
|
||||
refresh: "刷新账号或企业 AccessToken",
|
||||
link: "生成企业 Web 免密登录直达链接 (别名: hose-link)",
|
||||
"add-link": "从协助链接导入企业凭证(自动探测并持久化 OpenAPI 密钥)",
|
||||
"add-persistent": "通过 OpenAPI 密钥 (appKey + appSecurity) 持久化接入企业",
|
||||
"extract-keys": "从协助链接提取 OpenAPI 密钥",
|
||||
elevate: "为已配置企业提取并持久化保存 OpenAPI 密钥",
|
||||
accounts: "列出已保存账号",
|
||||
"switch-account": "切换默认账号",
|
||||
},
|
||||
},
|
||||
corps: {
|
||||
summary: "多企业租户管理",
|
||||
usage: "hose-use corps <子命令>",
|
||||
commands: {
|
||||
list: "列出本地企业配置",
|
||||
search: "搜索企业与员工",
|
||||
switch: "切换当前工作企业",
|
||||
current: "查看当前企业",
|
||||
link: "生成企业 Web 免密登录直达链接 (别名: hose-link)",
|
||||
"add-link": "从链接导入企业凭证(自动探测并持久化 OpenAPI 密钥)",
|
||||
"add-persistent": "通过 OpenAPI 密钥持久化接入企业",
|
||||
"extract-keys": "从协助链接提取 OpenAPI 密钥",
|
||||
elevate: "为已配置企业提取并持久化保存 OpenAPI 密钥",
|
||||
},
|
||||
},
|
||||
config: { summary: "全局运行模式与路径配置", usage: "hose-use config <子命令>", commands: { paths: "诊断配置目录链", get: "查看全局配置", mode: "切换 stateful/stateless", set: "更新指定配置项" } },
|
||||
workflow: { summary: "工作流查询、草稿与生命周期管理", usage: "hose-use workflow <子命令> [参数] [选项]", commands: { list: "列出工作流", get: "查看工作流详情", find: "按节点类型搜索", analyze: "静态分析工作流", patch: "生成草稿字段补丁", save: "保存草稿到远端", toggle: "切换启停状态", publish: "发布并启用工作流", history: "查看版本历史", logs: "查看运行日志", check: "检查错误管道" }, options: ["--dry-run 只预览写操作", "--yes/--confirm 确认写操作", "--file=<workflow.json> 指定工作流快照"] },
|
||||
bill: { summary: "单据检索与审批动作", usage: "hose-use bill <子命令> [单号|ID] [选项]", commands: { list: "查询单据", get: "查看单据详情", flow: "查看审批流程", approve: "同意审批", reject: "驳回审批", transfer: "转交审批", "add-node": "加签审批", comment: "添加评论" }, options: ["--dry-run 只预览审批动作", "--yes/--confirm 确认执行审批动作", "--comment=<原因> 驳回或评论内容"] },
|
||||
@@ -25,7 +54,7 @@ export const HELP_REGISTRY: Record<string, HelpTopic> = {
|
||||
app: { summary: "桌面端工作台应用管理", usage: "hose-use app <子命令>", commands: { list: "列出应用", get: "查看应用详情" } },
|
||||
menu: { summary: "桌面端主导航菜单树", usage: "hose-use menu list", commands: { list: "查看主导航", apps: "查看应用入口" } },
|
||||
openapi: { summary: "OpenAPI 规范导出与路径查询", usage: "hose-use openapi [paths|info|--raw|keys]", commands: { paths: "列出路径概要", info: "查看规范元数据", keys: "查看企业接入密钥" } },
|
||||
keys: { summary: "企业 OpenAPI 接入凭证", usage: "hose-use keys [--json] [--reveal]", commands: { keys: "读取当前企业密钥(默认脱敏)" }, options: ["--reveal 仅在明确授权后查看明文"] },
|
||||
keys: { summary: "企业 OpenAPI 接入凭证", usage: "hose-use keys [--json] [--reveal] [--save]", commands: { keys: "读取当前企业密钥(默认脱敏)" }, options: ["--reveal 仅在明确授权后查看明文", "--save --yes 提取并持久化保存到本地企业配置"] },
|
||||
store: { summary: "已购应用与应用商店探查", usage: "hose-use store <list|search|get>", commands: { list: "列出已购应用", search: "搜索应用商店", get: "查看应用详情" } },
|
||||
update: { summary: "版本自更新与发布记录", usage: "hose-use update [check|--changelog]", commands: { update: "检查并升级版本", check: "只检查可用版本", changelog: "查看发布记录" } },
|
||||
skill: { summary: "Agent Skill 管理", usage: "hose-use skill <install|status|dump>", commands: { install: "安装内嵌 Skill", status: "查看安装状态", dump: "导出 Skill 文件" } },
|
||||
|
||||
+17
-11
@@ -41,40 +41,46 @@ export function printJson(data: unknown, options: OutputOptions = {}): string {
|
||||
return json;
|
||||
}
|
||||
|
||||
export function formatSourceLabel(source?: string): string {
|
||||
export function formatSourceLabel(source?: string, persistentOpenApi?: boolean): string {
|
||||
const suffix = persistentOpenApi && source !== "openapi" ? " + OpenAPI 持久化密钥" : "";
|
||||
switch (source) {
|
||||
case "openapi":
|
||||
return "开放平台持久化密钥 (OpenAPI AppKey)";
|
||||
case "assist":
|
||||
return "官方协助/代客平台 (Assist Platform)";
|
||||
return `官方协助/代客平台 (Assist Platform)${suffix}`;
|
||||
case "account":
|
||||
return "统一认证中心 (IDP 账密/短信)";
|
||||
return `统一认证中心 (IDP 账密/短信)${suffix}`;
|
||||
case "browser":
|
||||
return "浏览器会话同步 (WebBridge)";
|
||||
return `浏览器会话同步 (WebBridge)${suffix}`;
|
||||
case "link":
|
||||
return "协助/免密链接导入 (Assistance Link)";
|
||||
return `协助/免密链接导入 (Assistance Link)${suffix}`;
|
||||
case "curl":
|
||||
case "f12":
|
||||
return "cURL 抓包导入 (cURL/F12)";
|
||||
return `cURL 抓包导入 (cURL/F12)${suffix}`;
|
||||
case "manual":
|
||||
return "手动配置";
|
||||
return `手动配置${suffix}`;
|
||||
default:
|
||||
return source || "未知来源";
|
||||
return (source || "未知来源") + suffix;
|
||||
}
|
||||
}
|
||||
|
||||
export function formatExpiresAt(expiresAt?: number | null): string {
|
||||
export function formatExpiresAt(expiresAt?: number | null, persistent?: boolean): string {
|
||||
if (!expiresAt || expiresAt <= 0) return "长期有效 / 服务端未显式限制";
|
||||
const diffMs = expiresAt - Date.now();
|
||||
const dateStr = new Date(expiresAt).toLocaleString("zh-CN", { hour12: false });
|
||||
if (diffMs <= 0) {
|
||||
if (persistent) {
|
||||
return `${dateStr} (🔄 持久化密钥自动续期)`;
|
||||
}
|
||||
return `${dateStr} (⚠️ 已过期)`;
|
||||
}
|
||||
const diffMins = Math.floor(diffMs / 60000);
|
||||
if (diffMins < 60) {
|
||||
return `${dateStr} (约剩余 ${diffMins} 分钟)`;
|
||||
return `${dateStr} (约剩余 ${diffMins} 分钟${persistent ? ",支持自动续期" : ""})`;
|
||||
}
|
||||
const diffHours = (diffMs / 3600000).toFixed(1);
|
||||
if (Number(diffHours) < 24) {
|
||||
return `${dateStr} (约剩余 ${diffHours} 小时)`;
|
||||
return `${dateStr} (约剩余 ${diffHours} 小时${persistent ? ",支持自动续期" : ""})`;
|
||||
}
|
||||
const diffDays = Math.floor(diffMs / 86400000);
|
||||
return `${dateStr} (约剩余 ${diffDays} 天)`;
|
||||
|
||||
+5
-1
@@ -82,10 +82,14 @@ async function runCliOnce(
|
||||
const result = await dispatchCli(rawArgs, options);
|
||||
const extraStdout = stdoutChunks.length ? `${stdoutChunks.join("\n")}\n` : "";
|
||||
const extraStderr = stderrChunks.length ? `${stderrChunks.join("\n")}\n` : "";
|
||||
const bodyStdout = result.preserveSensitiveStdout
|
||||
? result.stdout || ""
|
||||
: redactSensitiveText(result.stdout || "");
|
||||
return {
|
||||
stdout: redactSensitiveText(extraStdout + (result.stdout || "")),
|
||||
stdout: redactSensitiveText(extraStdout) + bodyStdout,
|
||||
stderr: redactSensitiveText(extraStderr + (result.stderr || "")),
|
||||
exitCode: result.exitCode,
|
||||
preserveSensitiveStdout: result.preserveSensitiveStdout,
|
||||
};
|
||||
} finally {
|
||||
console.log = originalLog;
|
||||
|
||||
@@ -22,6 +22,7 @@ export interface CliResult {
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
exitCode: number;
|
||||
preserveSensitiveStdout?: boolean;
|
||||
}
|
||||
|
||||
export interface OutputOptions {
|
||||
|
||||
@@ -6,8 +6,8 @@ Core 层负责基础设施:企业配置管理、认证 Token 获取与缓存
|
||||
|
||||
```text
|
||||
src/core/
|
||||
├── auth/ # 登录认证协议与凭证存储(纯凭据层)
|
||||
│ ├── login.ts # 登录四矩阵(RSA账密登录、短信验证码、F12/cURL凭证导入、浏览器同步)
|
||||
├── auth/ # 登录认证协议与凭证存储(纯凭据层:用户级主账号 + 企业级 OpenAPI 持久化双通道)
|
||||
│ ├── login.ts # 登录与换票矩阵(RSA账密、短信、F12/协助链接导入、浏览器同步、OpenAPI 密钥持久化与 getProvisionalAuth 续期)
|
||||
│ ├── account-store.ts # 多账号持久化存储 (~/.config/hose-use/accounts.json)
|
||||
│ ├── tools.ts # MCP Auth Tools 注册与调度
|
||||
│ ├── token-store.ts # 动态 Token 缓存 (~/.config/hose-use/tokens.json)
|
||||
@@ -15,9 +15,9 @@ src/core/
|
||||
├── http/ # 统一 HTTP 客户端装配与网络传输(语义化客户端)
|
||||
│ ├── factory.ts # Ky 底层客户端工厂(超时、重试、错误钩子)
|
||||
│ ├── fingerprint.ts # 统一浏览器指纹、User-Agent、Cookie 与 WAF 策略头
|
||||
│ ├── session-client.ts # 闭合用户会话客户端(三 Header + 指纹 + 401 续杯)
|
||||
│ ├── session-client.ts # 闭合用户会话客户端(三 Header + 指纹 + 账号/OpenAPI 双通道自动续杯)
|
||||
│ ├── openapi-client.ts # 开放平台应用客户端(appKey 换票与签名机制)
|
||||
│ ├── unity-client.ts # 应用中心与动态集群寻址客户端
|
||||
│ ├── unity-client.ts # 应用中心与动态集群寻址客户端(支持账号/OpenAPI 双通道预续期)
|
||||
│ ├── script-engine-client.ts # 工作流 MVEL/Python 脚本调试引擎客户端
|
||||
│ └── index.ts # 统一导出入口
|
||||
├── cache/ # 统一多级协同缓存
|
||||
|
||||
+1289
-36
File diff suppressed because it is too large.
Load diff
@@ -208,6 +208,26 @@ export function loadCorpConfigs(overrideDirs?: string[]): CorpConfig[] {
|
||||
export function saveCorpConfig(config: CorpConfig, dir?: string): string {
|
||||
const targetDir = dir || resolveWritableEnterprisesDir();
|
||||
ensureDir(targetDir);
|
||||
const candidatePath = join(targetDir, `${config.id}.json`);
|
||||
if (!config.credentials?.appKey && existsSync(candidatePath)) {
|
||||
try {
|
||||
const existing = JSON.parse(readFileSync(candidatePath, "utf-8"));
|
||||
const existingKey = existing?.credentials?.appKey || existing?.auth?.appKey;
|
||||
const existingSec = existing?.credentials?.appSecurity || existing?.auth?.appSecurity;
|
||||
if (existingKey && existingSec) {
|
||||
config = {
|
||||
...config,
|
||||
credentials: {
|
||||
...config.credentials,
|
||||
appKey: existingKey,
|
||||
appSecurity: existingSec,
|
||||
},
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// ignore malformed existing file
|
||||
}
|
||||
}
|
||||
const validated = CorpConfigSchema.parse(config);
|
||||
const filePath = join(targetDir, `${validated.id}.json`);
|
||||
writeFileSync(filePath, JSON.stringify(validated, null, 2), "utf-8");
|
||||
|
||||
+21
-12
@@ -12,6 +12,7 @@ export interface CorpSummary {
|
||||
baseUrl?: string;
|
||||
current: boolean;
|
||||
expiresAt?: number;
|
||||
persistent?: boolean;
|
||||
}
|
||||
|
||||
export function resolveCorpConfig(
|
||||
@@ -150,17 +151,25 @@ export class CorpContext {
|
||||
}
|
||||
|
||||
listCorps(): CorpSummary[] {
|
||||
return Array.from(this.corps.values()).map((corp) => ({
|
||||
id: corp.id,
|
||||
name: corp.name,
|
||||
corpId: corp.corpId || corp.credentials.corpId,
|
||||
staffId: corp.credentials.staffId,
|
||||
staffName: corp.staffName || corp.session?.staffName || undefined,
|
||||
source: corp.source || "manual",
|
||||
accountId: corp.accountId,
|
||||
baseUrl: corp.baseUrl,
|
||||
current: corp.id === this.current?.id,
|
||||
expiresAt: corp.auth?.expiresAt || (corp.session?.expTime ?? undefined),
|
||||
}));
|
||||
return Array.from(this.corps.values()).map((corp) => {
|
||||
const hasOpenApiKeys = Boolean(
|
||||
(corp.credentials?.appKey || corp.auth?.appKey) &&
|
||||
(corp.credentials?.appSecurity || corp.auth?.appSecurity)
|
||||
);
|
||||
const hasAccountBinding = corp.source === "account" && !corp.session?.isShortTermToken && Boolean(corp.accountId);
|
||||
return {
|
||||
id: corp.id,
|
||||
name: corp.name,
|
||||
corpId: corp.corpId || corp.credentials.corpId,
|
||||
staffId: corp.credentials.staffId,
|
||||
staffName: corp.staffName || corp.session?.staffName || undefined,
|
||||
source: corp.source || "manual",
|
||||
accountId: corp.accountId,
|
||||
baseUrl: corp.baseUrl,
|
||||
current: corp.id === this.current?.id,
|
||||
expiresAt: corp.auth?.expiresAt || (corp.session?.expTime ?? undefined),
|
||||
persistent: hasOpenApiKeys || hasAccountBinding,
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { z } from "zod";
|
||||
|
||||
export const CredentialSourceSchema = z.enum([
|
||||
"account", // 官方统一认证中心 (IDP) 账密/短信登录
|
||||
"openapi", // 开放平台持久化密钥 (appKey + appSecurity)
|
||||
"assist", // 官方协助/代客平台 (Assist Platform) 调试授权会话
|
||||
"browser", // 浏览器会话 / Cookie 同步
|
||||
"link", // 协助/免密链接导入 (thirdparty.html / assistance link)
|
||||
@@ -12,15 +13,19 @@ export const CredentialSourceSchema = z.enum([
|
||||
export type CredentialSource = z.infer<typeof CredentialSourceSchema>;
|
||||
|
||||
export const CorpCredentialsSchema = z.object({
|
||||
accessToken: z.string().describe("主站访问令牌"),
|
||||
accessToken: z.string().default("").describe("主站访问令牌"),
|
||||
corpId: z.string().describe("企业 ID"),
|
||||
staffId: z.string().describe("员工 ID"),
|
||||
appKey: z.string().optional().describe("开放平台应用 AppKey (持久化凭证)"),
|
||||
appSecurity: z.string().optional().describe("开放平台应用 AppSecurity (持久化凭证)"),
|
||||
});
|
||||
|
||||
export const CorpAuthConfigSchema = z.object({
|
||||
refreshTtl: z.number().default(300).describe("提前多少秒刷新,默认 5 分钟"),
|
||||
refreshToken: z.string().optional().describe("OAuth2 Refresh Token"),
|
||||
expiresAt: z.number().optional().describe("AccessToken 到期时间戳 (ms)"),
|
||||
appKey: z.string().optional().describe("开放平台应用 AppKey (兼容冗余字段)"),
|
||||
appSecurity: z.string().optional().describe("开放平台应用 AppSecurity (兼容冗余字段)"),
|
||||
});
|
||||
|
||||
export const CorpSessionInfoSchema = z.object({
|
||||
|
||||
@@ -1,5 +1,14 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { canRefreshCorpAccessToken, resolveLinkExpiresAt } from "../auth/login.js";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
canRefreshCorpAccessToken,
|
||||
getCorpProvisionalAuthLink,
|
||||
hasOpenApiPersistentCredentials,
|
||||
resolveLinkExpiresAt,
|
||||
selectOpenApiKey,
|
||||
} from "../auth/login.js";
|
||||
import { createSessionClient } from "./session-client.js";
|
||||
import type { CorpConfig } from "../config/types.js";
|
||||
|
||||
@@ -8,19 +17,32 @@ function corp(overrides: Partial<CorpConfig> = {}): CorpConfig {
|
||||
id: "corp-1",
|
||||
name: "测试企业",
|
||||
source: "link",
|
||||
credentials: { accessToken: "token", corpId: "corp-1", staffId: "staff-1" },
|
||||
credentials: { accessToken: "token", corpId: "corp-1", staffId: "corp-1:staff-1" },
|
||||
...overrides,
|
||||
baseUrl: overrides.baseUrl ?? "https://app.ekuaibao.com",
|
||||
};
|
||||
}
|
||||
|
||||
describe("core/http/session-client refresh policy", () => {
|
||||
it("only allows account credentials with an explicit account binding to refresh", () => {
|
||||
it("allows refresh for account credentials or OpenAPI persistent credentials", () => {
|
||||
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);
|
||||
|
||||
const openApiCorp = corp({
|
||||
source: "link",
|
||||
credentials: {
|
||||
accessToken: "token",
|
||||
corpId: "corp-1",
|
||||
staffId: "corp-1:staff-1",
|
||||
appKey: "key-123",
|
||||
appSecurity: "sec-456",
|
||||
},
|
||||
});
|
||||
expect(hasOpenApiPersistentCredentials(openApiCorp)).toBe(true);
|
||||
expect(canRefreshCorpAccessToken(openApiCorp)).toBe(true);
|
||||
});
|
||||
|
||||
it("fails expired temporary credentials without retrying or refreshing", async () => {
|
||||
@@ -39,6 +61,96 @@ describe("core/http/session-client refresh policy", () => {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
it("automatically refreshes expired token via OpenAPI getProvisionalAuth when appKey/appSecurity are present", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
const tempDir = mkdtempSync(join(tmpdir(), "hose-use-test-"));
|
||||
const prevEnv = process.env.HOSE_ENTERPRISES_DIR;
|
||||
process.env.HOSE_ENTERPRISES_DIR = tempDir;
|
||||
|
||||
const seenUrls: string[] = [];
|
||||
globalThis.fetch = (async (input: string | URL | Request) => {
|
||||
const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
||||
seenUrls.push(url);
|
||||
if (url.includes("/api/openapi/v1/auth/getAccessToken")) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
value: {
|
||||
accessToken: "openapi-token-xyz",
|
||||
corporationId: "corp-1",
|
||||
expireTime: Date.now() + 7200_000,
|
||||
},
|
||||
}),
|
||||
{ status: 200, headers: { "content-type": "application/json" } }
|
||||
);
|
||||
}
|
||||
if (url.includes("/api/openapi/v1.1/provisional/getProvisionalAuth")) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
value: {
|
||||
message:
|
||||
"https://app.ekuaibao.com/web/thirdparty.html?accessToken=fresh-session-token-999&ekbCorpId=corp-1",
|
||||
},
|
||||
}),
|
||||
{ status: 200, headers: { "content-type": "application/json" } }
|
||||
);
|
||||
}
|
||||
return new Response(JSON.stringify({ value: { ok: true } }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
}) as unknown as typeof fetch;
|
||||
|
||||
try {
|
||||
const persistentCorp = corp({
|
||||
source: "openapi",
|
||||
credentials: {
|
||||
accessToken: "",
|
||||
corpId: "corp-1",
|
||||
staffId: "corp-1:staff-1",
|
||||
appKey: "test-app-key",
|
||||
appSecurity: "test-app-security",
|
||||
},
|
||||
auth: {
|
||||
refreshTtl: 300,
|
||||
expiresAt: Date.now() - 10_000,
|
||||
},
|
||||
});
|
||||
|
||||
const client = await createSessionClient(persistentCorp);
|
||||
expect(persistentCorp.credentials.accessToken).toBe("fresh-session-token-999");
|
||||
|
||||
const linkRes = await getCorpProvisionalAuthLink(persistentCorp, { enterprisesDir: tempDir });
|
||||
expect(linkRes.method).toBe("provisional-openapi");
|
||||
expect(linkRes.url).toContain("accessToken=fresh-session-token-999");
|
||||
expect(client).toBeDefined();
|
||||
expect(seenUrls.some((u) => u.includes("getProvisionalAuth"))).toBe(true);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
if (prevEnv === undefined) delete process.env.HOSE_ENTERPRISES_DIR;
|
||||
else process.env.HOSE_ENTERPRISES_DIR = prevEnv;
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("core/auth/login > selectOpenApiKey", () => {
|
||||
const sampleKeys = [
|
||||
{ id: "k1", name: "停用密钥", appKey: "ak-1", appSecurity: "sec-1", active: false },
|
||||
{ id: "k2", name: "启用密钥A", appKey: "ak-2", appSecurity: "sec-2", active: true },
|
||||
{ id: "k3", name: "启用密钥B", appKey: "ak-3", appSecurity: "sec-3", active: true },
|
||||
];
|
||||
|
||||
it("auto-selects when only one active key exists", () => {
|
||||
const picked = selectOpenApiKey([sampleKeys[0]!, sampleKeys[1]!], "corp-1");
|
||||
expect(picked.appKey).toBe("ak-2");
|
||||
});
|
||||
|
||||
it("requires explicit selection or --force when multiple active keys exist", () => {
|
||||
expect(() => selectOpenApiKey(sampleKeys, "corp-1")).toThrow("存在多套");
|
||||
expect(selectOpenApiKey(sampleKeys, "corp-1", { force: true }).appKey).toBe("ak-2");
|
||||
expect(selectOpenApiKey(sampleKeys, "corp-1", { appKey: "ak-3" }).appKey).toBe("ak-3");
|
||||
});
|
||||
});
|
||||
|
||||
describe("core/auth/login link expiry", () => {
|
||||
|
||||
@@ -44,15 +44,16 @@ export async function createSessionClient(
|
||||
) {
|
||||
const canRefresh = canRefreshCorpAccessToken(corp);
|
||||
|
||||
// 1. 预检:若 Token 即将过期 (提前 refreshTtl 秒),静默无感自动续杯
|
||||
if (canRefresh && corp.auth?.expiresAt) {
|
||||
const ttlMs = (corp.auth.refreshTtl || 300) * 1000;
|
||||
if (Date.now() >= corp.auth.expiresAt - ttlMs) {
|
||||
// 1. 预检:若 Token 缺失或即将过期 (提前 refreshTtl 秒),静默无感自动续杯
|
||||
if (canRefresh) {
|
||||
const ttlMs = (corp.auth?.refreshTtl || 300) * 1000;
|
||||
const expiresAt = corp.auth?.expiresAt || corp.session?.expTime;
|
||||
if (!corp.credentials.accessToken || (expiresAt && Date.now() >= expiresAt - ttlMs)) {
|
||||
await refreshSingleCorpAccessToken(corp);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 仅账号凭证启用 401 自动重试与换票;临时凭证直接给出可操作错误
|
||||
// 2. 具备续期能力(主账号或 OpenAPI 持久化密钥)时启用 401 自动重试与换票;临时凭证直接给出可操作错误
|
||||
return createAuthClient({
|
||||
prefixUrl: corp.baseUrl || "https://app.ekuaibao.com",
|
||||
getHeaders: () => getSessionHeaders(corp, options.fingerprint),
|
||||
|
||||
@@ -2,6 +2,10 @@ import ky from "ky";
|
||||
import type { CorpConfig } from "../config/types.js";
|
||||
import { createAuthClient } from "./factory.js";
|
||||
import { AuthenticationError } from "../errors.js";
|
||||
import {
|
||||
canRefreshCorpAccessToken,
|
||||
refreshSingleCorpAccessToken,
|
||||
} from "../auth/login.js";
|
||||
|
||||
export const EASO_BASE_URL = "https://unity.ekuaibao.com";
|
||||
export const BUSINESS_CENTER_URL = "https://business-center.ekuaibao.com";
|
||||
@@ -133,6 +137,13 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
|
||||
};
|
||||
}
|
||||
|
||||
if (canRefreshCorpAccessToken(corp)) {
|
||||
const expiresAt = corp.auth?.expiresAt || corp.session?.expTime;
|
||||
if (!corp.credentials.accessToken || (expiresAt && Date.now() >= expiresAt - refreshTtl * 1000)) {
|
||||
await refreshSingleCorpAccessToken(corp);
|
||||
}
|
||||
}
|
||||
|
||||
const corpId = corp.corpId || corp.credentials.corpId;
|
||||
const staffId = corp.staffId || corp.credentials.staffId;
|
||||
const environment = resolveCorpCluster(corp);
|
||||
@@ -207,6 +218,13 @@ export async function getUnityClient(corp: CorpConfig): Promise<{
|
||||
};
|
||||
}
|
||||
|
||||
if (canRefreshCorpAccessToken(corp)) {
|
||||
const expiresAt = corp.auth?.expiresAt || corp.session?.expTime;
|
||||
if (!corp.credentials.accessToken || (expiresAt && Date.now() >= expiresAt - refreshTtl * 1000)) {
|
||||
await refreshSingleCorpAccessToken(corp);
|
||||
}
|
||||
}
|
||||
|
||||
const corpId = corp.corpId || corp.credentials.corpId;
|
||||
const staffId = corp.staffId || corp.credentials.staffId;
|
||||
const baseUrl = corp.baseUrl || EKB_BASE_URL;
|
||||
|
||||
Reference in new issue
Block a user