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

+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,
};
}