Files
hose-use/src/core/auth/login.ts
T

631 lines
20 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 {
saveAccount,
getAccount,
getActiveAccount,
AccountEntry,
} from "./account-store.js";
import {
CorporationItem,
CorporationItemSchema,
IdpOAuthTokenResponse,
PasswordLoginParams,
SendSmsCodeParams,
SmsCodeLoginParams,
SyncBrowserLoginParams,
} from "./types.js";
import {
DEFAULT_EKB_BASE_URL,
canRefreshCorpAccessToken,
fetchHoseOpenApiAccessToken,
fetchHoseProvisionalAuth,
fetchOpenApiKeysBySession,
getCorpOpenApiCredentials,
hasOpenApiPersistentCredentials,
normalizeBaseUrl,
selectOpenApiKey,
} from "./openapi-v1.js";
import { invalidateCorpSubdomainTokenCaches } from "./link-import.js";
export * from "./openapi-v1.js";
export * from "./link-import.js";
export * from "./openapi-onboard.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,
accountId?: string,
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} 访问令牌失败`);
}
let resolvedAppKey: string | undefined;
let resolvedAppSecurity: string | undefined;
try {
const keys = await fetchOpenApiKeysBySession({
baseUrl: corp.baseUrl || "https://app.ekuaibao.com",
accessToken: idpRes.access_token,
corpId: corp.corporationId,
});
if (keys.length > 0) {
const selected = selectOpenApiKey(keys, corp.corporationId, { force: true });
resolvedAppKey = selected.appKey;
resolvedAppSecurity = selected.appSecurity;
}
} catch {
// 非管理员或无密钥读取权限时静默跳过,保留账号级换票能力
}
const corpConfig: CorpConfig = {
id: corp.corporationId,
name: corp.corporationName,
corpId: corp.corporationId,
userId: corp.userId,
staffId: corp.staffId,
baseUrl: corp.baseUrl || "https://app.ekuaibao.com",
source: "account",
accountId,
credentials: {
accessToken: idpRes.access_token,
corpId: corp.corporationId,
staffId: corp.staffId,
...(resolvedAppKey ? { appKey: resolvedAppKey } : {}),
...(resolvedAppSecurity ? { appSecurity: resolvedAppSecurity } : {}),
},
auth: {
refreshTtl: 300,
refreshToken: idpRes.refresh_token,
expiresAt: Date.now() + idpRes.expires_in * 1000,
},
};
return {
accessToken: idpRes.access_token,
refreshToken: idpRes.refresh_token,
expiresIn: idpRes.expires_in,
corpConfig,
};
}
/**
* 针对单个企业凭证进行静默无感自动续杯
* 支持双通道续期:
* 1. 用户级主账号 (IDP cloudAuthToken -> 30天 access_token)
* 2. 企业级开放平台持久化密钥 (appKey + appSecurity -> getProvisionalAuth 临时会话)
*/
export async function refreshSingleCorpAccessToken(
corp: CorpConfig,
businessCenterUrl: string = DEFAULT_BUSINESS_CENTER_URL,
idpUrl: string = DEFAULT_IDP_URL,
enterprisesDir?: string
): Promise<boolean> {
if (!canRefreshCorpAccessToken(corp)) return false;
// 通道 1:用户级主账号 IDP 换票
if (corp.source === "account" && !corp.session?.isShortTermToken && corp.accountId) {
const account = getAccount(corp.accountId);
if (account?.cloudAuthToken) {
try {
const corpItem: CorporationItem = {
corporationId: corp.corpId || corp.credentials.corpId,
corporationName: corp.name,
cluster: corp.cluster || "app",
clientId: "whispered-app",
staffId: corp.staffId || corp.credentials.staffId,
userId: corp.userId || account.userId || "",
baseUrl: corp.baseUrl || "https://app.ekuaibao.com",
external: false,
needAuth: false,
};
const res = await switchCorporationAndExchangeToken(
account.cloudAuthToken,
corpItem,
corp.accountId,
idpUrl,
businessCenterUrl
);
corp.credentials.accessToken = res.accessToken;
if (!corp.auth) corp.auth = { refreshTtl: 300 };
corp.auth.refreshToken = res.refreshToken;
corp.auth.expiresAt = Date.now() + res.expiresIn * 1000;
saveCorpConfig(corp, enterprisesDir);
invalidateCorpSubdomainTokenCaches(corp);
return true;
} catch (err) {
if (!hasOpenApiPersistentCredentials(corp)) {
console.warn(`[auth] 自动续杯刷新企业 ${corp.name} 失败:`, err instanceof Error ? err.message : String(err));
return false;
}
}
}
}
// 通道 2:企业级 OpenAPI 持久化密钥 (appKey + appSecurity) 换取 Provisional Session
const openApiCreds = getCorpOpenApiCredentials(corp);
if (openApiCreds) {
try {
const baseUrl = normalizeBaseUrl(corp.baseUrl || DEFAULT_EKB_BASE_URL);
const corpId = corp.corpId || corp.credentials.corpId;
const staffId = corp.staffId || corp.credentials.staffId;
const openapiToken = await fetchHoseOpenApiAccessToken({
appKey: openApiCreds.appKey,
appSecurity: openApiCreds.appSecurity,
baseUrl,
});
const provisional = await fetchHoseProvisionalAuth({
baseUrl,
openapiToken,
corpId,
staffId,
expiresIn: 7200,
});
corp.credentials.accessToken = provisional.token;
if (!corp.auth) corp.auth = { refreshTtl: 300 };
corp.auth.expiresAt = provisional.expiresAt;
if (corp.session) {
corp.session.expTime = provisional.expiresAt;
}
saveCorpConfig(corp, enterprisesDir);
invalidateCorpSubdomainTokenCaches(corp);
return true;
} catch (err) {
console.warn(
`[auth] OpenAPI 持久化密钥续杯企业 ${corp.name} 失败:`,
err instanceof Error ? err.message : String(err)
);
return false;
}
}
return false;
}
// ── 全流程一站式高阶函数 ─────────────────────────────────────────────────────
export interface FullLoginOptions {
targetCorpId?: string;
saveAll?: boolean;
enterprisesDir?: string;
idpUrl?: string;
businessCenterUrl?: string;
}
export interface FullLoginResult {
selectedCorp: CorpConfig;
allCorps: CorpConfig[];
cloudAuthToken: string;
accountId: string;
}
/**
* 账密登录全流程(登录 ➔ 存账号 ➔ 拉取企业 ➔ 换取 Token ➔ 保存配置)
*/
export async function fullPasswordLogin(
params: PasswordLoginParams & FullLoginOptions
): Promise<FullLoginResult> {
const { cloudAuthToken } = await loginByPassword(params);
const accountId = formatAccount(params.phone, params.areaCode);
return exchangeAndSaveCorporations(accountId, cloudAuthToken, params);
}
/**
* 短信验证码登录全流程(提交验证码 ➔ 存账号 ➔ 拉取企业 ➔ 换取 Token ➔ 保存配置)
*/
export async function fullSmsLogin(
params: SmsCodeLoginParams & FullLoginOptions
): Promise<FullLoginResult> {
const { cloudAuthToken } = await loginBySmsCode(params);
const accountId = formatAccount(params.phone, params.areaCode);
return exchangeAndSaveCorporations(accountId, cloudAuthToken, params);
}
/**
* 浏览器同步全流程(从浏览器提取 ➔ 换取 Token ➔ 保存配置)
*/
export async function fullBrowserSyncLogin(
options: FullLoginOptions & SyncBrowserLoginParams = {}
): Promise<FullLoginResult> {
const { cloudAuthToken, activeSession } = await syncFromBrowserSession(options);
if (cloudAuthToken) {
const accountId = "browser_session";
return exchangeAndSaveCorporations(accountId, cloudAuthToken, options);
}
if (activeSession) {
const singleCorp: CorpConfig = {
id: activeSession.corpId,
name: "当前浏览器企业",
baseUrl: "https://app.ekuaibao.com",
source: "browser",
credentials: {
accessToken: activeSession.accessToken,
corpId: activeSession.corpId,
staffId: activeSession.staffId || `${activeSession.corpId}:admin`,
},
};
saveCorpConfig(singleCorp, options.enterprisesDir);
return {
selectedCorp: singleCorp,
allCorps: [singleCorp],
cloudAuthToken: "",
accountId: "browser_session",
};
}
throw new AuthenticationError("未能同步到有效登录会话");
}
/**
* 刷新指定账号下的所有企业 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> {
const corporations = await listUserCorporations(cloudAuthToken, options.businessCenterUrl);
if (corporations.length === 0) {
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 !== false) {
// 换取全部企业的 Token 并保存
for (const corp of corporations) {
try {
const { corpConfig } = await switchCorporationAndExchangeToken(
cloudAuthToken,
corp,
accountId,
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,
accountId,
options.idpUrl,
options.businessCenterUrl
);
selectedCorpConfig = corpConfig;
allConfigs.push(corpConfig);
saveCorpConfig(corpConfig, options.enterprisesDir);
}
return {
selectedCorp: selectedCorpConfig || allConfigs[0],
allCorps: allConfigs,
cloudAuthToken,
accountId,
};
}