From 3d549e2e2f92a507f640403ff58079a27d608d6d Mon Sep 17 00:00:00 2001 From: yunyingk Date: Thu, 27 Aug 2026 10:49:20 +0800 Subject: [PATCH] =?UTF-8?q?feat(auth):=20=E5=AE=8C=E5=96=84=E5=A4=9A?= =?UTF-8?q?=E8=B4=A6=E5=8F=B7=E4=B8=8E=E4=BC=81=E4=B8=9A=E5=88=86=E5=B1=82?= =?UTF-8?q?=E7=AE=A1=E7=90=86=E6=A8=A1=E5=9E=8B=EF=BC=8C=E5=85=A8=E9=9D=A2?= =?UTF-8?q?=E6=94=AF=E6=8C=81=20F12/cURL=20=E4=B8=B4=E6=97=B6=E5=87=AD?= =?UTF-8?q?=E8=AF=81=E5=AF=BC=E5=85=A5=E4=B8=8E=E4=B8=80=E9=94=AE=E4=BF=9D?= =?UTF-8?q?=E6=B4=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/login.ts | 266 ++++++++++++++++++++++++--------- src/core/README.core.md | 12 +- src/core/auth/account-store.ts | 105 +++++++++++++ src/core/auth/login.ts | 188 +++++++++++++++++++++-- src/core/auth/tools.ts | 175 ++++++++++++++++++++++ src/core/config/manager.ts | 40 ++++- src/core/config/types.ts | 21 ++- src/server.ts | 97 +++++------- 8 files changed, 749 insertions(+), 155 deletions(-) create mode 100644 src/core/auth/account-store.ts create mode 100644 src/core/auth/tools.ts diff --git a/scripts/login.ts b/scripts/login.ts index f0a311a..fa85a51 100644 --- a/scripts/login.ts +++ b/scripts/login.ts @@ -3,8 +3,12 @@ import { fullSmsLogin, fullBrowserSyncLogin, sendSmsVerificationCode, - listUserCorporations, + importF12Credentials, + parseHeadersOrCurl, + refreshAccountCorporations, } from "../src/core/auth/login.js"; +import { listAccounts, getActiveAccount } from "../src/core/auth/account-store.js"; +import { loadCorpConfigs } from "../src/core/config/loader.js"; import readline from "readline"; function prompt(question: string): Promise { @@ -20,92 +24,210 @@ function prompt(question: string): Promise { }); } +async function handleMenu() { + console.log("请选择登录或凭证导入方式:"); + console.log(" [1] 账号密码登录 (RSA 自动加密,自动拉取名下全部企业)"); + console.log(" [2] 手机短信验证码登录"); + console.log(" [3] F12 抓包导入 (粘贴 accessToken/corpId/staffId 或 cURL / Headers)"); + console.log(" [4] 浏览器会话一键同步 (WebBridge)"); + console.log(" [5] 刷新账号名下的所有企业 Token (批量保活)"); + console.log(" [6] 查看当前已配置的账号与企业列表\n"); + + const choice = await prompt("请输入选项序号 [1-6] (默认 1): ") || "1"; + + switch (choice) { + case "1": + return doPasswordLogin(); + case "2": + return doSmsLogin(); + case "3": + return doF12Import(); + case "4": + return doBrowserSync(); + case "5": + return doRefreshAccounts(); + case "6": + return doShowStatus(); + default: + console.error("无效选项"); + } +} + +async function doPasswordLogin(phoneInput?: string, pwdInput?: string) { + const phone = phoneInput || (await prompt("请输入手机号: ")); + const password = pwdInput || (await prompt("请输入密码: ")); + + if (!phone || !password) { + console.error("手机号和密码不能为空"); + return; + } + + console.log("\n正在进行全自动 RSA 账密登录..."); + const result = await fullPasswordLogin({ + phone, + password, + saveAll: true, + }); + + console.log("\n[SUCCESS] 账密登录成功!"); + console.log(`账号标识: ${result.accountId}`); + console.log(`当前激活企业: ${result.selectedCorp.name} (${result.selectedCorp.id})`); + console.log(`共保存企业配置: ${result.allCorps.length} 家`); + result.allCorps.forEach((c, idx) => { + console.log(` ${idx + 1}. [${c.id}] ${c.name} (${c.credentials.staffId})`); + }); +} + +async function doSmsLogin() { + const phone = await prompt("请输入手机号: "); + if (!phone) { + console.error("手机号不能为空"); + return; + } + + console.log(`\n正在向 ${phone} 请求发送短信验证码...`); + let codeId: string | undefined; + try { + const sendRes = await sendSmsVerificationCode({ phone }); + codeId = sendRes.codeId; + console.log("短信验证码已成功发送!"); + } catch (e) { + console.warn("直接发送提示:", e instanceof Error ? e.message : String(e)); + console.log("如果网页端触发了人机验证,请在浏览器中点击获取验证码后在下方输入。"); + } + + const code = await prompt("请输入收到的 6 位短信验证码: "); + if (!code) { + console.error("验证码不能为空"); + return; + } + + console.log("\n正在验证短信验证码并拉取企业..."); + const result = await fullSmsLogin({ + phone, + code, + codeId, + saveAll: true, + }); + + console.log("\n[SUCCESS] 短信验证码登录成功!"); + console.log(`账号标识: ${result.accountId}`); + console.log(`当前激活企业: ${result.selectedCorp.name} (${result.selectedCorp.id})`); + console.log(`共保存企业配置: ${result.allCorps.length} 家`); +} + +async function doF12Import() { + console.log("\n提示:您可以直接粘贴从 F12 Network 复制的 Request Headers、cURL 文本,或手动输入三要素。"); + const raw = await prompt("请粘贴 F12 抓包文本 (直接回车则手动逐项输入): "); + + let accessToken = ""; + let corpId = ""; + let staffId = ""; + let name = ""; + + if (raw) { + const parsed = parseHeadersOrCurl(raw); + accessToken = parsed.accessToken || ""; + corpId = parsed.corpId || ""; + staffId = parsed.staffId || ""; + } + + if (!accessToken) accessToken = await prompt("请输入 accessToken: "); + if (!corpId) corpId = await prompt("请输入 corpId: "); + if (!staffId) staffId = await prompt("请输入 staffId: "); + name = await prompt("请输入企业名称(选填): "); + + if (!accessToken || !corpId || !staffId) { + console.error("accessToken, corpId, staffId 均为必填!"); + return; + } + + console.log("\n正在校验凭证并保存企业配置..."); + const imported = await importF12Credentials({ + accessToken, + corpId, + staffId, + name: name || undefined, + }); + + console.log("\n[SUCCESS] 成功导入并保存企业凭证!"); + console.log(`企业名称: ${imported.name}`); + console.log(`企业 ID: ${imported.id}`); + console.log(`员工工号: ${imported.credentials.staffId}`); + console.log(`保存路径: enterprises/${imported.id}.json`); +} + +async function doBrowserSync() { + console.log("\n正在从本地运行的浏览器会话中同步登录态..."); + const result = await fullBrowserSyncLogin({ saveAll: true }); + console.log("\n[SUCCESS] 成功从浏览器同步企业凭证!"); + console.log(`当前激活企业: ${result.selectedCorp.name} (${result.selectedCorp.id})`); + console.log(`共保存企业配置: ${result.allCorps.length} 家`); +} + +async function doRefreshAccounts() { + console.log("\n正在使用主账号登录态刷新所有关联企业的 AccessToken..."); + const result = await refreshAccountCorporations(undefined, { saveAll: true }); + console.log("\n[SUCCESS] 成功批量刷新并更新企业配置!"); + console.log(`账号标识: ${result.accountId}`); + console.log(`共刷新企业: ${result.allCorps.length} 家`); + result.allCorps.forEach((c, idx) => { + console.log(` ${idx + 1}. [${c.id}] ${c.name}`); + }); +} + +async function doShowStatus() { + const accounts = listAccounts(); + const activeAccount = getActiveAccount(); + const corps = loadCorpConfigs(); + + console.log("\n====== 账号与企业状态概览 ======"); + console.log(`总账号数: ${accounts.length},当前激活账号: ${activeAccount?.accountId || "无"}`); + accounts.forEach((acc, i) => { + console.log(`\n账号 [${i + 1}]: ${acc.accountId} (用户 ID: ${acc.userId || "未知"})`); + console.log(`关联企业数: ${acc.corporations.length}`); + }); + + console.log(`\n总加载本地企业配置: ${corps.length} 个`); + corps.forEach((c, i) => { + console.log(` ${i + 1}. [${c.id}] ${c.name} (来源: ${c.source || "manual"}, 账号: ${c.accountId || "无"})`); + }); + console.log("================================"); +} + async function main() { const args = process.argv.slice(2); const isSync = args.includes("--sync"); const isSms = args.includes("--sms"); - const isPwd = args.includes("--pwd") || (!isSync && !isSms); + const isRefresh = args.includes("--refresh"); + const isStatus = args.includes("--status"); + const phoneArg = args.find((a) => a.startsWith("--phone="))?.split("=")[1]; + const pwdArg = args.find((a) => a.startsWith("--password="))?.split("=")[1]; console.log("=========================================="); - console.log(" 合思 (ekb-mcp) 登录授权助手 "); + console.log(" 合思 (ekb-mcp) 认证与凭证管理 "); console.log("==========================================\n"); try { + if (phoneArg && pwdArg) { + return await doPasswordLogin(phoneArg, pwdArg); + } if (isSync) { - console.log("正在尝试从当前运行的浏览器会话中同步登录态..."); - const result = await fullBrowserSyncLogin({ saveAll: true }); - console.log("\n[SUCCESS] 成功从浏览器同步企业凭证!"); - console.log(`默认企业: ${result.selectedCorp.name} (${result.selectedCorp.id})`); - console.log(`共保存企业配置: ${result.allCorps.length} 家`); - return; + return await doBrowserSync(); } - if (isSms) { - const phone = await prompt("请输入手机号: "); - if (!phone) { - console.error("手机号不能为空"); - process.exit(1); - } - - console.log(`\n正在向 ${phone} 请求发送短信验证码...`); - let codeId: string | undefined; - try { - const sendRes = await sendSmsVerificationCode({ phone }); - codeId = sendRes.codeId; - console.log("短信验证码已发送!"); - } catch (e) { - console.warn("直接发送提示:", e instanceof Error ? e.message : String(e)); - console.log("如果网页端触发了人机验证,请在浏览器中获取验证码后在下方输入。"); - } - - const code = await prompt("请输入收到的 6 位短信验证码: "); - if (!code) { - console.error("验证码不能为空"); - process.exit(1); - } - - console.log("\n正在验证并换取企业访问令牌..."); - const result = await fullSmsLogin({ - phone, - code, - codeId, - saveAll: true, - }); - - console.log("\n[SUCCESS] 短信验证码登录成功!"); - console.log(`默认企业: ${result.selectedCorp.name} (${result.selectedCorp.id})`); - console.log(`共保存企业配置: ${result.allCorps.length} 家`); - return; + return await doSmsLogin(); + } + if (isRefresh) { + return await doRefreshAccounts(); + } + if (isStatus) { + return await doShowStatus(); } - if (isPwd) { - const phone = args.find((a) => a.startsWith("--phone="))?.split("=")[1] || - (await prompt("请输入手机号: ")); - const password = args.find((a) => a.startsWith("--password="))?.split("=")[1] || - (await prompt("请输入密码: ")); - - if (!phone || !password) { - console.error("手机号和密码不能为空"); - process.exit(1); - } - - console.log("\n正在进行全自动 RSA 账密登录..."); - const result = await fullPasswordLogin({ - phone, - password, - saveAll: true, - }); - - console.log("\n[SUCCESS] 账密登录成功!"); - console.log(`默认企业: ${result.selectedCorp.name} (${result.selectedCorp.id})`); - console.log(`共保存企业配置: ${result.allCorps.length} 家`); - result.allCorps.forEach((c, idx) => { - console.log(` ${idx + 1}. [${c.id}] ${c.name}`); - }); - return; - } + await handleMenu(); } catch (error) { - console.error("\n[ERROR] 登录失败:", error instanceof Error ? error.message : String(error)); + console.error("\n[ERROR] 操作失败:", error instanceof Error ? error.message : String(error)); process.exit(1); } } diff --git a/src/core/README.core.md b/src/core/README.core.md index 71128f0..7815577 100644 --- a/src/core/README.core.md +++ b/src/core/README.core.md @@ -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 diff --git a/src/core/auth/account-store.ts b/src/core/auth/account-store.ts new file mode 100644 index 0000000..da1d440 --- /dev/null +++ b/src/core/auth/account-store.ts @@ -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; +export type AccountEntry = z.infer; +export type AccountStore = z.infer; + +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); +} diff --git a/src/core/auth/login.ts b/src/core/auth/login.ts index 3fee909..16615d1 100644 --- a/src/core/auth/login.ts +++ b/src/core/auth/login.ts @@ -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 { + const result: Partial = {}; + 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 { + 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 { 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 { 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 { + 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 { @@ -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, }; } diff --git a/src/core/auth/tools.ts b/src/core/auth/tools.ts new file mode 100644 index 0000000..8413156 --- /dev/null +++ b/src/core/auth/tools.ts @@ -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(), + }; + }, + }, +]; diff --git a/src/core/config/manager.ts b/src/core/config/manager.ts index 7f40d96..a0f6816 100644 --- a/src/core/config/manager.ts +++ b/src/core/config/manager.ts @@ -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 = 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, })); } diff --git a/src/core/config/types.ts b/src/core/config/types.ts index 440cc1a..be89d38 100644 --- a/src/core/config/types.ts +++ b/src/core/config/types.ts @@ -1,19 +1,26 @@ import { z } from "zod"; +export const CredentialSourceSchema = z.enum(["account", "manual", "browser", "f12"]); +export type CredentialSource = z.infer; + 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(), }); diff --git a/src/server.ts b/src/server.ts index 0bed133..226c7e4 100644 --- a/src/server.ts +++ b/src/server.ts @@ -10,26 +10,23 @@ import { CorpContext } from "./core/config/manager.js"; import { createEkbClient } from "./core/auth/ekb.js"; import { getEasoClient } from "./core/auth/easo.js"; import { AuthenticationError, EkbError, NotLoggedInError } from "./core/errors.js"; +import { authTools } from "./core/auth/tools.js"; import { platformTools } from "./domains/platform/tools.js"; -const SwitchCorpSchema = z.object({ - corpId: z.string().describe("企业 ID"), -}); - function formatError(error: unknown): { content: Array<{ type: "text"; text: string }>; isError: true; } { if (error instanceof NotLoggedInError) { return { - content: [{ type: "text", text: "未配置企业,请先添加企业配置" }], + content: [{ type: "text", text: "未配置企业,请先添加企业配置或登录" }], isError: true, }; } if (error instanceof AuthenticationError) { return { - content: [{ type: "text", text: "认证失败,请检查企业凭证或 token 是否过期" }], + content: [{ type: "text", text: `认证失败: ${error.message}` }], isError: true, }; } @@ -50,7 +47,7 @@ function formatError(error: unknown): { console.error(error); return { - content: [{ type: "text", text: "发生内部错误,请稍后重试" }], + content: [{ type: "text", text: error instanceof Error ? error.message : "发生内部错误,请稍后重试" }], isError: true, }; } @@ -72,23 +69,17 @@ async function main() { } ); + // 聚合所有工具 + const allTools = [...authTools, ...platformTools]; + // 注册工具列表 server.setRequestHandler(ListToolsRequestSchema, async () => { return { - tools: [ - // 企业切换工具 - { - name: "switch_corp", - description: "切换到指定企业", - inputSchema: (SwitchCorpSchema as any).toJSONSchema(), - }, - // Platform 工具 - ...platformTools.map((t) => ({ - name: t.name, - description: t.description, - inputSchema: (t.parameters as any).toJSONSchema(), - })), - ], + tools: allTools.map((t) => ({ + name: t.name, + description: t.description, + inputSchema: (t.parameters as any).toJSONSchema(), + })), }; }); @@ -96,54 +87,46 @@ async function main() { server.setRequestHandler(CallToolRequestSchema, async (request) => { const { name, arguments: args } = request.params; - // 企业切换 - if (name === "switch_corp") { - const parsed = SwitchCorpSchema.safeParse(args); - if (!parsed.success) { + try { + // 1. 检查 Auth 工具 + const authTool = authTools.find((t) => t.name === name); + if (authTool) { + const parsed = authTool.parameters.safeParse(args || {}); + if (!parsed.success) { + return { + content: [{ type: "text", text: `参数错误: ${parsed.error.message}` }], + isError: true, + }; + } + const result = await authTool.handler({ corpContext }, parsed.data as never); return { content: [ { type: "text", - text: `参数错误: ${parsed.error.message}`, + text: typeof result === "string" ? result : JSON.stringify(result, null, 2), + }, + ], + }; + } + + // 2. 检查 Domain 业务工具(需要当前企业上下文) + const currentCorp = corpContext.getCurrent(); + if (!currentCorp) { + return { + content: [ + { + type: "text", + text: "未配置企业,请先调用 import_f12_corp 导入凭证,或执行 bun run login 登录", }, ], isError: true, }; } - const { corpId } = parsed.data; - const success = corpContext.switchCorp(corpId); - return { - content: [ - { - type: "text", - text: success - ? `已切换到企业: ${corpId}` - : `企业 ${corpId} 不存在`, - }, - ], - }; - } - - // 获取当前企业 - const currentCorp = corpContext.getCurrent(); - if (!currentCorp) { - return { - content: [ - { - type: "text", - text: "未配置企业,请先添加企业配置", - }, - ], - isError: true, - }; - } - - try { // Platform 工具 const platformTool = platformTools.find((t) => t.name === name); if (platformTool) { - const parsed = platformTool.parameters.safeParse(args); + const parsed = platformTool.parameters.safeParse(args || {}); if (!parsed.success) { return { content: [{ type: "text", text: `参数错误: ${parsed.error.message}` }], @@ -160,7 +143,7 @@ async function main() { content: [ { type: "text", - text: JSON.stringify(result, null, 2), + text: typeof result === "string" ? result : JSON.stringify(result, null, 2), }, ], };