feat(auth): 完善多账号与企业分层管理模型,全面支持 F12/cURL 临时凭证导入与一键保活

This commit is contained in:
gitea committed 2026-08-27 10:49:20 +08:00
1 parent 255c7aee8d
commit 3d549e2e2f
8 files changed
+749 -155

No files matched your search

+7 -5
View File
@@ -7,11 +7,13 @@ Core 层负责基础设施:企业配置管理、认证 Token 获取与缓存
```text
src/core/
├── auth/ # 登录认证与 Token 获取、刷新、缓存
│ ├── login.ts # 登录三矩阵(RSA账密登录、短信验证码登录、浏览器同步)
│ ├── ekb.ts # 快报主站三 Header 认证
│ ├── easo.ts # EASO(unity.ekuaibao.com)四步认证
│ ├── piper.ts # Piper(piper.ekuaibao.com)三步认证
│ ├── token-store.ts # 持久化 Token 缓存(~/.cache/ekb-mcp/tokens.json)
│ ├── login.ts # 登录四矩阵(RSA账密登录、短信验证码、F12/cURL凭证导入、浏览器同步)
│ ├── account-store.ts # 多账号持久化存储 (~/.cache/ekb-mcp/accounts.json)
│ ├── tools.ts # MCP Auth Tools 注册与调度
│ ├── ekb.ts # 快报主站三 Header 认证
│ ├── easo.ts # EASO(unity.ekuaibao.com)四步认证
│ ├── piper.ts # Piper(piper.ekuaibao.com)三步认证
│ ├── token-store.ts # 动态 Token 缓存(~/.cache/ekb-mcp/tokens.json)
│ └── types.ts
├── config/ # 企业配置管理
│ ├── loader.ts
+105
View File
@@ -0,0 +1,105 @@
import { readFileSync, writeFileSync, mkdirSync } from "fs";
import { join, dirname } from "path";
import { homedir } from "os";
import { z } from "zod";
const ACCOUNT_CACHE_PATH = join(
homedir(),
".cache",
"ekb-mcp",
"accounts.json"
);
export const AccountCorporationMetaSchema = z.object({
id: z.string(),
name: z.string(),
staffId: z.string(),
cluster: z.string().optional().default("app"),
baseUrl: z.string().optional().default("https://app.ekuaibao.com"),
});
export const AccountEntrySchema = z.object({
accountId: z.string().describe("账号唯一标识(如手机号)"),
userId: z.string().optional().describe("用户唯一 ID"),
cloudAuthToken: z.string().optional().describe("业务中心会话凭证"),
activeCorpId: z.string().optional().describe("当前选中的默认企业 ID"),
createdAt: z.number().default(() => Date.now()),
updatedAt: z.number().default(() => Date.now()),
corporations: z.array(AccountCorporationMetaSchema).default([]),
});
export const AccountStoreSchema = z.object({
activeAccountId: z.string().optional(),
accounts: z.record(z.string(), AccountEntrySchema).default({}),
});
export type AccountCorporationMeta = z.infer<typeof AccountCorporationMetaSchema>;
export type AccountEntry = z.infer<typeof AccountEntrySchema>;
export type AccountStore = z.infer<typeof AccountStoreSchema>;
function ensureDir(path: string): void {
mkdirSync(dirname(path), { recursive: true });
}
export function loadAccountStore(): AccountStore {
try {
const content = readFileSync(ACCOUNT_CACHE_PATH, "utf-8");
return AccountStoreSchema.parse(JSON.parse(content));
} catch {
return { accounts: {} };
}
}
export function saveAccountStore(store: AccountStore): void {
ensureDir(ACCOUNT_CACHE_PATH);
writeFileSync(ACCOUNT_CACHE_PATH, JSON.stringify(store, null, 2), "utf-8");
}
export function saveAccount(entry: AccountEntry): void {
const store = loadAccountStore();
store.accounts[entry.accountId] = {
...entry,
updatedAt: Date.now(),
};
if (!store.activeAccountId) {
store.activeAccountId = entry.accountId;
}
saveAccountStore(store);
}
export function getAccount(accountId: string): AccountEntry | undefined {
const store = loadAccountStore();
return store.accounts[accountId];
}
export function listAccounts(): AccountEntry[] {
const store = loadAccountStore();
return Object.values(store.accounts);
}
export function getActiveAccount(): AccountEntry | undefined {
const store = loadAccountStore();
if (store.activeAccountId && store.accounts[store.activeAccountId]) {
return store.accounts[store.activeAccountId];
}
const all = Object.values(store.accounts);
return all[0];
}
export function setActiveAccount(accountId: string): boolean {
const store = loadAccountStore();
if (!store.accounts[accountId]) return false;
store.activeAccountId = accountId;
saveAccountStore(store);
return true;
}
export function deleteAccount(accountId: string): void {
const store = loadAccountStore();
delete store.accounts[accountId];
if (store.activeAccountId === accountId) {
const remaining = Object.keys(store.accounts);
store.activeAccountId = remaining[0];
}
saveAccountStore(store);
}
+179 -9
View File
@@ -3,6 +3,14 @@ import ky from "ky";
import { AuthenticationError } from "../errors.js";
import { CorpConfig } from "../config/types.js";
import { saveCorpConfig, saveMultipleCorpConfigs } from "../config/loader.js";
import {
saveAccount,
getAccount,
listAccounts,
getActiveAccount,
setActiveAccount,
AccountEntry,
} from "./account-store.js";
import {
CorporationItem,
CorporationItemSchema,
@@ -16,6 +24,7 @@ import {
const DEFAULT_BUSINESS_CENTER_URL = "https://business-center.ekuaibao.com";
const DEFAULT_IDP_URL = "https://idp.hosecloud.com";
const DEFAULT_WEBBRIDGE_URL = "http://127.0.0.1:10086";
const DEFAULT_EKB_BASE_URL = "https://app.ekuaibao.com";
// ── 基础工具函数 ─────────────────────────────────────────────────────────────
@@ -207,6 +216,108 @@ export async function syncFromBrowserSession(
}
}
// ── 模式 4:F12 / cURL / 手动直接导入单企业凭证 ───────────────────────────────
export interface F12ImportParams {
accessToken: string;
corpId: string;
staffId: string;
name?: string;
baseUrl?: string;
enterprisesDir?: string;
}
/**
* 解析从 F12 抓包复制出来的 Request Headers、cURL 命令或 URL 字符串
*/
export function parseHeadersOrCurl(rawInput: string): Partial<F12ImportParams> {
const result: Partial<F12ImportParams> = {};
if (!rawInput) return result;
// 1. 尝试匹配各种 -H / --header 参数:-H 'header: value' 或 -H "header: value"
const headerRegex = /(?:-H|--header)\s+['"]([^'"]+)['"]/gi;
let match: RegExpExecArray | null;
while ((match = headerRegex.exec(rawInput)) !== null) {
const headerStr = match[1];
const colonIdx = headerStr.indexOf(":");
if (colonIdx !== -1) {
const key = headerStr.slice(0, colonIdx).trim().toLowerCase().replace(/[^a-z]/g, "");
const val = headerStr.slice(colonIdx + 1).trim();
if (key === "accesstoken") result.accessToken = val;
if (key === "corpid" || key === "corporationid") result.corpId = val;
if (key === "staffid") result.staffId = val;
}
}
// 2. 逐行匹配标准 HTTP Headers (如 accesstoken: xxx)
const lines = rawInput.split("\n");
for (const line of lines) {
const trimmed = line.trim();
const colonIdx = trimmed.indexOf(":");
if (colonIdx !== -1) {
const key = trimmed.slice(0, colonIdx).trim().toLowerCase().replace(/[^a-z]/g, "");
const val = trimmed.slice(colonIdx + 1).trim().replace(/^['"]|['"]$/g, "");
if (key === "accesstoken" && !result.accessToken) result.accessToken = val;
if ((key === "corpid" || key === "corporationid") && !result.corpId) result.corpId = val;
if (key === "staffid" && !result.staffId) result.staffId = val;
}
}
return result;
}
/**
* 校验并导入单个 F12 抓包/手动凭证,保存到企业配置
*/
export async function importF12Credentials(
params: F12ImportParams
): Promise<CorpConfig> {
const { accessToken, corpId, staffId } = params;
const baseUrl = params.baseUrl || DEFAULT_EKB_BASE_URL;
if (!accessToken || !corpId || !staffId) {
throw new AuthenticationError("导入凭证失败:accessToken、corpId、staffId 均为必填项");
}
// 验证凭证有效性并尝试自动获取企业名称
let corpName = params.name;
try {
const res = await ky
.get(`${baseUrl}/api/account/v2/session`, {
headers: {
accesstoken: accessToken,
corpid: corpId,
staffid: staffId,
},
})
.json<{ value?: { corporationId?: string; loginStaffId?: string; expTime?: number } }>();
if (!res.value?.corporationId) {
throw new Error("服务端未返回有效 Session");
}
} catch (err) {
throw new AuthenticationError(`凭证校验失败,请检查 token 是否已过期: ${err instanceof Error ? err.message : String(err)}`);
}
const corpConfig: CorpConfig = {
id: corpId,
name: corpName || `企业-${corpId}`,
baseUrl,
source: "f12",
credentials: {
accessToken,
corpId,
staffId,
},
auth: {
refreshTtl: 300,
},
};
saveCorpConfig(corpConfig, params.enterprisesDir);
return corpConfig;
}
// ── 企业管理与主站 OAuth2 令牌换取 ─────────────────────────────────────────────
/**
@@ -238,6 +349,7 @@ export async function listUserCorporations(
export async function switchCorporationAndExchangeToken(
cloudAuthToken: string,
corp: CorporationItem,
accountId?: string,
idpUrl: string = DEFAULT_IDP_URL,
businessCenterUrl: string = DEFAULT_BUSINESS_CENTER_URL
): Promise<{ accessToken: string; refreshToken?: string; expiresIn: number; corpConfig: CorpConfig }> {
@@ -280,6 +392,8 @@ export async function switchCorporationAndExchangeToken(
id: corp.corporationId,
name: corp.corporationName,
baseUrl: corp.baseUrl || "https://app.ekuaibao.com",
source: "account",
accountId,
credentials: {
accessToken: idpRes.access_token,
corpId: corp.corporationId,
@@ -287,6 +401,8 @@ export async function switchCorporationAndExchangeToken(
},
auth: {
refreshTtl: 300,
refreshToken: idpRes.refresh_token,
expiresAt: Date.now() + idpRes.expires_in * 1000,
},
};
@@ -312,26 +428,29 @@ export interface FullLoginResult {
selectedCorp: CorpConfig;
allCorps: CorpConfig[];
cloudAuthToken: string;
accountId: string;
}
/**
* 账密登录全流程(登录 ➔ 拉取企业 ➔ 换取 Token ➔ 保存配置)
* 账密登录全流程(登录 ➔ 存账号 ➔ 拉取企业 ➔ 换取 Token ➔ 保存配置)
*/
export async function fullPasswordLogin(
params: PasswordLoginParams & FullLoginOptions
): Promise<FullLoginResult> {
const { cloudAuthToken } = await loginByPassword(params);
return exchangeAndSaveCorporations(cloudAuthToken, params);
const accountId = formatAccount(params.phone, params.areaCode);
return exchangeAndSaveCorporations(accountId, cloudAuthToken, params);
}
/**
* 短信验证码登录全流程(提交验证码 ➔ 拉取企业 ➔ 换取 Token ➔ 保存配置)
* 短信验证码登录全流程(提交验证码 ➔ 存账号 ➔ 拉取企业 ➔ 换取 Token ➔ 保存配置)
*/
export async function fullSmsLogin(
params: SmsCodeLoginParams & FullLoginOptions
): Promise<FullLoginResult> {
const { cloudAuthToken } = await loginBySmsCode(params);
return exchangeAndSaveCorporations(cloudAuthToken, params);
const accountId = formatAccount(params.phone, params.areaCode);
return exchangeAndSaveCorporations(accountId, cloudAuthToken, params);
}
/**
@@ -343,14 +462,16 @@ export async function fullBrowserSyncLogin(
const { cloudAuthToken, activeSession } = await syncFromBrowserSession(options);
if (cloudAuthToken) {
return exchangeAndSaveCorporations(cloudAuthToken, options);
const accountId = "browser_session";
return exchangeAndSaveCorporations(accountId, cloudAuthToken, options);
}
if (activeSession) {
const singleCorp: CorpConfig = {
id: activeSession.corpId,
name: "当前企业",
name: "当前浏览器企业",
baseUrl: "https://app.ekuaibao.com",
source: "browser",
credentials: {
accessToken: activeSession.accessToken,
corpId: activeSession.corpId,
@@ -362,6 +483,7 @@ export async function fullBrowserSyncLogin(
selectedCorp: singleCorp,
allCorps: [singleCorp],
cloudAuthToken: "",
accountId: "browser_session",
};
}
@@ -369,9 +491,36 @@ export async function fullBrowserSyncLogin(
}
/**
* 内部统一:根据 cloudAuthToken 批量换票并保存企业配置
* 刷新指定账号下的所有企业 Token
*/
export async function refreshAccountCorporations(
accountId?: string,
options: FullLoginOptions = {}
): Promise<FullLoginResult> {
let account: AccountEntry | undefined;
if (accountId) {
account = getAccount(accountId);
} else {
account = getActiveAccount();
}
if (!account || !account.cloudAuthToken) {
throw new AuthenticationError(
accountId ? `未找到账号 ${accountId} 的登录凭证` : "当前无活跃账号,请先登录"
);
}
return exchangeAndSaveCorporations(account.accountId, account.cloudAuthToken, {
...options,
saveAll: true,
});
}
/**
* 内部统一:根据 cloudAuthToken 批量换票并保存账号与企业配置
*/
async function exchangeAndSaveCorporations(
accountId: string,
cloudAuthToken: string,
options: FullLoginOptions
): Promise<FullLoginResult> {
@@ -380,22 +529,41 @@ async function exchangeAndSaveCorporations(
throw new AuthenticationError("该账号名下未找到任何可用企业");
}
// 确定目标企业
// 1. 确定目标企业
let target = corporations.find((c) => c.corporationId === options.targetCorpId);
if (!target) {
target = corporations[0];
}
// 2. 保存账号根索引到 accounts.json
const accountEntry: AccountEntry = {
accountId,
userId: corporations[0]?.userId,
cloudAuthToken,
activeCorpId: target.corporationId,
createdAt: Date.now(),
updatedAt: Date.now(),
corporations: corporations.map((c) => ({
id: c.corporationId,
name: c.corporationName,
staffId: c.staffId,
cluster: c.cluster,
baseUrl: c.baseUrl,
})),
};
saveAccount(accountEntry);
const allConfigs: CorpConfig[] = [];
let selectedCorpConfig: CorpConfig | null = null;
if (options.saveAll) {
if (options.saveAll !== false) {
// 换取全部企业的 Token 并保存
for (const corp of corporations) {
try {
const { corpConfig } = await switchCorporationAndExchangeToken(
cloudAuthToken,
corp,
accountId,
options.idpUrl,
options.businessCenterUrl
);
@@ -413,6 +581,7 @@ async function exchangeAndSaveCorporations(
const { corpConfig } = await switchCorporationAndExchangeToken(
cloudAuthToken,
target,
accountId,
options.idpUrl,
options.businessCenterUrl
);
@@ -425,5 +594,6 @@ async function exchangeAndSaveCorporations(
selectedCorp: selectedCorpConfig || allConfigs[0],
allCorps: allConfigs,
cloudAuthToken,
accountId,
};
}
+175
View File
@@ -0,0 +1,175 @@
import { z } from "zod";
import { CorpContext } from "../config/manager.js";
import { loadCorpConfigs } from "../config/loader.js";
import {
importF12Credentials,
parseHeadersOrCurl,
refreshAccountCorporations,
} from "./login.js";
import { listAccounts, getActiveAccount } from "./account-store.js";
import { createEkbClient } from "./ekb.js";
// ── Auth Tools 定义 ──────────────────────────────────────────────────────────
export const authTools = [
{
name: "list_corps",
description: "列出当前所有已配置的企业(包括账号关联企业与手动导入企业)",
parameters: z.object({}),
handler: async ({ corpContext }: { corpContext: CorpContext }) => {
return {
activeCorp: corpContext.getCurrent()?.id,
corporations: corpContext.listCorps(),
};
},
},
{
name: "switch_corp",
description: "切换当前活跃企业",
parameters: z.object({
corpId: z.string().describe("目标企业 ID"),
}),
handler: async (
{ corpContext }: { corpContext: CorpContext },
params: { corpId: string }
) => {
const success = corpContext.switchCorp(params.corpId);
if (!success) {
throw new Error(`企业 ${params.corpId} 不存在或未配置`);
}
const current = corpContext.getCurrent();
return {
success: true,
message: `已切换到企业: ${current?.name} (${current?.id})`,
corp: current,
};
},
},
{
name: "whoami",
description: "查看当前操作员身份、当前活跃企业与账号状态",
parameters: z.object({}),
handler: async ({ corpContext }: { corpContext: CorpContext }) => {
const current = corpContext.getCurrent();
if (!current) {
return {
authenticated: false,
message: "未配置任何企业",
activeAccount: getActiveAccount(),
};
}
// 测试当前 Session
let sessionData: unknown = null;
let sessionValid = false;
try {
const client = createEkbClient(current);
const res = await client.get("api/account/v2/session").json<{ value?: unknown }>();
sessionData = res.value;
sessionValid = !!res.value;
} catch (e) {
sessionValid = false;
}
return {
authenticated: sessionValid,
currentCorp: {
id: current.id,
name: current.name,
staffId: current.credentials.staffId,
source: current.source,
accountId: current.accountId,
baseUrl: current.baseUrl,
},
session: sessionData,
};
},
},
{
name: "import_f12_corp",
description: "从网页 F12 抓包(Network / Headers / cURL)直接导入单企业登录凭证",
parameters: z.object({
accessToken: z.string().optional().describe("主站 accessToken"),
corpId: z.string().optional().describe("企业 ID"),
staffId: z.string().optional().describe("员工 ID"),
name: z.string().optional().describe("企业名称(可选)"),
rawHeadersOrCurl: z.string().optional().describe("F12 复制的原始 Headers 文本或 cURL 命令行字符串(自动解析)"),
baseUrl: z.string().optional().describe("站点基础地址,默认 https://app.ekuaibao.com"),
}),
handler: async (
{ corpContext }: { corpContext: CorpContext },
params: {
accessToken?: string;
corpId?: string;
staffId?: string;
name?: string;
rawHeadersOrCurl?: string;
baseUrl?: string;
}
) => {
let accessToken = params.accessToken;
let corpId = params.corpId;
let staffId = params.staffId;
if (params.rawHeadersOrCurl) {
const parsed = parseHeadersOrCurl(params.rawHeadersOrCurl);
if (parsed.accessToken) accessToken = parsed.accessToken;
if (parsed.corpId) corpId = parsed.corpId;
if (parsed.staffId) staffId = parsed.staffId;
}
if (!accessToken || !corpId || !staffId) {
throw new Error("导入失败:必须提供 accessToken, corpId, staffId 或有效的 rawHeadersOrCurl 抓包内容");
}
const importedConfig = await importF12Credentials({
accessToken,
corpId,
staffId,
name: params.name,
baseUrl: params.baseUrl,
});
corpContext.upsertCorp(importedConfig, true);
return {
success: true,
message: `成功导入并保存企业凭证: ${importedConfig.name} (${importedConfig.id})`,
corp: importedConfig,
};
},
},
{
name: "refresh_corps",
description: "通过主账号登录态一键刷新名下所有企业的最新 AccessToken 并重新加载",
parameters: z.object({
accountId: z.string().optional().describe("指定刷新的账号手机号,为空时刷新当前活跃账号"),
}),
handler: async (
{ corpContext }: { corpContext: CorpContext },
params: { accountId?: string }
) => {
const result = await refreshAccountCorporations(params.accountId, { saveAll: true });
const freshCorps = loadCorpConfigs();
corpContext.reload(freshCorps);
return {
success: true,
message: `成功刷新账号 ${result.accountId} 下的所有企业凭证`,
refreshedCount: result.allCorps.length,
corporations: corpContext.listCorps(),
};
},
},
{
name: "list_accounts",
description: "查看本地已保存的所有登录主账号",
parameters: z.object({}),
handler: async () => {
return {
activeAccount: getActiveAccount()?.accountId,
accounts: listAccounts(),
};
},
},
];
+35 -5
View File
@@ -1,15 +1,30 @@
import { CorpConfig } from "./types";
import { CorpConfig } from "./types.js";
export interface CorpSummary {
id: string;
name: string;
source?: string;
accountId?: string;
staffId: string;
baseUrl?: string;
current: boolean;
}
export class CorpContext {
private current: CorpConfig | null = null;
private corps: Map<string, CorpConfig> = new Map();
constructor(corps: CorpConfig[]) {
constructor(corps: CorpConfig[] = []) {
this.reload(corps);
}
reload(corps: CorpConfig[]): void {
this.corps.clear();
for (const corp of corps) {
this.corps.set(corp.id, corp);
}
if (corps.length > 0) {
this.current = corps[0];
if (this.corps.size > 0 && (!this.current || !this.corps.has(this.current.id))) {
this.current = Array.from(this.corps.values())[0];
}
}
@@ -17,6 +32,17 @@ export class CorpContext {
return this.current;
}
getCorp(corpId: string): CorpConfig | undefined {
return this.corps.get(corpId);
}
upsertCorp(corp: CorpConfig, setCurrent: boolean = false): void {
this.corps.set(corp.id, corp);
if (setCurrent || !this.current) {
this.current = corp;
}
}
switchCorp(corpId: string): boolean {
const corp = this.corps.get(corpId);
if (!corp) return false;
@@ -24,10 +50,14 @@ export class CorpContext {
return true;
}
listCorps(): Array<{ id: string; name: string; current: boolean }> {
listCorps(): CorpSummary[] {
return Array.from(this.corps.values()).map((corp) => ({
id: corp.id,
name: corp.name,
source: corp.source || "manual",
accountId: corp.accountId,
staffId: corp.credentials.staffId,
baseUrl: corp.baseUrl,
current: corp.id === this.current?.id,
}));
}
+14 -7
View File
@@ -1,19 +1,26 @@
import { z } from "zod";
export const CredentialSourceSchema = z.enum(["account", "manual", "browser", "f12"]);
export type CredentialSource = z.infer<typeof CredentialSourceSchema>;
export const CorpCredentialsSchema = z.object({
accessToken: z.string(),
corpId: z.string(),
staffId: z.string(),
accessToken: z.string().describe("主站访问令牌"),
corpId: z.string().describe("企业 ID"),
staffId: z.string().describe("员工 ID"),
});
export const CorpAuthConfigSchema = z.object({
refreshTtl: z.number().default(300), // 提前多少秒刷新,默认 5 分钟
refreshTtl: z.number().default(300).describe("提前多少秒刷新,默认 5 分钟"),
refreshToken: z.string().optional().describe("OAuth2 Refresh Token"),
expiresAt: z.number().optional().describe("AccessToken 到期时间戳 (ms)"),
});
export const CorpConfigSchema = z.object({
id: z.string(),
name: z.string(),
baseUrl: z.string().url().optional(), // 默认 https://app.ekuaibao.com
id: z.string().describe("企业 ID"),
name: z.string().describe("企业名称"),
baseUrl: z.string().url().optional().default("https://app.ekuaibao.com"),
source: CredentialSourceSchema.optional().default("manual").describe("凭证来源: account/manual/browser/f12"),
accountId: z.string().optional().describe("所属主账号标识(如手机号)"),
credentials: CorpCredentialsSchema,
auth: CorpAuthConfigSchema.optional(),
});