feat(auth): 实现三种登录覆盖矩阵与企业配置自动生成 (账密/短信/浏览器同步)

This commit is contained in:
gitea committed 2026-08-27 10:43:27 +08:00
1 parent 2085a97e34
commit 255c7aee8d
7 files changed
+643 -6

No files matched your search

+10
View File
@@ -33,9 +33,19 @@ bun install
bun run dev # 开发模式(热重载)
bun run start # 生产模式
bun run typecheck # TypeScript 类型检查
bun run login # 交互式登录 / 企业配置生成
bun run export:workflow-schema # 导出工作流 JSON Schema
```
### 登录授权方式
```bash
bun run login # 1. 交互式账号密码登录
bun run login --phone=138... --password=... # 2. 命令行参数静默登录
bun run login --sms # 3. 短信验证码登录
bun run login --sync # 4. 从当前运行的浏览器一键同步
```
## 架构
```
+1
View File
@@ -7,6 +7,7 @@
"dev": "bun run --watch src/server.ts",
"start": "bun run src/server.ts",
"typecheck": "tsc --noEmit",
"login": "bun run scripts/login.ts",
"export:workflow-schema": "bun run scripts/export-workflow-schema.ts"
},
"dependencies": {
+113
View File
@@ -0,0 +1,113 @@
import {
fullPasswordLogin,
fullSmsLogin,
fullBrowserSyncLogin,
sendSmsVerificationCode,
listUserCorporations,
} from "../src/core/auth/login.js";
import readline from "readline";
function prompt(question: string): Promise<string> {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
return new Promise((resolve) => {
rl.question(question, (answer) => {
rl.close();
resolve(answer.trim());
});
});
}
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);
console.log("==========================================");
console.log(" 合思 (ekb-mcp) 登录授权助手 ");
console.log("==========================================\n");
try {
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;
}
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;
}
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;
}
} catch (error) {
console.error("\n[ERROR] 登录失败:", error instanceof Error ? error.message : String(error));
process.exit(1);
}
}
main();
+2 -1
View File
@@ -6,7 +6,8 @@ Core 层负责基础设施:企业配置管理、认证 Token 获取与缓存
```text
src/core/
├── auth/ # Token 获取、刷新、缓存
├── auth/ # 登录认证与 Token 获取、刷新、缓存
│ ├── login.ts # 登录三矩阵(RSA账密登录、短信验证码登录、浏览器同步)
│ ├── ekb.ts # 快报主站三 Header 认证
│ ├── easo.ts # EASO(unity.ekuaibao.com)四步认证
│ ├── piper.ts # Piper(piper.ekuaibao.com)三步认证
+429
View File
@@ -0,0 +1,429 @@
import crypto from "crypto";
import ky from "ky";
import { AuthenticationError } from "../errors.js";
import { CorpConfig } from "../config/types.js";
import { saveCorpConfig, saveMultipleCorpConfigs } from "../config/loader.js";
import {
CorporationItem,
CorporationItemSchema,
IdpOAuthTokenResponse,
PasswordLoginParams,
SendSmsCodeParams,
SmsCodeLoginParams,
SyncBrowserLoginParams,
} from "./types.js";
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";
// ── 基础工具函数 ─────────────────────────────────────────────────────────────
/**
* 获取业务中心 RSA 登录公钥 (Base64)
*/
export async function fetchPublicKey(
businessCenterUrl: string = DEFAULT_BUSINESS_CENTER_URL
): Promise<string> {
const res = await ky
.get(`${businessCenterUrl}/cloud-auth/public/auth/public-key`)
.json<{ data?: { base64?: string } }>();
const base64 = res.data?.base64;
if (!base64) {
throw new AuthenticationError("获取登录加密公钥失败");
}
return base64;
}
/**
* 使用 RSA 公钥 (PKCS#1) 加密密码
*/
export function encryptPassword(password: string, publicKeyBase64: string): string {
const pem = `-----BEGIN PUBLIC KEY-----\n${publicKeyBase64}\n-----END PUBLIC KEY-----`;
return crypto
.publicEncrypt(
{
key: pem,
padding: crypto.constants.RSA_PKCS1_PADDING,
},
Buffer.from(password)
)
.toString("base64");
}
/**
* 格式化手机号/用户名(如 86-13800000000)
*/
export function formatAccount(phone: string, areaCode: string = "86"): string {
const clean = phone.trim();
if (clean.includes("-")) return clean;
return `${areaCode}-${clean}`;
}
// ── 模式 1:账号密码登录 ──────────────────────────────────────────────────────
/**
* 账号密码登录获取 cloudAuthToken
*/
export async function loginByPassword(
params: PasswordLoginParams
): Promise<{ cloudAuthToken: string }> {
const businessCenterUrl = params.businessCenterUrl || DEFAULT_BUSINESS_CENTER_URL;
const areaCode = params.areaCode || "86";
const deviceType = params.deviceType || "desktop";
// 1. 获取公钥并加密密码
const pubKey = await fetchPublicKey(businessCenterUrl);
const encryptedPassword = encryptPassword(params.password, pubKey);
// 2. 发起账密登录
const res = await ky
.post(`${businessCenterUrl}/cloud-auth/public/auth/login-by-password`, {
json: {
deviceType,
username: formatAccount(params.phone, areaCode),
password: encryptedPassword,
},
})
.json<{ data?: string; errorCode?: number; errorMessage?: string }>();
if (!res.data) {
throw new AuthenticationError(res.errorMessage || "账号或密码错误");
}
return { cloudAuthToken: res.data };
}
// ── 模式 2:短信验证码登录 ────────────────────────────────────────────────────
/**
* 发送短信验证码
*/
export async function sendSmsVerificationCode(
params: SendSmsCodeParams
): Promise<{ codeId?: string }> {
const businessCenterUrl = params.businessCenterUrl || DEFAULT_BUSINESS_CENTER_URL;
const areaCode = params.areaCode || "86";
const payload: Record<string, unknown> = {
bizType: "LOGIN",
account: formatAccount(params.phone, areaCode),
channelType: "SMS",
...params.captchaParams,
};
const res = await ky
.post(`${businessCenterUrl}/cloud-auth/public/auth/send-verification-code`, {
json: payload,
})
.json<{ data?: { codeId?: string }; errorCode?: number; errorMessage?: string }>();
if (res.errorCode) {
throw new AuthenticationError(res.errorMessage || "发送验证码失败");
}
return { codeId: res.data?.codeId };
}
/**
* 提交短信验证码登录获取 cloudAuthToken
*/
export async function loginBySmsCode(
params: SmsCodeLoginParams
): Promise<{ cloudAuthToken: string }> {
const businessCenterUrl = params.businessCenterUrl || DEFAULT_BUSINESS_CENTER_URL;
const areaCode = params.areaCode || "86";
const deviceType = params.deviceType || "desktop";
const res = await ky
.post(`${businessCenterUrl}/cloud-auth/public/auth/login-by-code`, {
json: {
username: formatAccount(params.phone, areaCode),
code: params.code.trim(),
codeId: params.codeId,
deviceType,
},
})
.json<{ data?: string; errorCode?: number; errorMessage?: string }>();
if (!res.data) {
throw new AuthenticationError(res.errorMessage || "验证码错误或已过期");
}
return { cloudAuthToken: res.data };
}
// ── 模式 3:浏览器会话同步 ────────────────────────────────────────────────────
/**
* 从本地运行的 Kimi WebBridge 或浏览器会话中提取鉴权 Token
*/
export async function syncFromBrowserSession(
params: SyncBrowserLoginParams = {}
): Promise<{ cloudAuthToken?: string; activeSession?: { accessToken: string; corpId: string; staffId?: string } }> {
const webbridgeUrl = params.webbridgeUrl || DEFAULT_WEBBRIDGE_URL;
try {
const res = await ky
.post(`${webbridgeUrl}/command`, {
json: {
action: "evaluate",
args: {
code: `(() => {
const sessionStr = localStorage.getItem("session");
const cloudAuthToken = localStorage.getItem("cloudAuthToken");
let sessionObj = null;
try { sessionObj = JSON.parse(sessionStr || "{}"); } catch {}
return {
cloudAuthToken,
accessToken: sessionObj?.user?.accessToken || localStorage.getItem("accessToken"),
corpId: sessionObj?.user?.corpId || localStorage.getItem("corpId"),
staffId: sessionObj?.user?.staffId || sessionObj?.staff?.id || localStorage.getItem("staffId"),
};
})()`,
},
session: "ekb-sync-auth",
},
})
.json<{ ok?: boolean; data?: { value?: { cloudAuthToken?: string; accessToken?: string; corpId?: string; staffId?: string } } }>();
const val = res.data?.value;
if (!val || (!val.cloudAuthToken && !val.accessToken)) {
throw new AuthenticationError("未能从当前浏览器会话中获取到合思登录凭证,请确保网页已登录");
}
return {
cloudAuthToken: val.cloudAuthToken,
activeSession: val.accessToken && val.corpId ? {
accessToken: val.accessToken,
corpId: val.corpId,
staffId: val.staffId,
} : undefined,
};
} catch (error) {
if (error instanceof AuthenticationError) throw error;
throw new AuthenticationError(`连接浏览器 WebBridge 失败: ${error instanceof Error ? error.message : String(error)}`);
}
}
// ── 企业管理与主站 OAuth2 令牌换取 ─────────────────────────────────────────────
/**
* 列出当前账号名下的所有企业
*/
export async function listUserCorporations(
cloudAuthToken: string,
businessCenterUrl: string = DEFAULT_BUSINESS_CENTER_URL
): Promise<CorporationItem[]> {
const res = await ky
.get(`${businessCenterUrl}/cloud-auth/public/auth/list-corporations`, {
headers: {
"cloud-auth-token": cloudAuthToken,
},
})
.json<{ data?: { items?: unknown[]; externalItems?: unknown[] }; errorCode?: number; errorMessage?: string }>();
if (!res.data?.items) {
throw new AuthenticationError(res.errorMessage || "获取企业列表失败");
}
const allItems = [...(res.data.items || []), ...(res.data.externalItems || [])];
return allItems.map((item) => CorporationItemSchema.parse(item));
}
/**
* 选定企业并换取主站 30 天有效期的 access_token
*/
export async function switchCorporationAndExchangeToken(
cloudAuthToken: string,
corp: CorporationItem,
idpUrl: string = DEFAULT_IDP_URL,
businessCenterUrl: string = DEFAULT_BUSINESS_CENTER_URL
): Promise<{ accessToken: string; refreshToken?: string; expiresIn: number; corpConfig: CorpConfig }> {
// 1. 在业务中心切换企业获取 authCode
const switchRes = await ky
.post(`${businessCenterUrl}/cloud-auth/public/auth/switch-corporation`, {
headers: {
"cloud-auth-token": cloudAuthToken,
},
json: {
corporationId: corp.corporationId,
userId: corp.userId,
cluster: corp.cluster,
},
})
.json<{ data?: { accessToken?: string }; errorCode?: number; errorMessage?: string }>();
const authCode = switchRes.data?.accessToken;
if (!authCode) {
throw new AuthenticationError(switchRes.errorMessage || `切换到企业 ${corp.corporationName} 失败`);
}
// 2. 用 authCode 向 IDP 换取真正的主站 access_token
const idpRes = await ky
.post(`${idpUrl}/api/idp/public/oauth2/token`, {
json: {
clientId: corp.clientId || "whispered-app",
grantType: "authorization_code",
code: authCode,
withIdToken: false,
},
})
.json<IdpOAuthTokenResponse>();
if (!idpRes.access_token) {
throw new AuthenticationError(`换取企业 ${corp.corporationName} 访问令牌失败`);
}
const corpConfig: CorpConfig = {
id: corp.corporationId,
name: corp.corporationName,
baseUrl: corp.baseUrl || "https://app.ekuaibao.com",
credentials: {
accessToken: idpRes.access_token,
corpId: corp.corporationId,
staffId: corp.staffId,
},
auth: {
refreshTtl: 300,
},
};
return {
accessToken: idpRes.access_token,
refreshToken: idpRes.refresh_token,
expiresIn: idpRes.expires_in,
corpConfig,
};
}
// ── 全流程一站式高阶函数 ─────────────────────────────────────────────────────
export interface FullLoginOptions {
targetCorpId?: string;
saveAll?: boolean;
enterprisesDir?: string;
idpUrl?: string;
businessCenterUrl?: string;
}
export interface FullLoginResult {
selectedCorp: CorpConfig;
allCorps: CorpConfig[];
cloudAuthToken: string;
}
/**
* 账密登录全流程(登录 ➔ 拉取企业 ➔ 换取 Token ➔ 保存配置)
*/
export async function fullPasswordLogin(
params: PasswordLoginParams & FullLoginOptions
): Promise<FullLoginResult> {
const { cloudAuthToken } = await loginByPassword(params);
return exchangeAndSaveCorporations(cloudAuthToken, params);
}
/**
* 短信验证码登录全流程(提交验证码 ➔ 拉取企业 ➔ 换取 Token ➔ 保存配置)
*/
export async function fullSmsLogin(
params: SmsCodeLoginParams & FullLoginOptions
): Promise<FullLoginResult> {
const { cloudAuthToken } = await loginBySmsCode(params);
return exchangeAndSaveCorporations(cloudAuthToken, params);
}
/**
* 浏览器同步全流程(从浏览器提取 ➔ 换取 Token ➔ 保存配置)
*/
export async function fullBrowserSyncLogin(
options: FullLoginOptions & SyncBrowserLoginParams = {}
): Promise<FullLoginResult> {
const { cloudAuthToken, activeSession } = await syncFromBrowserSession(options);
if (cloudAuthToken) {
return exchangeAndSaveCorporations(cloudAuthToken, options);
}
if (activeSession) {
const singleCorp: CorpConfig = {
id: activeSession.corpId,
name: "当前企业",
baseUrl: "https://app.ekuaibao.com",
credentials: {
accessToken: activeSession.accessToken,
corpId: activeSession.corpId,
staffId: activeSession.staffId || `${activeSession.corpId}:admin`,
},
};
saveCorpConfig(singleCorp, options.enterprisesDir);
return {
selectedCorp: singleCorp,
allCorps: [singleCorp],
cloudAuthToken: "",
};
}
throw new AuthenticationError("未能同步到有效登录会话");
}
/**
* 内部统一:根据 cloudAuthToken 批量换票并保存企业配置
*/
async function exchangeAndSaveCorporations(
cloudAuthToken: string,
options: FullLoginOptions
): Promise<FullLoginResult> {
const corporations = await listUserCorporations(cloudAuthToken, options.businessCenterUrl);
if (corporations.length === 0) {
throw new AuthenticationError("该账号名下未找到任何可用企业");
}
// 确定目标企业
let target = corporations.find((c) => c.corporationId === options.targetCorpId);
if (!target) {
target = corporations[0];
}
const allConfigs: CorpConfig[] = [];
let selectedCorpConfig: CorpConfig | null = null;
if (options.saveAll) {
// 换取全部企业的 Token 并保存
for (const corp of corporations) {
try {
const { corpConfig } = await switchCorporationAndExchangeToken(
cloudAuthToken,
corp,
options.idpUrl,
options.businessCenterUrl
);
allConfigs.push(corpConfig);
if (corp.corporationId === target.corporationId) {
selectedCorpConfig = corpConfig;
}
} catch (err) {
console.warn(`[auth] 跳过企业 ${corp.corporationName}:`, err instanceof Error ? err.message : String(err));
}
}
saveMultipleCorpConfigs(allConfigs, options.enterprisesDir);
} else {
// 仅换取选定的目标企业
const { corpConfig } = await switchCorporationAndExchangeToken(
cloudAuthToken,
target,
options.idpUrl,
options.businessCenterUrl
);
selectedCorpConfig = corpConfig;
allConfigs.push(corpConfig);
saveCorpConfig(corpConfig, options.enterprisesDir);
}
return {
selectedCorp: selectedCorpConfig || allConfigs[0],
allCorps: allConfigs,
cloudAuthToken,
};
}
+63
View File
@@ -24,3 +24,66 @@ export const TokenStoreSchema = z.record(z.string(), CorpTokensSchema);
export type TokenEntry = z.infer<typeof TokenEntrySchema>;
export type CorpTokens = z.infer<typeof CorpTokensSchema>;
export type TokenStore = z.infer<typeof TokenStoreSchema>;
// ── 登录认证模型 ─────────────────────────────────────────────────────────────
export const CorporationItemSchema = z.object({
corporationId: z.string(),
corporationName: z.string(),
corporationEnName: z.string().nullable().optional(),
cluster: z.string().default("app"),
clientId: z.string().optional().default("whispered-app"),
staffId: z.string(),
userId: z.string(),
sourceChannel: z.string().optional(),
baseUrl: z.string().optional().default("https://app.ekuaibao.com/"),
external: z.boolean().optional().default(false),
needAuth: z.boolean().optional().default(false),
});
export type CorporationItem = z.infer<typeof CorporationItemSchema>;
export interface IdpOAuthTokenResponse {
access_token: string;
token_type: string;
expires_in: number;
refresh_token?: string;
id_token?: string;
}
export interface PasswordLoginParams {
phone: string;
password: string;
areaCode?: string; // 默认 "86"
deviceType?: string; // 默认 "desktop"
businessCenterUrl?: string;
idpUrl?: string;
}
export interface SendSmsCodeParams {
phone: string;
areaCode?: string;
captchaParams?: {
aliSceneId?: string;
aliVerifyParam?: string;
txTicket?: string;
txRandStr?: string;
};
businessCenterUrl?: string;
}
export interface SmsCodeLoginParams {
phone: string;
code: string;
codeId?: string;
areaCode?: string;
deviceType?: string;
businessCenterUrl?: string;
idpUrl?: string;
}
export interface SyncBrowserLoginParams {
webbridgeUrl?: string;
idpUrl?: string;
businessCenterUrl?: string;
}
+25 -5
View File
@@ -1,13 +1,18 @@
import { readFileSync, readdirSync } from "fs";
import { readFileSync, readdirSync, writeFileSync, mkdirSync } from "fs";
import { join } from "path";
import { CorpConfig, CorpConfigSchema } from "./types";
import { CorpConfig, CorpConfigSchema } from "./types.js";
const ENTERPRISES_DIR = "./enterprises";
export function loadCorpConfigs(): CorpConfig[] {
function ensureDir(dir: string): void {
mkdirSync(dir, { recursive: true });
}
export function loadCorpConfigs(dir: string = ENTERPRISES_DIR): CorpConfig[] {
let files: string[];
try {
files = readdirSync(ENTERPRISES_DIR).filter((f) => f.endsWith(".json"));
ensureDir(dir);
files = readdirSync(dir).filter((f) => f.endsWith(".json"));
} catch (error) {
console.error(
`[config] failed to read enterprises directory: ${error instanceof Error ? error.message : String(error)}`
@@ -18,7 +23,7 @@ export function loadCorpConfigs(): CorpConfig[] {
const configs: CorpConfig[] = [];
for (const file of files) {
try {
const content = readFileSync(join(ENTERPRISES_DIR, file), "utf-8");
const content = readFileSync(join(dir, file), "utf-8");
const parsed = JSON.parse(content);
configs.push(CorpConfigSchema.parse(parsed));
} catch (error) {
@@ -30,3 +35,18 @@ export function loadCorpConfigs(): CorpConfig[] {
return configs;
}
export function saveCorpConfig(config: CorpConfig, dir: string = ENTERPRISES_DIR): string {
ensureDir(dir);
const validated = CorpConfigSchema.parse(config);
const filePath = join(dir, `${validated.id}.json`);
writeFileSync(filePath, JSON.stringify(validated, null, 2), "utf-8");
return filePath;
}
export function saveMultipleCorpConfigs(
configs: CorpConfig[],
dir: string = ENTERPRISES_DIR
): string[] {
return configs.map((config) => saveCorpConfig(config, dir));
}