From b7a3bf2c037e340abecad98e7fa4a59f74ecaa54 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Thu, 27 Aug 2026 11:04:41 +0800 Subject: [PATCH] =?UTF-8?q?feat(auth):=20=E5=AE=9E=E7=8E=B0=E5=85=A8?= =?UTF-8?q?=E8=87=AA=E5=8A=A8=E6=97=A0=E6=84=9F=E7=BB=AD=E6=9D=AF=20(401/?= =?UTF-8?q?=E5=8D=B3=E5=B0=86=E8=BF=87=E6=9C=9F=E8=87=AA=E5=8A=A8=E9=87=8D?= =?UTF-8?q?=E8=AF=95=E6=8D=A2=E7=A5=A8)=20=E4=B8=8E=E4=BC=81=E4=B8=9A?= =?UTF-8?q?=E5=A4=9A=E8=BA=AB=E4=BB=BD=E5=94=AF=E4=B8=80=E6=A0=87=E8=AF=86?= =?UTF-8?q?=E5=88=86=E5=B1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/core/auth/easo.ts | 13 +++++++---- src/core/auth/ekb.ts | 25 +++++++++++++++----- src/core/auth/login.ts | 48 ++++++++++++++++++++++++++++++++++++++ src/core/auth/piper.ts | 10 +++++--- src/core/config/manager.ts | 13 +++++++++-- src/core/config/types.ts | 5 +++- src/core/http/factory.ts | 25 ++++++++++++++++++++ 7 files changed, 122 insertions(+), 17 deletions(-) diff --git a/src/core/auth/easo.ts b/src/core/auth/easo.ts index c13a4cd..71d7e30 100644 --- a/src/core/auth/easo.ts +++ b/src/core/auth/easo.ts @@ -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: () => { diff --git a/src/core/auth/ekb.ts b/src/core/auth/ekb.ts index bcccec2..c105158 100644 --- a/src/core/auth/ekb.ts +++ b/src/core/auth/ekb.ts @@ -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 { 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); + }, }); } diff --git a/src/core/auth/login.ts b/src/core/auth/login.ts index 16615d1..ca6abbb 100644 --- a/src/core/auth/login.ts +++ b/src/core/auth/login.ts @@ -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 { + 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 { diff --git a/src/core/auth/piper.ts b/src/core/auth/piper.ts index 80bb3d8..c3e7063 100644 --- a/src/core/auth/piper.ts +++ b/src/core/auth/piper.ts @@ -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); diff --git a/src/core/config/manager.ts b/src/core/config/manager.ts index cd5efcd..0775166 100644 --- a/src/core/config/manager.ts +++ b/src/core/config/manager.ts @@ -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) { diff --git a/src/core/config/types.ts b/src/core/config/types.ts index 083075a..7d19fc8 100644 --- a/src/core/config/types.ts +++ b/src/core/config/types.ts @@ -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("所属主账号标识(如手机号)"), diff --git a/src/core/http/factory.ts b/src/core/http/factory.ts index 14b1db9..335e821 100644 --- a/src/core/http/factory.ts +++ b/src/core/http/factory.ts @@ -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) {