Merge pull request #51 from yunyingk/feat/corps-add-link-and-multi-cluster

feat: 支持协助链接秒级导入 (corps add-link) 与多集群 (wx2等) 动态换票
This commit is contained in:
yunyingk authored and GitHub committed 2026-09-07 14:45:03 +08:00
commit 0ee5031dc8
13 files changed
+1268 -408

No files matched your search

+748 -242
View File
File diff suppressed because it is too large. Load diff
+1
View File
@@ -36,6 +36,7 @@ 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`, `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) |
| 代客协助凭证导入 / 探针连通性诊断 | `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`, `hose-use bill get <单号|ID> [--risk]` | [references/bill.md](references/bill.md) |
+14 -1
View File
@@ -42,6 +42,19 @@ hose-use auth refresh
```
- 主动调用主站会话刷新接口,续期当前企业凭据的 AccessToken。
### 第三方免密/协助链接一键导入 (`corps add-link` / `auth add-link`)
```bash
# 直接粘贴企业微信免密、合思代客或协助 thirdparty.html 链接
hose-use corps add-link "https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=...&ekbCorpId=..."
# 可选附加别名与覆盖参数
hose-use corps add-link "<url>" --name="客户企业别名" --overwrite
```
- **全自动识别与身份探测**:
- 自动从 URL 提取服务节点 `baseUrl`、集群环境 `cluster`(如 `wx2`、`app`)、`accessToken` 与 `corpId`;
- 自动向 `$UNITY` JWT 与主站 Session 反查员工工号 (`staffId`)、员工姓名、绑定手机、企业全称与是否企业管理员,无需手动寻找工号;
- 动态自适应多集群环境换票,确保主站单据审批与 EASO 低代码工作流平台权限全绿连通。
### 代客协助凭证导入
```bash
hose-use auth import \
@@ -50,7 +63,7 @@ hose-use auth import \
--staff-id="Cxa3oOtQi2eS$g:2HQbkGx2DgnM00" \
--token="1361c470-3d7c-4a3a-a1fb-e946aee5723b"
```
- **智能探测机制**:若 `corp-id` 包含 `$UNITY` 或特殊字符,系统会自动探测代客服务会话接口,解析 13 位过期毫秒时间戳并正确建立凭证映射。
- **智能探测机制**:若 `corp-id` 包含 `$UNITY` 或特殊字符,系统会自动探测代客服务会话接口,解析 13 位过期毫秒时间戳并正确建立凭证映射。也可直接传入抓包 cURL 或包含 URL 的文本。
### 多账号清单
```bash
+68 -42
View File
@@ -5,6 +5,7 @@ import {
sendSmsVerificationCode,
importCredentials,
importF12Credentials,
importFromLink,
parseHeadersOrCurl,
refreshAccountCorporations,
} from "../../core/auth/login.js";
@@ -35,6 +36,8 @@ export async function handleAuthCommand(
return handleRefresh(parsed, runtime);
case "import":
return handleImport(parsed, runtime);
case "add-link":
return handleAddLink(parsed, runtime);
case "accounts":
return handleAccounts(parsed, runtime);
case "switch-account":
@@ -42,7 +45,7 @@ export async function handleAuthCommand(
default:
return {
stdout: "",
stderr: `未知 auth 子命令: ${action}。支持: login, status, refresh, import, accounts, switch-account\n`,
stderr: `未知 auth 子命令: ${action}。支持: login, status, refresh, import, add-link, accounts, switch-account\n`,
exitCode: 1,
};
}
@@ -231,69 +234,92 @@ async function handleRefresh(parsed: CliParsedArgs, runtime: CliRuntime): Promis
}
async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
let raw = stringOption(parsed.options, ["raw", "headers", "curl"]);
let raw = parsed.args[0] || stringOption(parsed.options, ["raw", "headers", "curl", "url", "link"]);
let accessToken = stringOption(parsed.options, ["token", "accessToken"]);
let corpId = stringOption(parsed.options, ["corp", "corpId"]);
let staffId = stringOption(parsed.options, ["staff", "staffId"]);
let name = stringOption(parsed.options, ["name"]);
const overwrite = booleanOption(parsed.options, ["overwrite", "force", "f"], false);
if (!raw && !accessToken) {
raw = await prompt("请粘贴抓包文本 / cURL 命令行 (直接回车则手动逐项输入): ");
if (!raw && !accessToken && process.stdin.isTTY) {
raw = await prompt("请粘贴抓包文本 / cURL 命令行 / 协助免密 URL (直接回车则手动逐项输入): ");
}
let baseUrl: string | undefined;
if (raw) {
const parsedObj = parseHeadersOrCurl(raw);
if (parsedObj.accessToken) accessToken = parsedObj.accessToken;
if (parsedObj.corpId) corpId = parsedObj.corpId;
if (parsedObj.staffId) staffId = parsedObj.staffId;
if (parsedObj.baseUrl) baseUrl = parsedObj.baseUrl;
}
if (!accessToken) accessToken = await prompt("请输入 accessToken: ");
if (!corpId) corpId = await prompt("请输入 corpId: ");
if (!staffId) staffId = await prompt("请输入 staffId: ");
if (!accessToken && process.stdin.isTTY) accessToken = await prompt("请输入 accessToken: ");
if (!corpId && process.stdin.isTTY) corpId = await prompt("请输入 corpId: ");
if (!accessToken || !corpId || !staffId) {
return { stdout: "", stderr: "accessToken, corpId, staffId 均为必填!\n", exitCode: 1 };
if (!accessToken || !corpId) {
return { stdout: "", stderr: "accessToken 与 corpId 均为必填!\n", exitCode: 1 };
}
const imported = await importCredentials({
accessToken,
corpId,
staffId,
name,
});
try {
const imported = await importCredentials({
accessToken,
corpId,
staffId,
name,
baseUrl,
overwrite,
source: raw && (raw.startsWith("http://") || raw.startsWith("https://")) ? "link" : undefined,
});
if (runtime.jsonMode) {
return { stdout: printJson(imported), stderr: "", exitCode: 0 };
}
const summaryPairs: Record<string, unknown> = {
"企业名称": imported.name,
"企业 ID": imported.id,
"员工工号": imported.credentials.staffId,
"员工姓名": imported.staffName || imported.session?.staffName || "-",
"凭证来源": formatSourceLabel(imported.source),
"过期时间": formatExpiresAt(imported.auth?.expiresAt || imported.session?.expTime),
"保存路径": `enterprises/${imported.id}.json`,
};
if (imported.session?.isAssistPlatform) {
summaryPairs["协助平台"] = "是 (Assist Platform 调试授权)";
if (imported.session.operationUserName || imported.session.operationUserId) {
summaryPairs["协助操作人"] = `${imported.session.operationUserName || ""} (${imported.session.operationUserId || ""})`.trim();
if (runtime.jsonMode) {
return { stdout: printJson(imported, runtime.outputOptions), stderr: "", exitCode: 0 };
}
if (imported.session.assistId) {
summaryPairs["协助会话 ID"] = imported.session.assistId;
const summaryPairs: Record<string, unknown> = {
"企业名称": imported.name,
"企业 ID": imported.id,
"集群环境": imported.cluster || "app",
"员工工号": imported.credentials.staffId,
"员工姓名": imported.staffName || imported.session?.staffName || "-",
"手机号码": imported.session?.cellphone || "-",
"是否管理": imported.session?.isAdmin ? "是" : "否",
"凭证来源": formatSourceLabel(imported.source),
"服务节点": imported.baseUrl,
"过期时间": formatExpiresAt(imported.auth?.expiresAt || imported.session?.expTime),
"保存路径": `enterprises/${imported.id}.json`,
};
if (imported.session?.isAssistPlatform) {
summaryPairs["协助平台"] = "是 (Assist Platform 调试授权)";
if (imported.session.operationUserName || imported.session.operationUserId) {
summaryPairs["协助操作人"] = `${imported.session.operationUserName || ""} (${imported.session.operationUserId || ""})`.trim();
}
if (imported.session.assistId) {
summaryPairs["协助会话 ID"] = imported.session.assistId;
}
}
const summaryText = printKeyValue(summaryPairs);
return {
stdout: `[SUCCESS] 成功导入并保存企业凭证!\n${summaryText}\n`,
stderr: "",
exitCode: 0,
};
} catch (error) {
return {
stdout: "",
stderr: `[ERROR] 导入凭证失败: ${error instanceof Error ? error.message : String(error)}\n`,
exitCode: 1,
};
}
}
const summaryText = printKeyValue(summaryPairs);
return {
stdout: `[SUCCESS] 成功导入并保存企业凭证!\n${summaryText}\n`,
stderr: "",
exitCode: 0,
};
async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const linkUrl = parsed.args[0] || stringOption(parsed.options, ["url", "link"]);
return handleImport({ ...parsed, args: linkUrl ? [linkUrl] : [] }, runtime);
}
async function handleAccounts(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
+81
View File
@@ -0,0 +1,81 @@
import { describe, it, expect } from "bun:test";
import { parseHeadersOrCurl } from "../../core/auth/login.js";
import { resolveCorpCluster } from "../../core/auth/easo.js";
import { handleCorpsCommand } from "./corps.js";
import type { CliRuntime } from "../types.js";
describe("core/auth/login > parseHeadersOrCurl & URL link parsing", () => {
it("successfully parses standard thirdparty.html assistance links", () => {
const url = "https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=token123&ekbCorpId=corpABC&pageType=home";
const parsed = parseHeadersOrCurl(url);
expect(parsed.baseUrl).toBe("https://wx2.ekuaibao.com");
expect(parsed.accessToken).toBe("token123");
expect(parsed.corpId).toBe("corpABC");
});
it("extracts custom staffId and standard corpId query params", () => {
const url = "https://app.ekuaibao.com/thirdparty.html?token=secret999&corpId=corpXYZ&staffId=corpXYZ:user1";
const parsed = parseHeadersOrCurl(url);
expect(parsed.baseUrl).toBe("https://app.ekuaibao.com");
expect(parsed.accessToken).toBe("secret999");
expect(parsed.corpId).toBe("corpXYZ");
expect(parsed.staffId).toBe("corpXYZ:user1");
});
it("handles curl command lines with assistance URL", () => {
const curl = `curl "https://wx.ekuaibao.com/web/thirdparty.html?accessToken=testToken&ekbCorpId=testCorp" -H "User-Agent: Mozilla"`;
const parsed = parseHeadersOrCurl(curl);
expect(parsed.baseUrl).toBe("https://wx.ekuaibao.com");
expect(parsed.accessToken).toBe("testToken");
expect(parsed.corpId).toBe("testCorp");
});
});
describe("core/auth/easo > resolveCorpCluster", () => {
it("prioritizes explicit cluster config", () => {
expect(resolveCorpCluster({ cluster: "wx2", baseUrl: "https://app.ekuaibao.com" })).toBe("wx2");
});
it("extracts cluster from hostname subdomain", () => {
expect(resolveCorpCluster({ baseUrl: "https://wx2.ekuaibao.com" })).toBe("wx2");
expect(resolveCorpCluster({ baseUrl: "https://wx.ekuaibao.com" })).toBe("wx");
expect(resolveCorpCluster({ baseUrl: "https://app.ekuaibao.com" })).toBe("app");
});
it("falls back to app when unknown", () => {
expect(resolveCorpCluster({})).toBe("app");
expect(resolveCorpCluster({ baseUrl: "https://custom-domain.com" })).toBe("app");
});
});
describe("cli/commands/corps > handleCorpsCommand add-link", () => {
const dummyRuntime: CliRuntime = {
corpContext: {
listCorps: () => [],
getCurrent: () => null,
switchCorp: () => false,
resolve: () => null,
} as any,
selectedCorp: null,
jsonMode: false,
};
it("returns error exit code when no link URL is provided", async () => {
const res = await handleCorpsCommand(
{
area: "corps",
action: "add-link",
args: [],
options: {},
raw: ["corps", "add-link"],
},
dummyRuntime
);
expect(res.exitCode).toBe(1);
expect(res.stderr).toContain("必须提供协助/免密链接 URL");
});
});
+73 -1
View File
@@ -1,3 +1,6 @@
import { importFromLink } from "../../core/auth/login.js";
import { stringOption, booleanOption } from "../parser.js";
import { prompt } from "../helpers.js";
import { printJson, printKeyValue, printTable, formatSourceLabel, formatExpiresAt } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
@@ -15,10 +18,12 @@ export async function handleCorpsCommand(
return handleSwitch(parsed, runtime);
case "current":
return handleCurrent(parsed, runtime);
case "add-link":
return handleAddLink(parsed, runtime);
default:
return {
stdout: "",
stderr: `未知 corps 子命令: ${action}。支持: list, switch, current\n`,
stderr: `未知 corps 子命令: ${action}。支持: list, switch, current, add-link\n`,
exitCode: 1,
};
}
@@ -148,3 +153,70 @@ async function handleCurrent(parsed: CliParsedArgs, runtime: CliRuntime): Promis
exitCode: 0,
};
}
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);
if (!linkUrl && process.stdin.isTTY) {
linkUrl = await prompt("请输入第三方协助/免密登录链接 URL: ");
}
if (!linkUrl) {
return {
stdout: "",
stderr: "错误:必须提供协助/免密链接 URL!用法: hose-use corps add-link <url> [--name <企业别名>] [--overwrite]\n",
exitCode: 1,
};
}
try {
const corp = await importFromLink(linkUrl, {
name,
overwrite,
});
if (runtime.jsonMode) {
return { stdout: printJson(corp, runtime.outputOptions), stderr: "", exitCode: 0 };
}
const summaryPairs: Record<string, unknown> = {
"企业名称": corp.name,
"企业 ID": corp.id,
"集群环境": corp.cluster || "app",
"员工工号": corp.credentials.staffId,
"员工姓名": corp.staffName || corp.session?.staffName || "-",
"手机号码": corp.session?.cellphone || "-",
"是否管理": corp.session?.isAdmin ? "是" : "否",
"凭证来源": formatSourceLabel(corp.source),
"服务节点": corp.baseUrl,
"过期时间": formatExpiresAt(corp.auth?.expiresAt || corp.session?.expTime),
"保存路径": `enterprises/${corp.id}.json`,
};
if (corp.session?.isAssistPlatform) {
summaryPairs["协助平台"] = "是 (Assist Platform 调试授权)";
if (corp.session.operationUserName || corp.session.operationUserId) {
summaryPairs["协助操作人"] = `${corp.session.operationUserName || ""} (${corp.session.operationUserId || ""})`.trim();
}
if (corp.session.assistId) {
summaryPairs["协助会话 ID"] = corp.session.assistId;
}
}
const summaryText = printKeyValue(summaryPairs);
return {
stdout: `[SUCCESS] 成功导入并保存企业凭证!\n${summaryText}\n`,
stderr: "",
exitCode: 0,
};
} catch (error) {
return {
stdout: "",
stderr: `[ERROR] 导入协助链接失败: ${error instanceof Error ? error.message : String(error)}\n`,
exitCode: 1,
};
}
}
+47 -32
View File
@@ -1,4 +1,5 @@
import { createClientsForCorp } from "../helpers.js";
import { createEkbClient } from "../../core/auth/ekb.js";
import { getEasoClient } from "../../core/auth/easo.js";
import * as api from "../../domains/platform/api.js";
import { printJson, printKeyValue, formatSourceLabel, formatExpiresAt } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
@@ -30,49 +31,63 @@ export async function handleProbeCommand(
platformAccess: { status: "pending" },
};
// 1. 独立测试 EKB 主站 Session
let ekbClient: Awaited<ReturnType<typeof createEkbClient>> | null = null;
try {
const clients = await createClientsForCorp(currentCorp);
ekbClient = await createEkbClient(currentCorp);
const sessionRes = await ekbClient
.get("api/account/v2/session")
.json<{ value?: { userId?: string; loginStaffId?: string; expTime?: number } }>();
// 1. 测试 EKB 主站 Session
results.ekbSession = {
status: "ok",
userId: sessionRes.value?.userId,
loginStaffId: sessionRes.value?.loginStaffId,
expTime: sessionRes.value?.expTime ? new Date(sessionRes.value.expTime).toLocaleString() : undefined,
};
} catch (e) {
results.ekbSession = {
status: "error",
error: e instanceof Error ? e.message : String(e),
};
}
// 2. 独立测试自建应用列表访问
let platforms: any[] = [];
if (ekbClient) {
try {
const sessionRes = await clients.ekbClient
.get("api/account/v2/session")
.json<{ value?: { userId?: string; loginStaffId?: string; expTime?: number } }>();
results.ekbSession = {
status: "ok",
userId: sessionRes.value?.userId,
loginStaffId: sessionRes.value?.loginStaffId,
expTime: sessionRes.value?.expTime ? new Date(sessionRes.value.expTime).toLocaleString() : undefined,
};
} catch (e) {
results.ekbSession = {
status: "error",
error: e instanceof Error ? e.message : String(e),
};
}
// 2. 测试 EASO Token 换取
try {
const platforms = await api.listPlatforms(clients.ekbClient, currentCorp.credentials.corpId);
platforms = await api.listPlatforms(ekbClient, currentCorp.credentials.corpId);
results.platformAccess = {
status: "ok",
totalPlatforms: platforms.length,
};
const stats = await api.getWorkflowStats(clients.easoClient, platforms[0]?.id || "platform");
results.easoToken = {
status: "ok",
message: "EASO 四步换票握手成功",
};
} catch (e) {
results.easoToken = {
results.platformAccess = {
status: "error",
error: e instanceof Error ? e.message : String(e),
};
}
} catch (error) {
results.error = error instanceof Error ? error.message : String(error);
} else {
results.platformAccess = {
status: "error",
error: "主站客户端未能初始化",
};
}
// 3. 独立测试 EASO Token 换取
try {
const { client: easoClient } = await getEasoClient(currentCorp);
const targetPlatformId = platforms[0]?.id || currentCorp.credentials.corpId;
await api.getWorkflowStats(easoClient, targetPlatformId);
results.easoToken = {
status: "ok",
message: "EASO 四步换票握手成功",
};
} catch (e) {
results.easoToken = {
status: "error",
error: e instanceof Error ? e.message : String(e),
};
}
if (runtime.jsonMode) {
+3 -1
View File
@@ -46,6 +46,8 @@ export function formatSourceLabel(source?: string): string {
return "统一认证中心 (IDP 账密/短信)";
case "browser":
return "浏览器会话同步 (WebBridge)";
case "link":
return "协助/免密链接导入 (Assistance Link)";
case "curl":
case "f12":
return "cURL 抓包导入 (cURL/F12)";
@@ -56,7 +58,7 @@ export function formatSourceLabel(source?: string): string {
}
}
export function formatExpiresAt(expiresAt?: number): string {
export function formatExpiresAt(expiresAt?: number | null): string {
if (!expiresAt || expiresAt <= 0) return "长期有效 / 服务端未显式限制";
const diffMs = expiresAt - Date.now();
const dateStr = new Date(expiresAt).toLocaleString("zh-CN", { hour12: false });
+28 -6
View File
@@ -7,6 +7,22 @@ const EASO_BASE_URL = "https://unity.ekuaibao.com";
const BUSINESS_CENTER_URL = "https://business-center.ekuaibao.com";
const EKB_BASE_URL = "https://app.ekuaibao.com";
export function resolveCorpCluster(corp: { cluster?: string; baseUrl?: string }): string {
if (corp.cluster && corp.cluster.trim()) {
return corp.cluster.trim();
}
if (corp.baseUrl) {
try {
const url = new URL(corp.baseUrl);
const match = /^([a-z0-9-]+)\.ekuaibao\.com$/i.exec(url.hostname);
if (match && match[1]) {
return match[1].toLowerCase();
}
} catch {}
}
return "app";
}
// 内存缓存
const easoMemoryCache = new Map<
string,
@@ -19,14 +35,15 @@ function isExpired(entry: { expiresAt: number }, refreshTtl: number): boolean {
async function fetchHoseToken(
accessToken: string,
corpId: string
corpId: string,
environment: string = "app"
): Promise<string> {
const response = await ky
.get(`${BUSINESS_CENTER_URL}/auth/oauth2/grant/ekb/accessToken`, {
searchParams: {
corpId,
ekbAccessToken: accessToken,
environment: "app",
environment,
},
})
.json<{ data: string }>();
@@ -39,10 +56,11 @@ async function fetchHoseToken(
async function fetchUnityJwt(
accessToken: string,
corpId: string,
staffId: string
staffId: string,
baseUrl: string = EKB_BASE_URL
): Promise<string> {
const response = await ky
.get(`${EKB_BASE_URL}/api/engine/realm/$UNITY/actions/jwt`, {
.get(`${baseUrl}/api/engine/realm/$UNITY/actions/jwt`, {
searchParams: { corpId },
headers: {
accesstoken: accessToken,
@@ -106,16 +124,20 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
const corpId = corp.corpId || corp.credentials.corpId;
const staffId = corp.staffId || corp.credentials.staffId;
const environment = resolveCorpCluster(corp);
const baseUrl = corp.baseUrl || EKB_BASE_URL;
// 重新换取
const hoseToken = await fetchHoseToken(
corp.credentials.accessToken,
corpId
corpId,
environment
);
const unityJwt = await fetchUnityJwt(
corp.credentials.accessToken,
corpId,
staffId
staffId,
baseUrl
);
const easoToken = await fetchEasoRealmToken(
corpId,
+174 -61
View File
@@ -1,8 +1,11 @@
import crypto from "crypto";
import ky from "ky";
import { existsSync } from "node:fs";
import { join } from "node:path";
import { AuthenticationError } from "../errors.js";
import { CorpConfig } from "../config/types.js";
import { saveCorpConfig, saveMultipleCorpConfigs } from "../config/loader.js";
import { saveCorpConfig, saveMultipleCorpConfigs, resolveWritableEnterprisesDir } from "../config/loader.js";
import { resolveCorpCluster } from "./easo.js";
import {
saveAccount,
getAccount,
@@ -221,10 +224,20 @@ export async function syncFromBrowserSession(
export interface F12ImportParams {
accessToken: string;
corpId: string;
staffId: string;
staffId?: string;
name?: string;
baseUrl?: string;
cluster?: string;
source?: import("../config/types.js").CredentialSource;
enterprisesDir?: string;
overwrite?: boolean;
}
export interface ImportFromLinkOptions {
name?: string;
baseUrl?: string;
enterprisesDir?: string;
overwrite?: boolean;
}
/**
@@ -234,6 +247,26 @@ export function parseHeadersOrCurl(rawInput: string): Partial<F12ImportParams> {
const result: Partial<F12ImportParams> = {};
if (!rawInput) return result;
// 0. 尝试匹配完整 URL(包含 http:// 或 https://)
const urlMatch = /(https?:\/\/[^\s"'<>]+)/i.exec(rawInput);
if (urlMatch) {
try {
const parsedUrl = new URL(urlMatch[1]);
result.baseUrl = `${parsedUrl.protocol}//${parsedUrl.host}`;
const tokenParam =
parsedUrl.searchParams.get("accessToken") ||
parsedUrl.searchParams.get("token");
if (tokenParam) result.accessToken = tokenParam;
const corpParam =
parsedUrl.searchParams.get("ekbCorpId") ||
parsedUrl.searchParams.get("corpId") ||
parsedUrl.searchParams.get("corporationId");
if (corpParam) result.corpId = corpParam;
const staffParam = parsedUrl.searchParams.get("staffId");
if (staffParam) result.staffId = staffParam;
} catch {}
}
// 1. 尝试匹配各种 -H / --header 参数:-H 'header: value' 或 -H "header: value"
const headerRegex = /(?:-H|--header)\s+['"]([^'"]+)['"]/gi;
let match: RegExpExecArray | null;
@@ -263,13 +296,25 @@ export function parseHeadersOrCurl(rawInput: string): Partial<F12ImportParams> {
}
}
// 3. 从 URL 中提取 query 参数(例如 ?corpId=xxx 或 &corpId=xxx)
// 3. 从 URL/Query 中提取 query 参数(例如 ?corpId=xxx 或 &corpId=xxx 或 ekbCorpId=xxx)
if (!result.corpId) {
const urlCorpMatch = /(?:[?&]corpId=)([^&'"\s]+)/i.exec(rawInput);
const urlCorpMatch = /(?:[?&](?:ekbCorpId|corpId|corporationId)=)([^&'"\s]+)/i.exec(rawInput);
if (urlCorpMatch) {
result.corpId = decodeURIComponent(urlCorpMatch[1]);
}
}
if (!result.accessToken) {
const urlTokenMatch = /(?:[?&](?:accessToken|token)=)([^&'"\s]+)/i.exec(rawInput);
if (urlTokenMatch) {
result.accessToken = decodeURIComponent(urlTokenMatch[1]);
}
}
if (!result.staffId) {
const urlStaffMatch = /(?:[?&]staffId=)([^&'"\s]+)/i.exec(rawInput);
if (urlStaffMatch) {
result.staffId = decodeURIComponent(urlStaffMatch[1]);
}
}
// 4. 从 Cookie (-b / Cookie header) 中提取 ekb-access-token 或 corpId
if (!result.accessToken) {
@@ -294,14 +339,76 @@ export function parseHeadersOrCurl(rawInput: string): Partial<F12ImportParams> {
export async function importCredentials(
params: F12ImportParams
): Promise<CorpConfig> {
const { accessToken, corpId, staffId } = params;
const { accessToken, corpId } = params;
let staffId = params.staffId;
const baseUrl = params.baseUrl || DEFAULT_EKB_BASE_URL;
if (!accessToken || !corpId || !staffId) {
throw new AuthenticationError("导入凭证失败:accessToken、corpId、staffId 均为必填项");
if (!accessToken || !corpId) {
throw new AuthenticationError("导入凭证失败:accessToken 与 corpId 均为必填项");
}
// 1. 验证凭证有效性并提取官方服务端 Session 元数据
// 检查已存在保护:当明确要求不覆盖 (overwrite === false) 且文件已存在时拦截
const targetDir = params.enterprisesDir || resolveWritableEnterprisesDir();
const targetFile = join(targetDir, `${corpId}.json`);
if (params.overwrite === false && existsSync(targetFile)) {
throw new AuthenticationError(`企业 [${corpId}] 配置文件已存在。若要更新覆盖,请附加 --overwrite 参数。`);
}
// 1. 若 staffId 缺失,优先通过 $UNITY JWT 自动探测 staffId、企业名与身份
let corpName = params.name;
let staffName: string | undefined;
let cellphone: string | undefined;
let isAdmin: boolean | undefined;
let sourceChannel: string | undefined;
let jwtExpMs: number | undefined;
try {
const jwtHeaders: Record<string, string> = {
accesstoken: accessToken,
corpid: corpId,
};
if (staffId) {
jwtHeaders.staffid = staffId;
}
const jwtRes = await ky
.get(`${baseUrl}/api/engine/realm/$UNITY/actions/jwt`, {
searchParams: { corpId },
headers: jwtHeaders,
})
.json<{ id?: string; value?: string }>();
const token = jwtRes.id || jwtRes.value;
if (token) {
const parts = token.split(".");
if (parts.length >= 2) {
const payload = JSON.parse(Buffer.from(parts[1], "base64").toString("utf-8"));
if (!staffId && payload.staffId) {
staffId = payload.staffId;
}
if (!corpName && payload.corporationName) {
corpName = payload.corporationName;
}
if (payload.staffName) {
staffName = payload.staffName;
}
if (payload.cellphone) {
cellphone = payload.cellphone;
}
if (payload.isAdmin !== undefined) {
isAdmin = payload.isAdmin === "true" || payload.isAdmin === true;
}
if (payload.sourceChannel) {
sourceChannel = payload.sourceChannel;
}
if (payload.exp) {
jwtExpMs = Number(payload.exp) * 1000;
}
}
}
} catch {
// 探测失败则继续后续降级流程
}
// 2. 验证凭证有效性并提取官方服务端 Session 元数据
let sessionData: {
id?: string;
userId?: string;
@@ -321,13 +428,16 @@ export async function importCredentials(
} | undefined;
try {
const sessionHeaders: Record<string, string> = {
accesstoken: accessToken,
corpid: corpId,
};
if (staffId) {
sessionHeaders.staffid = staffId;
}
const res = await ky
.get(`${baseUrl}/api/account/v2/session`, {
headers: {
accesstoken: accessToken,
corpid: corpId,
staffid: staffId,
},
headers: sessionHeaders,
})
.json<{
value?: {
@@ -353,60 +463,31 @@ export async function importCredentials(
if (!sessionData || (!sessionData.corporationId && !sessionData.id && !sessionData.userId)) {
throw new Error("服务端未返回有效 Session");
}
if (!staffId && sessionData.loginStaffId) {
staffId = sessionData.loginStaffId;
}
if (!staffName && sessionData.privilege) {
staffName = sessionData.privilege;
}
} catch (err) {
throw new AuthenticationError(`凭证校验失败,请检查 token 是否已过期: ${err instanceof Error ? err.message : String(err)}`);
}
// 2. 尝试通过 $UNITY JWT 获取真实企业名称与员工详细信息 (如果未手动指定)
let corpName = params.name;
let staffName = sessionData?.privilege;
let cellphone: string | undefined;
let isAdmin: boolean | undefined;
let sourceChannel: string | undefined;
let jwtExpMs: number | undefined;
// 兜底 staffId:若依然为空,退化为 corpId:admin
if (!staffId) {
staffId = `${corpId}:admin`;
}
try {
const jwtRes = await ky
.get(`${baseUrl}/api/engine/realm/$UNITY/actions/jwt`, {
searchParams: { corpId },
headers: {
accesstoken: accessToken,
corpid: corpId,
staffid: staffId,
},
})
.json<{ id?: string; value?: string }>();
const token = jwtRes.id || jwtRes.value;
if (token) {
const parts = token.split(".");
if (parts.length >= 2) {
const payload = JSON.parse(Buffer.from(parts[1], "base64").toString("utf-8"));
if (!corpName && payload.corporationName) {
corpName = payload.corporationName;
}
if (payload.staffName) {
staffName = payload.staffName;
}
if (payload.cellphone) {
cellphone = payload.cellphone;
}
if (payload.isAdmin !== undefined) {
isAdmin = payload.isAdmin === "true" || payload.isAdmin === true;
}
if (payload.exp) {
jwtExpMs = Number(payload.exp) * 1000;
}
}
// 3. 智能判断语义化凭证来源与集群环境
let source: import("../config/types.js").CredentialSource = params.source || "curl";
if (!params.source) {
if (sessionData?.isAssistPlatform || sessionData?.platform === "ASSIST") {
source = "assist";
}
} catch {
// 忽略尝试获取企业名失败
}
// 3. 智能判断语义化凭证来源
let source: import("../config/types.js").CredentialSource = "curl";
if (sessionData?.isAssistPlatform || sessionData?.platform === "ASSIST") {
source = "assist";
}
const cluster = params.cluster || resolveCorpCluster({ cluster: params.cluster, baseUrl });
// 4. 计算 Token 过期时间戳 (ms)
let expiresAt: number | undefined;
@@ -414,8 +495,8 @@ export async function importCredentials(
expiresAt = sessionData.expTime;
} else if (jwtExpMs && jwtExpMs > 0) {
expiresAt = jwtExpMs;
} else if (sessionData?.isAssistPlatform && sessionData?.loginTime) {
// 协助平台短期调试 Token 通常 2 小时有效
} else if ((sessionData?.isAssistPlatform || source === "link") && sessionData?.loginTime) {
// 协助/免密平台短期调试 Token 通常 2 小时有效
expiresAt = sessionData.loginTime + 2 * 3600 * 1000;
}
@@ -423,6 +504,7 @@ export async function importCredentials(
id: corpId,
name: corpName || `企业-${corpId}`,
baseUrl,
cluster,
source,
staffName,
credentials: {
@@ -456,6 +538,37 @@ export async function importCredentials(
return corpConfig;
}
/**
* 直接通过第三方协助/免密链接 (thirdparty.html / assistance link) 一键导入企业
*/
export async function importFromLink(
linkUrl: string,
options: ImportFromLinkOptions = {}
): Promise<CorpConfig> {
const parsed = parseHeadersOrCurl(linkUrl);
const accessToken = parsed.accessToken;
const corpId = parsed.corpId;
const baseUrl = options.baseUrl || parsed.baseUrl || DEFAULT_EKB_BASE_URL;
if (!accessToken) {
throw new AuthenticationError("未能从提供的链接中提取到 accessToken 参数");
}
if (!corpId) {
throw new AuthenticationError("未能从提供的链接中提取到 ekbCorpId 或 corpId 参数");
}
return await importCredentials({
accessToken,
corpId,
staffId: parsed.staffId,
name: options.name,
baseUrl,
enterprisesDir: options.enterprisesDir,
overwrite: options.overwrite,
source: "link",
});
}
// 保持历史命名兼容
export const importF12Credentials = importCredentials;
+13 -6
View File
@@ -2,6 +2,7 @@ import ky from "ky";
import { CorpConfig } from "../../core/config/types.js";
import { createAuthClient } from "../../core/http/factory.js";
import { AuthenticationError } from "../../core/errors.js";
import { resolveCorpCluster } from "./easo.js";
const PIPER_BASE_URL = "https://piper.ekuaibao.com";
const BUSINESS_CENTER_URL = "https://business-center.ekuaibao.com";
@@ -19,14 +20,15 @@ function isExpired(entry: { expiresAt: number }, refreshTtl: number): boolean {
async function fetchHoseToken(
accessToken: string,
corpId: string
corpId: string,
environment: string = "app"
): Promise<string> {
const response = await ky
.get(`${BUSINESS_CENTER_URL}/auth/oauth2/grant/ekb/accessToken`, {
searchParams: {
corpId,
ekbAccessToken: accessToken,
environment: "app",
environment,
},
})
.json<{ data: string }>();
@@ -39,10 +41,11 @@ async function fetchHoseToken(
async function fetchEasoJwt(
accessToken: string,
corpId: string,
staffId: string
staffId: string,
baseUrl: string = EKB_BASE_URL
): Promise<string> {
const response = await ky
.get(`${EKB_BASE_URL}/api/engine/realm/$EASO/actions/jwt`, {
.get(`${baseUrl}/api/engine/realm/$EASO/actions/jwt`, {
searchParams: { corpId },
headers: {
accesstoken: accessToken,
@@ -82,16 +85,20 @@ export async function getPiperClient(
const corpId = corp.corpId || corp.credentials.corpId;
const staffId = corp.staffId || corp.credentials.staffId;
const environment = resolveCorpCluster(corp);
const baseUrl = corp.baseUrl || EKB_BASE_URL;
// 重新换取
const hoseToken = await fetchHoseToken(
corp.credentials.accessToken,
corpId
corpId,
environment
);
const easoJwt = await fetchEasoJwt(
corp.credentials.accessToken,
corpId,
staffId
staffId,
baseUrl
);
const entry = {
+1 -1
View File
@@ -152,7 +152,7 @@ export class CorpContext {
staffId: corp.credentials.staffId,
baseUrl: corp.baseUrl,
current: corp.id === this.current?.id,
expiresAt: corp.auth?.expiresAt || corp.session?.expTime,
expiresAt: corp.auth?.expiresAt || (corp.session?.expTime ?? undefined),
}));
}
}
+17 -15
View File
@@ -4,6 +4,7 @@ export const CredentialSourceSchema = z.enum([
"account", // 官方统一认证中心 (IDP) 账密/短信登录
"assist", // 官方协助/代客平台 (Assist Platform) 调试授权会话
"browser", // 浏览器会话 / Cookie 同步
"link", // 协助/免密链接导入 (thirdparty.html / assistance link)
"manual", // 手动配置
"curl", // cURL 抓包 / HTTP Headers 导入
"f12", // 兼容旧版抓包标识
@@ -23,20 +24,20 @@ export const CorpAuthConfigSchema = z.object({
});
export const CorpSessionInfoSchema = z.object({
platform: z.string().optional().describe("官方会话平台类型 (如 ASSIST, WEB, MOBILE, OPENAPI)"),
isAssistPlatform: z.boolean().optional().describe("是否为官方协助/代客平台登录"),
isShortTermToken: z.boolean().optional().describe("是否为短期临时 Token"),
assistId: z.string().optional().describe("协助会话/工单 ID"),
operationUserId: z.string().optional().describe("协助操作人 ID (如内部运维/实施账号)"),
operationUserName: z.string().optional().describe("协助操作人姓名"),
staffName: z.string().optional().describe("当前员工真实姓名"),
cellphone: z.string().optional().describe("绑定手机号"),
isAdmin: z.boolean().optional().describe("是否管理员"),
deviceType: z.string().optional().describe("设备类型"),
loginAccountType: z.string().optional().describe("登录账号类型"),
loginTime: z.number().optional().describe("登录时间戳 (ms)"),
expTime: z.number().optional().describe("过期时间戳 (ms)"),
sourceChannel: z.string().optional().describe("来源渠道 (如 APP, WEB)"),
platform: z.string().nullable().optional().describe("官方会话平台类型 (如 ASSIST, WEB, MOBILE, OPENAPI)"),
isAssistPlatform: z.boolean().nullable().optional().describe("是否为官方协助/代客平台登录"),
isShortTermToken: z.boolean().nullable().optional().describe("是否为短期临时 Token"),
assistId: z.string().nullable().optional().describe("协助会话/工单 ID"),
operationUserId: z.string().nullable().optional().describe("协助操作人 ID (如内部运维/实施账号)"),
operationUserName: z.string().nullable().optional().describe("协助操作人姓名"),
staffName: z.string().nullable().optional().describe("当前员工真实姓名"),
cellphone: z.string().nullable().optional().describe("绑定手机号"),
isAdmin: z.boolean().nullable().optional().describe("是否管理员"),
deviceType: z.string().nullable().optional().describe("设备类型"),
loginAccountType: z.string().nullable().optional().describe("登录账号类型"),
loginTime: z.number().nullable().optional().describe("登录时间戳 (ms)"),
expTime: z.number().nullable().optional().describe("过期时间戳 (ms)"),
sourceChannel: z.string().nullable().optional().describe("来源渠道 (如 APP, WEB)"),
});
export type CorpSessionInfo = z.infer<typeof CorpSessionInfoSchema>;
@@ -48,7 +49,8 @@ export const CorpConfigSchema = z.object({
staffId: z.string().optional().describe("员工工号 (默认取 credentials.staffId)"),
staffName: z.string().optional().describe("员工真实姓名"),
baseUrl: z.string().url().optional().default("https://app.ekuaibao.com"),
source: CredentialSourceSchema.optional().default("manual").describe("凭证来源: account/assist/browser/manual/curl/f12"),
cluster: z.string().optional().describe("企业部署集群 (如 app, wx2, wx)"),
source: CredentialSourceSchema.optional().default("manual").describe("凭证来源: account/assist/browser/link/manual/curl/f12"),
accountId: z.string().optional().describe("所属主账号标识(如手机号)"),
credentials: CorpCredentialsSchema,
auth: CorpAuthConfigSchema.optional(),