feat(auth): 实现全自动无感续杯 (401/即将过期自动重试换票) 与企业多身份唯一标识分层

This commit is contained in:
gitea committed 2026-08-27 11:04:41 +08:00
1 parent 189415cdac
commit b7a3bf2c03
7 files changed
+122 -17

No files matched your search

+8 -5
View File
@@ -104,18 +104,21 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
};
}
const corpId = corp.corpId || corp.credentials.corpId;
const staffId = corp.staffId || corp.credentials.staffId;
// 重新换取
const hoseToken = await fetchHoseToken(
corp.credentials.accessToken,
corp.credentials.corpId
corpId
);
const unityJwt = await fetchUnityJwt(
corp.credentials.accessToken,
corp.credentials.corpId,
corp.credentials.staffId
corpId,
staffId
);
const easoToken = await fetchEasoRealmToken(
corp.credentials.corpId,
corpId,
unityJwt,
hoseToken
);
@@ -134,7 +137,7 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
getHeaders: () => ({
Authorization: `Bearer ${easoToken}`,
accesstoken: corp.credentials.accessToken,
corporationid: corp.credentials.corpId,
corporationid: corpId,
hoseaccesstoken: hoseToken,
}),
onUnauthorized: () => {
+19 -6
View File
@@ -1,17 +1,30 @@
import { CorpConfig } from "../config/types.js";
import { createClient } from "../http/factory.js";
import { createAuthClient } from "../http/factory.js";
import { refreshSingleCorpAccessToken } from "./login.js";
export function getEkbHeaders(corp: CorpConfig): Record<string, string> {
return {
accesstoken: corp.credentials.accessToken,
corpid: corp.credentials.corpId,
staffid: corp.credentials.staffId,
corpid: corp.corpId || corp.credentials.corpId,
staffid: corp.staffId || corp.credentials.staffId,
};
}
export function createEkbClient(corp: CorpConfig) {
return createClient({
export async function createEkbClient(corp: CorpConfig) {
// 1. 预检:若 Token 即将过期 (提前 refreshTtl 秒),静默无感自动续杯
if (corp.auth?.expiresAt) {
const ttlMs = (corp.auth.refreshTtl || 300) * 1000;
if (Date.now() >= corp.auth.expiresAt - ttlMs) {
await refreshSingleCorpAccessToken(corp);
}
}
// 2. 使用带 401 自动重试与换票的 AuthClient
return createAuthClient({
prefixUrl: corp.baseUrl || "https://app.ekuaibao.com",
headers: getEkbHeaders(corp),
getHeaders: () => getEkbHeaders(corp),
onUnauthorized: async () => {
await refreshSingleCorpAccessToken(corp);
},
});
}
+48
View File
@@ -391,6 +391,9 @@ export async function switchCorporationAndExchangeToken(
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,
@@ -414,6 +417,51 @@ export async function switchCorporationAndExchangeToken(
};
}
/**
* 针对单个企业凭证进行静默无感自动续杯
*/
export async function refreshSingleCorpAccessToken(
corp: CorpConfig,
businessCenterUrl: string = DEFAULT_BUSINESS_CENTER_URL,
idpUrl: string = DEFAULT_IDP_URL
): Promise<boolean> {
const account = corp.accountId ? getAccount(corp.accountId) : getActiveAccount();
if (!account?.cloudAuthToken) return false;
try {
const corpItem: CorporationItem = {
corporationId: corp.corpId || corp.credentials.corpId,
corporationName: corp.name,
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);
return true;
} catch (err) {
console.warn(`[auth] 自动续杯刷新企业 ${corp.name} 失败:`, err instanceof Error ? err.message : String(err));
return false;
}
}
// ── 全流程一站式高阶函数 ─────────────────────────────────────────────────────
export interface FullLoginOptions {
+7 -3
View File
@@ -80,15 +80,18 @@ export async function getPiperClient(
});
}
const corpId = corp.corpId || corp.credentials.corpId;
const staffId = corp.staffId || corp.credentials.staffId;
// 重新换取
const hoseToken = await fetchHoseToken(
corp.credentials.accessToken,
corp.credentials.corpId
corpId
);
const easoJwt = await fetchEasoJwt(
corp.credentials.accessToken,
corp.credentials.corpId,
corp.credentials.staffId
corpId,
staffId
);
const entry = {
@@ -104,6 +107,7 @@ export async function getPiperClient(
getHeaders: () => ({
Authorization: `Bearer ${easoJwt}`,
platformid: platformId,
hoseaccesstoken: hoseToken,
}),
onUnauthorized: () => {
piperMemoryCache.delete(cacheKey);
+11 -2
View File
@@ -26,9 +26,18 @@ export function resolveCorpConfig(
const selectedCorpId = requestedCorpId ?? configuredCorpId;
if (selectedCorpId) {
const corp = corps.find((item) => item.id === selectedCorpId);
// 1. 优先按身份/配置 ID 精确匹配 (如 uzU7pcWfScck00@17718556446)
let corp = corps.find((item) => item.id === selectedCorpId);
// 2. 其次按企业物理 ID 匹配 (如 uzU7pcWfScck00)
if (!corp) {
corp = corps.find(
(item) =>
item.corpId === selectedCorpId ||
item.credentials.corpId === selectedCorpId
);
}
if (corp) return corp;
throw new Error(`未找到企业 ID 为 ${selectedCorpId} 的企业配置`);
throw new Error(`未找到企业或身份标识为 [${selectedCorpId}] 的企业配置`);
}
if (!options.stateful) {
+4 -1
View File
@@ -16,8 +16,11 @@ export const CorpAuthConfigSchema = z.object({
});
export const CorpConfigSchema = z.object({
id: z.string().describe("企业 ID"),
id: z.string().describe("配置/身份唯一标识 (默认等于 corpId,同企业多身份时形如 corpId@accountId 或 corpId:staffId)"),
name: z.string().describe("企业名称"),
corpId: z.string().optional().describe("底层企业物理 ID (未填时默认等于 id)"),
userId: z.string().optional().describe("所属用户 ID"),
staffId: z.string().optional().describe("员工工号 (默认取 credentials.staffId)"),
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("所属主账号标识(如手机号)"),
+25
View File
@@ -37,6 +37,31 @@ export function createAuthClient(options: CreateAuthClientOptions): KyInstance {
}
},
],
afterResponse: [
async ({ request, response }) => {
if (!response) return response;
const errorType = response.headers.get("error-type");
const isAuthError =
response.status === 401 ||
errorType === "UnauthenticatedException" ||
errorType === "UnauthorizedException";
if (isAuthError && options.onUnauthorized) {
// 触发自动续杯刷新 Token
await options.onUnauthorized();
// 用新 Token 重新发送一次请求
const freshHeaders = await options.getHeaders();
for (const [key, value] of Object.entries(freshHeaders)) {
if (value !== undefined) {
request.headers.set(key, value);
}
}
return ky(request);
}
return response;
},
],
beforeRetry: [
async ({ request }) => {
if (options.onUnauthorized) {