oauthService.ts 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193
  1. /* eslint-disable max-lines -- OAuthService 集中维护 OAuth 会话生命周期和 provider 切换边界,当前 review 修复只收窄后台迁移写入条件。 */
  2. import { randomBytes } from "node:crypto";
  3. import {
  4. ApiError,
  5. formatLogPrefix,
  6. type ApiClient,
  7. BIGMODEL_PROVIDER_ID,
  8. ZAI_PROVIDER_ID,
  9. type OAuthCallbackResult,
  10. type OAuthCachedSessionRestoreResult,
  11. type OAuthProviderId,
  12. type OAuthProviderMeta,
  13. type OAuthStartResponse,
  14. type OAuthTokenSet,
  15. type OAuthUserProfile,
  16. type UserInfo,
  17. resolveJwtExpiration,
  18. } from "@zcode/shared";
  19. import type { ICredentialService } from "../credential/credential.js";
  20. import { createServiceLogger } from "../logger/serviceLogger.js";
  21. import { readApiJson } from "../providers/api/apiJson.js";
  22. import type { IOAuthService } from "./oauth.js";
  23. import { isCurrentOAuthCredentialRequest } from "#src/oauth/oauthUnauthorizedRequest.js";
  24. import { hasOAuthAuthorizationCode, parseOAuthLoginAttribution } from "./callbackAttribution.js";
  25. import {
  26. refreshLegacyBigModelCachedProfile,
  27. withProviderProfileSchema,
  28. } from "./oauthProfileSchema.js";
  29. import { createOAuthProviderAdapters, type OAuthProviderAdapter } from "./providers/index.js";
  30. import { OAuthCredentialRepo } from "./repo/oauthCredentialRepo.js";
  31. import { createOAuthRuntimeConfig } from "./runtimeConfig.js";
  32. import {
  33. buildDesktopOAuthRedirectUriFromEnv,
  34. buildZCodeApiUrlFromEnv,
  35. } from "./providers/configUtils.js";
  36. /** OAuth 超时时间(5 分钟) */
  37. const OAUTH_TIMEOUT_MS = 5 * 60 * 1000;
  38. const COMPLETED_POLLING_STATE_GRACE_MS = 30 * 1000;
  39. const ZCODE_JWT_TOKEN_KEY = "zcodejwttoken";
  40. const log = (...args: unknown[]) =>
  41. console.log(formatLogPrefix("oauthService", process.pid), ...args);
  42. const serviceLog = createServiceLogger("oauthService");
  43. interface PendingState {
  44. state: string;
  45. provider: OAuthProviderId;
  46. timeout: NodeJS.Timeout;
  47. phase: "awaiting-attribution-or-code" | "awaiting-code-after-attribution";
  48. completionPromise?: Promise<OAuthCallbackResult | null>;
  49. polling?: {
  50. expiresAt: number;
  51. flowId: string;
  52. nextPollAt: number;
  53. pollIntervalMs: number;
  54. pollToken: string;
  55. pollUrl: string;
  56. };
  57. }
  58. interface OAuthFlowEnvelope {
  59. code?: unknown;
  60. msg?: unknown;
  61. data?: unknown;
  62. }
  63. interface OAuthServiceDependencies {
  64. adapters?: OAuthProviderAdapter[];
  65. apiClient?: ApiClient;
  66. now?: () => number;
  67. env?: NodeJS.ProcessEnv;
  68. onProviderLogout?: (provider: OAuthProviderId, accountIdentity?: string | null) => Promise<void>;
  69. }
  70. function readTrimmedString(value: unknown): string | null {
  71. return typeof value === "string" && value.trim() ? value.trim() : null;
  72. }
  73. function isUnknownRecord(value: unknown): value is Record<string, unknown> {
  74. return typeof value === "object" && value !== null;
  75. }
  76. function toUserInfo(profile: OAuthUserProfile): UserInfo {
  77. return {
  78. id: profile.id,
  79. username: profile.username,
  80. displayName: profile.displayName,
  81. ...(profile.avatarUrl ? { avatarUrl: profile.avatarUrl } : {}),
  82. };
  83. }
  84. function isSameOAuthProfile(left: OAuthUserProfile, right: OAuthUserProfile): boolean {
  85. return (
  86. left.id === right.id &&
  87. left.username === right.username &&
  88. left.displayName === right.displayName &&
  89. left.avatarUrl === right.avatarUrl &&
  90. JSON.stringify(left.rawProfile ?? null) === JSON.stringify(right.rawProfile ?? null)
  91. );
  92. }
  93. function resolveInactiveOAuthProvider(provider: OAuthProviderId): OAuthProviderId | null {
  94. if (provider === ZAI_PROVIDER_ID) {
  95. return BIGMODEL_PROVIDER_ID;
  96. }
  97. if (provider === BIGMODEL_PROVIDER_ID) {
  98. return ZAI_PROVIDER_ID;
  99. }
  100. return null;
  101. }
  102. /**
  103. * OAuth 认证服务实现
  104. *
  105. * 在 host process 中运行,管理 OAuth 流程的完整生命周期。
  106. */
  107. export class OAuthService implements IOAuthService {
  108. private readonly credentialService: ICredentialService;
  109. private readonly repo: OAuthCredentialRepo;
  110. private readonly adapters = new Map<OAuthProviderId, OAuthProviderAdapter>();
  111. private readonly now: () => number;
  112. private readonly onProviderLogout?: (
  113. provider: OAuthProviderId,
  114. accountIdentity?: string | null,
  115. ) => Promise<void>;
  116. private readonly apiClient?: ApiClient;
  117. private readonly env: NodeJS.ProcessEnv;
  118. private pendingState: PendingState | null = null;
  119. private oauthFlowStartGeneration = 0;
  120. private oauthFlowStartProvider: OAuthProviderId | null = null;
  121. private oauthSessionGeneration = 0;
  122. private sessionMutationQueue: Promise<unknown> = Promise.resolve();
  123. private recentlyCompletedPollingState: {
  124. generation: number;
  125. expiresAt: number;
  126. provider: OAuthProviderId;
  127. state: string;
  128. } | null = null;
  129. constructor(credentialService: ICredentialService, dependencies: OAuthServiceDependencies = {}) {
  130. this.credentialService = credentialService;
  131. this.now = dependencies.now ?? Date.now;
  132. this.onProviderLogout = dependencies.onProviderLogout;
  133. this.apiClient = dependencies.apiClient;
  134. this.env = dependencies.env ?? process.env;
  135. const adapters =
  136. dependencies.adapters ??
  137. createOAuthProviderAdapters(createOAuthRuntimeConfig(dependencies.env), {
  138. apiClient: dependencies.apiClient,
  139. });
  140. for (const adapter of adapters) {
  141. this.adapters.set(adapter.providerId, adapter);
  142. }
  143. this.repo = new OAuthCredentialRepo(credentialService, {
  144. providerIds: adapters.map((adapter) => adapter.providerId),
  145. onCorruptOAuthSessionCleared: async (providers) => {
  146. // 本地 OAuth 凭据解密失败后等价于强制 logout。
  147. // repo 只能清 OAuth 命名空间,派生的 Start/Coding Plan provider key 必须回到 service 层清理。
  148. await this.notifyProvidersLogout(providers);
  149. },
  150. });
  151. }
  152. async getProviders(): Promise<OAuthProviderMeta[]> {
  153. return [...this.adapters.values()]
  154. .map((adapter) => adapter.meta)
  155. .filter((meta) => meta.enabled)
  156. .sort((a, b) => a.order - b.order);
  157. }
  158. async getActiveProvider(): Promise<OAuthProviderId | null> {
  159. return this.repo.getActiveProvider();
  160. }
  161. async restoreCachedSession(): Promise<UserInfo | null> {
  162. const result = await this.restoreCachedSessionState();
  163. return result.status === "authenticated" ? result.userInfo : null;
  164. }
  165. async restoreCachedSessionState(): Promise<OAuthCachedSessionRestoreResult> {
  166. const restoreGeneration = this.oauthSessionGeneration;
  167. const activeProvider = await this.repo.getActiveProvider();
  168. if (!activeProvider) {
  169. log("restoreCachedSession skipped: no active provider");
  170. return { status: "signed-out" };
  171. }
  172. const adapter = this.adapters.get(activeProvider);
  173. if (!adapter || !adapter.meta.enabled) {
  174. log(
  175. "restoreCachedSession aborted: provider unavailable, clearing active provider:",
  176. activeProvider,
  177. );
  178. await this.repo.setActiveProvider(null);
  179. return { status: "signed-out" };
  180. }
  181. const profile = await this.repo.loadActiveUserProfile();
  182. if (!profile) {
  183. // zai / bigmodel 这类 OAuth token 生命周期很短,启动时如果强依赖远端 userinfo 校验,
  184. // 用户明明刚登录过,也会因为 access_token 过期被误判成未登录。
  185. // 这里改为优先读取登录成功时持久化的 user_info,只要用户没有手动退出,就按缓存恢复展示态。
  186. log("restoreCachedSession skipped: missing cached user profile:", activeProvider);
  187. return { status: "signed-out" };
  188. }
  189. // 启动缓存恢复只需要检查共享 zcode JWT;若通过 loadActiveTokenSet 连带读取
  190. // provider access token,会把原本后台执行的 BigModel profile 迁移重新阻塞到首屏恢复链路。
  191. const zcodeJwtToken = (await this.credentialService.load(ZCODE_JWT_TOKEN_KEY))?.trim() ?? "";
  192. if (zcodeJwtToken && resolveJwtExpiration(zcodeJwtToken, this.now()).kind === "expired") {
  193. serviceLog.info("cached session invalidated because zcode JWT expired", {
  194. provider: activeProvider,
  195. });
  196. const invalidated = await this.invalidateExpiredCachedSession(
  197. restoreGeneration,
  198. activeProvider,
  199. profile,
  200. zcodeJwtToken,
  201. );
  202. if (!invalidated) {
  203. return this.restoreCachedSessionState();
  204. }
  205. return { status: "reauthentication-required", reason: "jwt-expired" };
  206. }
  207. if (activeProvider === BIGMODEL_PROVIDER_ID) {
  208. const migrationGeneration = this.oauthSessionGeneration;
  209. void refreshLegacyBigModelCachedProfile({
  210. adapter,
  211. cachedProfile: profile,
  212. loadTokenSet: () =>
  213. this.loadBigModelCachedProfileMigrationTokenSet(migrationGeneration, profile),
  214. now: this.now,
  215. runWithAdapterError: (run) => this.runWithAdapterError(adapter, run),
  216. saveProfile: (nextProfile) =>
  217. this.saveBigModelCachedProfileMigration(migrationGeneration, profile, nextProfile),
  218. })
  219. .then((migratedProfile) => {
  220. if (migratedProfile !== profile) {
  221. log(
  222. "restoreCachedSession migrated cached profile:",
  223. activeProvider,
  224. migratedProfile.id,
  225. );
  226. }
  227. })
  228. .catch((error: unknown) => {
  229. log(
  230. "restoreCachedSession background profile migration failed:",
  231. activeProvider,
  232. error instanceof Error ? error.message : String(error),
  233. );
  234. });
  235. }
  236. if (activeProvider === ZAI_PROVIDER_ID) {
  237. if (!zcodeJwtToken) {
  238. // sidebar 登录入口之前只看缓存 user_info,会把“缺少 zcodejwttoken”的状态误判成已登录。
  239. // 这里补充 zcodejwttoken 门槛,确保没有后端 JWT 时统一按未登录处理。
  240. log("restoreCachedSession skipped: missing zcodejwttoken:", activeProvider);
  241. return { status: "signed-out" };
  242. }
  243. }
  244. log("restoreCachedSession restored:", activeProvider, profile.id);
  245. return { status: "authenticated", userInfo: toUserInfo(profile) };
  246. }
  247. private async invalidateExpiredCachedSession(
  248. expectedGeneration: number,
  249. expectedProvider: OAuthProviderId,
  250. expectedProfile: OAuthUserProfile,
  251. expectedJwt: string,
  252. ): Promise<boolean> {
  253. const invalidated = await this.runSessionMutation(async () => {
  254. const currentProvider = await this.repo.getActiveProvider();
  255. const currentProfile = await this.repo.loadUserProfile(expectedProvider);
  256. const currentJwt = (await this.credentialService.load(ZCODE_JWT_TOKEN_KEY))?.trim() ?? "";
  257. if (
  258. this.oauthSessionGeneration !== expectedGeneration ||
  259. currentProvider !== expectedProvider ||
  260. !currentProfile ||
  261. !isSameOAuthProfile(currentProfile, expectedProfile) ||
  262. currentJwt !== expectedJwt
  263. ) {
  264. // 启动恢复读取过期凭据后,新登录或 provider 切换可能已经完成;
  265. // 旧恢复任务只能清理仍与其快照完全一致的会话,不能误删刚写入的新认证状态。
  266. serviceLog.info("skipped stale expired JWT session invalidation", {
  267. provider: expectedProvider,
  268. });
  269. return false;
  270. }
  271. this.oauthSessionGeneration += 1;
  272. await this.repo.clearActiveSession();
  273. return true;
  274. });
  275. if (!invalidated) {
  276. return false;
  277. }
  278. await this.cancelPending(expectedProvider);
  279. try {
  280. await this.notifyProviderLogout(expectedProvider, expectedProfile.id);
  281. } catch (error) {
  282. // JWT 已过期时主认证事实必须先失效;派生 provider 清理失败不能把 UI 留在伪登录态。
  283. serviceLog.warn("expired JWT derived provider cleanup failed", {
  284. provider: expectedProvider,
  285. error,
  286. });
  287. }
  288. return true;
  289. }
  290. private async loadBigModelCachedProfileMigrationTokenSet(
  291. expectedGeneration: number,
  292. expectedCachedProfile: OAuthUserProfile,
  293. ): Promise<OAuthTokenSet | null> {
  294. return this.runSessionMutation(async () => {
  295. if (this.oauthSessionGeneration !== expectedGeneration) {
  296. log("restoreCachedSession skipped stale BigModel token migration");
  297. return null;
  298. }
  299. const activeProvider = await this.repo.getActiveProvider();
  300. const currentProfile = await this.repo.loadUserProfile(BIGMODEL_PROVIDER_ID);
  301. if (
  302. activeProvider !== BIGMODEL_PROVIDER_ID ||
  303. !currentProfile ||
  304. !isSameOAuthProfile(currentProfile, expectedCachedProfile)
  305. ) {
  306. // 迁移请求目标固定是 BigModel,token 也必须固定读取 BigModel 命名空间;
  307. // 发请求前先复核持久化快照,避免切换到 ZAI 后把其他 provider token 发给 BigModel。
  308. log("restoreCachedSession skipped stale BigModel token migration:", activeProvider);
  309. return null;
  310. }
  311. return this.repo.loadTokenSet(BIGMODEL_PROVIDER_ID);
  312. });
  313. }
  314. private async saveBigModelCachedProfileMigration(
  315. expectedGeneration: number,
  316. expectedCachedProfile: OAuthUserProfile,
  317. nextProfile: OAuthUserProfile,
  318. ): Promise<void> {
  319. await this.runSessionMutation(async () => {
  320. if (this.oauthSessionGeneration !== expectedGeneration) {
  321. log("restoreCachedSession skipped stale BigModel profile migration");
  322. return;
  323. }
  324. const activeProvider = await this.repo.getActiveProvider();
  325. if (activeProvider !== BIGMODEL_PROVIDER_ID) {
  326. log("restoreCachedSession skipped stale BigModel profile migration:", activeProvider);
  327. return;
  328. }
  329. const currentProfile = await this.repo.loadUserProfile(BIGMODEL_PROVIDER_ID);
  330. if (!currentProfile || !isSameOAuthProfile(currentProfile, expectedCachedProfile)) {
  331. // BigModel 旧缓存迁移在后台完成,期间用户可能 logout、切到 ZAI,
  332. // 或重新登录 BigModel。只有当前缓存仍是启动时那份旧缓存时,旧迁移结果才允许落盘。
  333. log("restoreCachedSession skipped outdated BigModel profile migration");
  334. return;
  335. }
  336. await this.repo.saveUserProfile(BIGMODEL_PROVIDER_ID, nextProfile);
  337. });
  338. }
  339. private runSessionMutation<T>(run: () => Promise<T>): Promise<T> {
  340. // 后台 profile 迁移、logout、provider 切换都会改 OAuth 凭据;
  341. // 必须串行化,避免旧迁移在退出或切换清理之后重新写回 user_info。
  342. const next = this.sessionMutationQueue.catch(() => undefined).then(run);
  343. this.sessionMutationQueue = next.catch(() => undefined);
  344. return next;
  345. }
  346. private async persistOAuthSession(
  347. provider: OAuthProviderId,
  348. tokenSet: OAuthTokenSet,
  349. profile: OAuthUserProfile,
  350. isStillCurrent?: () => boolean,
  351. ): Promise<void> {
  352. const inactiveProvider = resolveInactiveOAuthProvider(provider);
  353. const previousTokenSet = await this.repo.loadTokenSet(provider);
  354. const previousProfile = await this.repo.loadUserProfile(provider);
  355. const previousInactiveTokenSet = inactiveProvider
  356. ? await this.repo.loadTokenSet(inactiveProvider)
  357. : null;
  358. const previousInactiveProfile = inactiveProvider
  359. ? await this.repo.loadUserProfile(inactiveProvider)
  360. : null;
  361. const previousActiveProvider = await this.repo.getActiveProvider();
  362. const rollback = async () => {
  363. if (previousTokenSet) await this.repo.saveTokenSet(provider, previousTokenSet);
  364. else await this.repo.clearProvider(provider);
  365. if (previousProfile) await this.repo.saveUserProfile(provider, previousProfile);
  366. else await this.repo.clearUserProfile(provider);
  367. if (inactiveProvider) {
  368. if (previousInactiveTokenSet)
  369. await this.repo.saveTokenSet(inactiveProvider, previousInactiveTokenSet);
  370. else await this.repo.clearProvider(inactiveProvider);
  371. if (previousInactiveProfile)
  372. await this.repo.saveUserProfile(inactiveProvider, previousInactiveProfile);
  373. else await this.repo.clearUserProfile(inactiveProvider);
  374. }
  375. if (previousActiveProvider) await this.repo.setActiveProvider(previousActiveProvider);
  376. else await this.repo.setActiveProvider(null);
  377. };
  378. const assertCurrent = async () => {
  379. if (isStillCurrent && !isStillCurrent()) {
  380. await rollback();
  381. throw new Error("OAuth flow 已取消");
  382. }
  383. };
  384. this.oauthSessionGeneration += 1;
  385. if (inactiveProvider) {
  386. await assertCurrent();
  387. // ZAI 与 BigModel 是互斥身份域。切换 provider 时必须先清旧 provider,
  388. // 再保存当前 token;反序会让 clearProvider 误删共享的 zcodejwttoken。
  389. await this.repo.clearProvider(inactiveProvider);
  390. }
  391. await assertCurrent();
  392. await this.repo.saveTokenSet(provider, tokenSet);
  393. await assertCurrent();
  394. await this.repo.saveUserProfile(provider, withProviderProfileSchema(provider, profile));
  395. await assertCurrent();
  396. await this.repo.setActiveProvider(provider);
  397. if (isStillCurrent && !isStillCurrent()) {
  398. // active provider 写入无法被底层 credential IO 取消;失效 flow 不能仅按
  399. // provider 清理,否则同 provider 的新 flow 可能被旧 flow 误删。
  400. await rollback();
  401. throw new Error("OAuth flow 已取消");
  402. }
  403. }
  404. private async runPendingSessionCompletion(
  405. pending: PendingState,
  406. complete: () => Promise<{ tokenSet: OAuthTokenSet; profile: OAuthUserProfile }>,
  407. preserveAttribution?: () => Promise<void>,
  408. ): Promise<OAuthCallbackResult | null> {
  409. const completion = this.runSessionMutation(async () => {
  410. // polling 与 deep link 可能同时完成,也可能在等待期间开始新登录。
  411. // 只有仍指向同一 pending 对象的路径能落盘,防止迟到结果覆盖更新的登录选择。
  412. if (this.pendingState !== pending) {
  413. if (
  414. !this.pendingState &&
  415. this.recentlyCompletedPollingState?.state === pending.state &&
  416. this.recentlyCompletedPollingState.generation === this.oauthFlowStartGeneration
  417. ) {
  418. // 回调入队时已通过有效性检查,不能因队列等待超过去重窗口而丢失归因。
  419. await preserveAttribution?.();
  420. return { kind: "duplicate" as const, provider: pending.provider };
  421. }
  422. return null;
  423. }
  424. await preserveAttribution?.();
  425. if (this.pendingState !== pending) return null;
  426. const { tokenSet, profile } = await complete();
  427. // exchangeToken 期间用户可能取消或切换到新 flow;旧请求返回后必须再次校验,
  428. // 否则已取消的登录仍会把旧凭据写回本地。
  429. if (this.pendingState !== pending) {
  430. return null;
  431. }
  432. await this.persistOAuthSession(
  433. pending.provider,
  434. tokenSet,
  435. profile,
  436. () => this.pendingState === pending,
  437. );
  438. if (this.pendingState === pending) {
  439. this.clearPendingState();
  440. }
  441. this.recentlyCompletedPollingState = {
  442. generation: this.oauthFlowStartGeneration,
  443. expiresAt: this.now() + COMPLETED_POLLING_STATE_GRACE_MS,
  444. provider: pending.provider,
  445. state: pending.state,
  446. };
  447. return {
  448. kind: "session" as const,
  449. provider: pending.provider,
  450. userInfo: toUserInfo(profile),
  451. };
  452. });
  453. // 共享首个兑换 Promise 会让失败传播给另一条已拿到凭据的路径。
  454. // 复用会话串行队列,每个候选独立执行;失败只在已排队候选均失败后向 UI 报告。
  455. pending.completionPromise = completion;
  456. try {
  457. return await completion;
  458. } catch (error) {
  459. const fallback = pending.completionPromise;
  460. if (fallback && fallback !== completion) {
  461. try {
  462. await fallback;
  463. } catch {
  464. // 两条路径均失败时保留各自的错误,不能让备用路径覆盖首条失败原因。
  465. throw error;
  466. }
  467. if (
  468. !this.pendingState &&
  469. this.recentlyCompletedPollingState?.state === pending.state &&
  470. this.recentlyCompletedPollingState.generation === this.oauthFlowStartGeneration
  471. ) {
  472. return { kind: "duplicate", provider: pending.provider };
  473. }
  474. if (this.pendingState !== pending) return null;
  475. }
  476. throw error;
  477. } finally {
  478. if (pending.completionPromise === completion) pending.completionPromise = undefined;
  479. }
  480. }
  481. async restoreSession(): Promise<UserInfo | null> {
  482. const activeProvider = await this.repo.getActiveProvider();
  483. if (!activeProvider) {
  484. log("restoreSession skipped: no active provider");
  485. return null;
  486. }
  487. log("restoreSession started:", activeProvider);
  488. const adapter = this.adapters.get(activeProvider);
  489. if (!adapter || !adapter.meta.enabled) {
  490. log(
  491. "restoreSession aborted: provider unavailable, clearing active provider:",
  492. activeProvider,
  493. );
  494. await this.repo.setActiveProvider(null);
  495. return null;
  496. }
  497. let tokenSet = await this.repo.loadActiveTokenSet();
  498. if (!tokenSet && adapter.loadLegacyTokenSet) {
  499. log("restoreSession fallback: trying provider legacy token set:", activeProvider);
  500. tokenSet = await adapter.loadLegacyTokenSet((key) => this.credentialService.load(key));
  501. // 多 provider 改造后,旧版 BigModel 仍可能只保留 legacy token key。
  502. // 这里在 provider 兼容读取成功后回填命名空间 key,避免每次启动都重复走 legacy 分支。
  503. if (tokenSet) {
  504. log("restoreSession fallback hit: migrating legacy token set:", activeProvider);
  505. await this.repo.saveActiveTokenSet(tokenSet);
  506. await this.repo.saveTokenSet(activeProvider, tokenSet);
  507. }
  508. }
  509. if (!tokenSet || !adapter.fetchUserInfo) {
  510. log(
  511. "restoreSession failed: missing token or user-info capability, logging out:",
  512. activeProvider,
  513. );
  514. await this.logout();
  515. return null;
  516. }
  517. try {
  518. log("restoreSession validating token with provider userinfo endpoint:", activeProvider);
  519. const profile = await this.runWithAdapterError(adapter, () =>
  520. adapter.fetchUserInfo!(tokenSet, {
  521. providerId: activeProvider,
  522. state: "",
  523. redirectUri: adapter.redirectUri,
  524. now: this.now,
  525. }),
  526. );
  527. await this.repo.saveActiveUserProfile(withProviderProfileSchema(activeProvider, profile));
  528. await this.repo.setActiveProvider(activeProvider);
  529. log("restoreSession validated:", activeProvider, profile.id);
  530. return toUserInfo(profile);
  531. } catch (error) {
  532. const normalized = adapter.normalizeError(error);
  533. // 启动恢复只看本地凭据会把“过期 token”误判成已登录。
  534. // 当远端明确返回未授权(401/403)时,立即按退出流程清理本地登录态。
  535. if (this.isUnauthorizedError(normalized)) {
  536. log("restoreSession unauthorized, logging out:", activeProvider, normalized.message);
  537. await this.logout();
  538. return null;
  539. }
  540. log("restoreSession validation error:", activeProvider, normalized.message);
  541. throw normalized;
  542. }
  543. }
  544. async startOAuth(provider: OAuthProviderId): Promise<OAuthStartResponse> {
  545. return this.startOAuthInternal(provider);
  546. }
  547. async startOAuthWithPolling(provider: OAuthProviderId): Promise<OAuthStartResponse> {
  548. if (provider !== ZAI_PROVIDER_ID && provider !== BIGMODEL_PROVIDER_ID) {
  549. return this.startOAuthInternal(provider);
  550. }
  551. const adapter = this.getEnabledAdapter(provider);
  552. if (!this.apiClient) {
  553. throw new Error("ApiClient 注入缺失:OAuth polling 必须通过 Providers 传入 apiClient");
  554. }
  555. // 两个 init 并发时,先发但后返回的旧响应会覆盖较新的 pending flow。
  556. // generation 让最后一次用户操作拥有 flow,旧响应只结束自己的调用方。
  557. const startGeneration = ++this.oauthFlowStartGeneration;
  558. this.oauthFlowStartProvider = provider;
  559. this.clearPendingState();
  560. const pollToken = randomBytes(32).toString("hex");
  561. const initUrl = buildZCodeApiUrlFromEnv(this.env, "/api/v1/oauth/cli/init");
  562. const envelope = await readApiJson<OAuthFlowEnvelope>(this.apiClient, initUrl, {
  563. method: "POST",
  564. headers: {
  565. Authorization: `Bearer ${pollToken}`,
  566. "Content-Type": "application/json",
  567. },
  568. body: JSON.stringify({ provider }),
  569. });
  570. if (this.oauthFlowStartGeneration !== startGeneration) {
  571. throw new Error("OAuth flow 已被新的登录请求替换");
  572. }
  573. this.oauthFlowStartProvider = null;
  574. const data = envelope.data;
  575. if (
  576. envelope.code !== 0 ||
  577. !isUnknownRecord(data) ||
  578. !readTrimmedString(data.flow_id) ||
  579. !readTrimmedString(data.authorize_url) ||
  580. !Number.isFinite(data.expires_at) ||
  581. !Number.isFinite(data.poll_interval_sec)
  582. ) {
  583. throw new Error(readTrimmedString(envelope.msg) || "OAuth flow 初始化响应无效");
  584. }
  585. const flowId = readTrimmedString(data.flow_id)!;
  586. const authorizeUrlString = readTrimmedString(data.authorize_url)!;
  587. const expiresAt = (data.expires_at as number) * 1_000;
  588. const pollIntervalMs = (data.poll_interval_sec as number) * 1_000;
  589. let authorizeUrl: URL;
  590. try {
  591. authorizeUrl = new URL(authorizeUrlString);
  592. } catch {
  593. throw new Error("OAuth flow 初始化响应无效");
  594. }
  595. if (provider === BIGMODEL_PROVIDER_ID) {
  596. // BigModel CLI callback 的失败页会截断原有 Desktop deep link 回调体验。
  597. // flow 仍由 Host 轮询,但浏览器回调恢复到官网中转页,再透传到 zcode://oauth/callback。
  598. authorizeUrl.searchParams.set("redirect", buildDesktopOAuthRedirectUriFromEnv(this.env));
  599. } else if (provider === ZAI_PROVIDER_ID) {
  600. // Z.AI 后端 init 仍可能返回 provider-specific callback,导致回跳行为与 BigModel 不一致。
  601. // Desktop 统一改写为官网中转页,再由官网透传到 zcode://oauth/callback。
  602. authorizeUrl.searchParams.set("redirect_uri", buildDesktopOAuthRedirectUriFromEnv(this.env));
  603. }
  604. const state = authorizeUrl.searchParams.get("state")?.trim();
  605. const remainingLifetimeMs = expiresAt - this.now();
  606. if (
  607. authorizeUrl.protocol !== "https:" ||
  608. !state ||
  609. !Number.isFinite(expiresAt) ||
  610. !Number.isFinite(pollIntervalMs) ||
  611. remainingLifetimeMs <= 0 ||
  612. pollIntervalMs < 1_000 ||
  613. pollIntervalMs >= remainingLifetimeMs
  614. ) {
  615. throw new Error("OAuth flow 初始化响应无效");
  616. }
  617. const timeoutMs = Math.min(OAUTH_TIMEOUT_MS, remainingLifetimeMs);
  618. const timeout = setTimeout(() => {
  619. const pending = this.pendingState;
  620. // polling flow 超时必须立即收口,不能等待下一次 UI 轮询;同时校验 flowId,避免旧定时器清掉新 flow。
  621. if (pending?.state === state && pending.polling?.flowId === flowId) {
  622. this.clearPendingState();
  623. }
  624. }, timeoutMs);
  625. this.pendingState = {
  626. state,
  627. provider: adapter.providerId,
  628. timeout,
  629. phase: "awaiting-attribution-or-code",
  630. polling: {
  631. expiresAt,
  632. flowId,
  633. nextPollAt: this.now(),
  634. pollIntervalMs,
  635. pollToken,
  636. pollUrl: buildZCodeApiUrlFromEnv(
  637. this.env,
  638. `/api/v1/oauth/cli/poll/${encodeURIComponent(flowId)}`,
  639. ),
  640. },
  641. };
  642. serviceLog.info("OAuth polling flow started", {
  643. expiresInMs: timeoutMs,
  644. pollIntervalMs,
  645. provider,
  646. });
  647. return { provider, authorizeUrl: authorizeUrl.toString(), state };
  648. }
  649. async pollPendingOAuth(): Promise<OAuthCallbackResult | null> {
  650. const apiClient = this.apiClient;
  651. if (!apiClient) {
  652. return null;
  653. }
  654. const pending = this.pendingState;
  655. const polling = pending?.polling;
  656. if (!pending || !polling) {
  657. return null;
  658. }
  659. if (this.now() >= polling.expiresAt) {
  660. this.clearPendingState();
  661. throw new Error("OAuth flow 已过期");
  662. }
  663. if (this.now() < polling.nextPollAt) {
  664. return null;
  665. }
  666. polling.nextPollAt = this.now() + polling.pollIntervalMs;
  667. let envelope: OAuthFlowEnvelope;
  668. try {
  669. envelope = await readApiJson<OAuthFlowEnvelope>(apiClient, polling.pollUrl, {
  670. headers: { Authorization: `Bearer ${polling.pollToken}` },
  671. });
  672. } catch (error) {
  673. if (this.pendingState !== pending) return null;
  674. if (
  675. error instanceof ApiError &&
  676. error.status &&
  677. error.status >= 400 &&
  678. error.status < 500 &&
  679. error.status !== 408 &&
  680. error.status !== 429
  681. ) {
  682. try {
  683. return await this.runPendingSessionCompletion(pending, async () => {
  684. throw error;
  685. });
  686. } catch (terminalError) {
  687. if (this.pendingState === pending) this.clearPendingState();
  688. throw terminalError;
  689. }
  690. }
  691. // 轮询是 deep link 丢失时的可靠路径,单次断网或 5xx 不能立即取消 flow。
  692. // 保留服务端下发的查询间隔,下一轮继续尝试;高频状态只记 debug,避免生产日志膨胀。
  693. serviceLog.debug("OAuth polling request will retry", {
  694. error: error instanceof Error ? error.message : String(error),
  695. provider: pending.provider,
  696. });
  697. return null;
  698. }
  699. if (this.pendingState !== pending) {
  700. return null;
  701. }
  702. if (
  703. envelope.code === 0 &&
  704. isUnknownRecord(envelope.data) &&
  705. readTrimmedString(envelope.data.status) === "pending"
  706. ) {
  707. return null;
  708. }
  709. try {
  710. const result = await this.runPendingSessionCompletion(pending, async () => {
  711. const pollData = envelope.data;
  712. if (envelope.code !== 0 || !isUnknownRecord(pollData)) {
  713. throw new Error(readTrimmedString(envelope.msg) || "OAuth flow 查询响应无效");
  714. }
  715. const status = readTrimmedString(pollData.status);
  716. if (status === "failed") {
  717. throw new Error("OAuth flow 授权失败");
  718. }
  719. if (status !== "ready") {
  720. throw new Error("OAuth flow 查询响应无效");
  721. }
  722. const ready = pollData;
  723. const user = isUnknownRecord(ready.user) ? ready.user : null;
  724. const zai = isUnknownRecord(ready.zai) ? ready.zai : null;
  725. const bigmodel = isUnknownRecord(ready.bigmodel) ? ready.bigmodel : null;
  726. const providerAccessToken =
  727. pending.provider === ZAI_PROVIDER_ID
  728. ? readTrimmedString(zai?.access_token)
  729. : readTrimmedString(bigmodel?.access_token) || readTrimmedString(bigmodel?.accessToken);
  730. const zcodeJwtToken = readTrimmedString(ready.token);
  731. const userId = readTrimmedString(user?.user_id);
  732. if (!zcodeJwtToken || !providerAccessToken || !userId) {
  733. throw new Error("OAuth flow 查询响应无效");
  734. }
  735. const username = readTrimmedString(user?.name) || readTrimmedString(user?.email) || userId;
  736. const avatarUrl = readTrimmedString(user?.avatar);
  737. const profile: OAuthUserProfile = {
  738. id: userId,
  739. username,
  740. displayName: username,
  741. ...(avatarUrl ? { avatarUrl } : {}),
  742. rawProfile: user,
  743. };
  744. const adapter = this.getAdapter(pending.provider);
  745. const refreshToken =
  746. pending.provider === BIGMODEL_PROVIDER_ID
  747. ? readTrimmedString(bigmodel?.refresh_token) ||
  748. readTrimmedString(bigmodel?.refreshToken)
  749. : undefined;
  750. const tokenSet = adapter.normalizePolledTokenSet
  751. ? await adapter.normalizePolledTokenSet({
  752. accessToken: providerAccessToken,
  753. zcodeJwtToken,
  754. ...(refreshToken ? { refreshToken } : {}),
  755. })
  756. : {
  757. accessToken: providerAccessToken,
  758. zcodeJwtToken,
  759. ...(refreshToken ? { refreshToken } : {}),
  760. };
  761. return { tokenSet, profile };
  762. });
  763. if (result?.kind === "session") {
  764. serviceLog.info("OAuth polling flow completed", { provider: pending.provider });
  765. }
  766. return result;
  767. } catch (error) {
  768. if (this.pendingState === pending) this.clearPendingState();
  769. throw error;
  770. }
  771. }
  772. private async startOAuthInternal(provider: OAuthProviderId): Promise<OAuthStartResponse> {
  773. const adapter = this.getEnabledAdapter(provider);
  774. // 同窗口快速连续点击不同 provider 时,旧 state 如果不先取消,
  775. // 两条并发流程会共享同一回调通道,导致后回调抢占前回调并触发 state 错配。
  776. await this.runSessionMutation(async () => {
  777. this.oauthFlowStartGeneration += 1;
  778. this.oauthFlowStartProvider = null;
  779. this.clearPendingState();
  780. });
  781. const state = randomBytes(32).toString("hex");
  782. const timeout = setTimeout(() => {
  783. if (this.pendingState?.state === state) {
  784. this.pendingState = null;
  785. }
  786. }, OAUTH_TIMEOUT_MS);
  787. this.pendingState = {
  788. state,
  789. provider: adapter.providerId,
  790. timeout,
  791. phase: "awaiting-attribution-or-code",
  792. };
  793. const authorizeUrl = adapter.buildAuthorizeUrl({
  794. providerId: adapter.providerId,
  795. state,
  796. redirectUri: adapter.redirectUri,
  797. now: this.now,
  798. });
  799. return {
  800. provider: adapter.providerId,
  801. authorizeUrl,
  802. state,
  803. };
  804. }
  805. async handleCallback(url: string): Promise<OAuthCallbackResult | null> {
  806. const pending = this.pendingState;
  807. if (!pending) {
  808. const callbackState = new URL(url).searchParams.get("state")?.trim();
  809. const completed = this.recentlyCompletedPollingState;
  810. if (
  811. callbackState &&
  812. completed?.state === callbackState &&
  813. completed.generation === this.oauthFlowStartGeneration &&
  814. this.now() < completed.expiresAt
  815. ) {
  816. const attribution = parseOAuthLoginAttribution(new URL(url).searchParams);
  817. await this.runSessionMutation(async () => {
  818. // 修复原因:轮询先成功时仍需保存浏览器归因,不能把登录去重当作丢弃整条回调。
  819. if (
  820. !this.pendingState &&
  821. this.recentlyCompletedPollingState === completed &&
  822. completed.generation === this.oauthFlowStartGeneration &&
  823. attribution
  824. ) {
  825. await this.repo.saveLoginAttribution(attribution);
  826. }
  827. });
  828. return { kind: "duplicate", provider: completed.provider };
  829. }
  830. throw new Error("OAuth state 不匹配或已过期");
  831. }
  832. const parsedUrl = new URL(url);
  833. const state = parsedUrl.searchParams.get("state");
  834. if (!state || state !== pending.state) {
  835. throw new Error("OAuth state 不匹配或已过期");
  836. }
  837. if (pending.polling && this.now() >= pending.polling.expiresAt) {
  838. this.clearPendingState();
  839. throw new Error("OAuth flow 已过期");
  840. }
  841. const attribution = parseOAuthLoginAttribution(parsedUrl.searchParams);
  842. if (attribution && !hasOAuthAuthorizationCode(parsedUrl.searchParams)) {
  843. if (pending.phase === "awaiting-code-after-attribution") {
  844. throw new Error("OAuth 归因回调已处理");
  845. }
  846. // 修复原因:纯归因回调是最终授权码前的中转步骤,不能清掉仍需继续登录的 state;
  847. // 但若不显式推进 phase,同一 state 可重复写入归因并隐式复用 pending 生命周期。
  848. pending.phase = "awaiting-code-after-attribution";
  849. try {
  850. await this.repo.saveLoginAttribution(attribution);
  851. } catch (error) {
  852. if (this.pendingState === pending) {
  853. pending.phase = "awaiting-attribution-or-code";
  854. }
  855. throw error;
  856. }
  857. return {
  858. kind: "attribution",
  859. provider: pending.provider,
  860. attribution,
  861. };
  862. }
  863. const adapter = this.getAdapter(pending.provider);
  864. const fallbackProfile: OAuthUserProfile = {
  865. id: "unknown",
  866. username: "user",
  867. displayName: "User",
  868. };
  869. return this.runPendingSessionCompletion(
  870. pending,
  871. async () => {
  872. const callback = adapter.parseCallbackParams(url);
  873. const context = {
  874. providerId: adapter.providerId,
  875. state: callback.state,
  876. redirectUri: adapter.redirectUri,
  877. now: this.now,
  878. };
  879. const tokenSet = await this.runWithAdapterError(adapter, () =>
  880. adapter.exchangeToken(callback, context),
  881. );
  882. let profile = fallbackProfile;
  883. if (adapter.fetchUserInfo) {
  884. try {
  885. profile = await this.runWithAdapterError(adapter, () =>
  886. adapter.fetchUserInfo!(tokenSet, context),
  887. );
  888. } catch {
  889. // 获取用户信息失败不阻塞登录
  890. }
  891. }
  892. return { tokenSet, profile };
  893. },
  894. attribution ? () => this.repo.saveLoginAttribution(attribution) : undefined,
  895. );
  896. }
  897. async refreshToken(provider?: OAuthProviderId): Promise<void> {
  898. const generation = this.oauthSessionGeneration;
  899. const targetProvider = await this.resolveProvider(provider);
  900. if (!targetProvider) {
  901. throw new Error("当前没有可用的登录 provider");
  902. }
  903. const adapter = this.getEnabledAdapter(targetProvider);
  904. if (!adapter.refreshToken) {
  905. throw new Error(
  906. `${adapter.meta.displayName} OAuth 暂未提供 refresh token 交换接口,请重新登录`,
  907. );
  908. }
  909. const activeProvider = await this.repo.getActiveProvider();
  910. if (targetProvider !== activeProvider) {
  911. throw new Error("只能刷新当前 App 登录 provider,请重新登录");
  912. }
  913. const tokenSet = await this.repo.loadActiveTokenSet();
  914. if (!tokenSet?.refreshToken) {
  915. throw new Error("当前账号缺少 refresh_token,请重新登录");
  916. }
  917. const refreshed = await this.runWithAdapterError(adapter, () =>
  918. adapter.refreshToken!(tokenSet, {
  919. providerId: targetProvider,
  920. state: "",
  921. redirectUri: adapter.redirectUri,
  922. now: this.now,
  923. }),
  924. );
  925. await this.runSessionMutation(async () => {
  926. // 刷新写回若绕过会话队列,会插入 401 的核对/清理窗口,或在退出后复活凭据。
  927. if (
  928. this.oauthSessionGeneration !== generation ||
  929. (await this.repo.getActiveProvider()) !== targetProvider ||
  930. (await this.credentialService.load(`oauth:${targetProvider}:access_token`)) !==
  931. tokenSet.accessToken
  932. )
  933. return;
  934. await this.repo.saveActiveTokenSet(refreshed);
  935. });
  936. }
  937. /** Host 本地 401 提交入口,不扩展 IOAuthService 的跨端契约。 */
  938. logoutIfCurrentCredentialRequest(input: string | URL, headers: Headers): Promise<boolean> {
  939. return this.logoutActiveSession(() =>
  940. isCurrentOAuthCredentialRequest({
  941. input,
  942. headers,
  943. credentialService: this.credentialService,
  944. env: this.env,
  945. }),
  946. );
  947. }
  948. private async logoutActiveSession(isCurrent?: () => Promise<boolean>): Promise<boolean> {
  949. const result = await this.runSessionMutation(async () => {
  950. // 异步分类的 true 不是清理授权;凭据复核与清理必须和登录写入共用队列。
  951. if (isCurrent && !(await isCurrent())) return null;
  952. const activeProvider = await this.repo.getActiveProvider();
  953. // 合并边界:清理前保留原账号身份,不能退回仅按平台清理或在退出后再猜身份。
  954. const accountIdentity = activeProvider
  955. ? ((await this.repo.loadUserProfile(activeProvider))?.id ?? null)
  956. : null;
  957. this.oauthSessionGeneration += 1;
  958. await this.repo.clearActiveSession();
  959. return { activeProvider, accountIdentity };
  960. });
  961. if (!result) return false;
  962. if (result.activeProvider) {
  963. await this.cancelPending(result.activeProvider);
  964. try {
  965. await this.notifyProviderLogout(result.activeProvider, result.accountIdentity);
  966. } catch (error) {
  967. if (!isCurrent) throw error;
  968. // 凭据已经清理,派生配置失败不能吞掉原有过期提示;手动退出仍保留原错误语义。
  969. serviceLog.warn("Unauthorized session provider cleanup failed", { error });
  970. }
  971. }
  972. return true;
  973. }
  974. async logout(provider?: OAuthProviderId): Promise<void> {
  975. if (!provider) {
  976. await this.logoutActiveSession();
  977. return;
  978. }
  979. const loggedOutIdentity = await this.runSessionMutation(async () => {
  980. const activeProvider = await this.repo.getActiveProvider();
  981. if (provider !== activeProvider) {
  982. return undefined;
  983. }
  984. const accountIdentity = (await this.repo.loadUserProfile(provider))?.id ?? null;
  985. this.oauthSessionGeneration += 1;
  986. // ZAI/BigModel provider 的 Unlink 已收敛为 App logout。
  987. // 只有当前 active provider 才代表登录事实,避免旧 unlink 路径误删非当前 provider token。
  988. await this.repo.clearActiveSession();
  989. return accountIdentity;
  990. });
  991. if (loggedOutIdentity !== undefined) {
  992. await this.notifyProviderLogout(provider, loggedOutIdentity);
  993. }
  994. await this.cancelPending(provider);
  995. }
  996. async logoutAll(): Promise<void> {
  997. const providers = [...this.adapters.keys()];
  998. const accountIdentities = await this.runSessionMutation(async () => {
  999. const identities = new Map<OAuthProviderId, string | null>();
  1000. for (const provider of providers) {
  1001. identities.set(provider, (await this.repo.loadUserProfile(provider))?.id ?? null);
  1002. }
  1003. this.oauthSessionGeneration += 1;
  1004. await this.repo.clearAll(providers);
  1005. return identities;
  1006. });
  1007. await this.cancelPending();
  1008. await this.notifyProvidersLogout(providers, accountIdentities);
  1009. }
  1010. async cancelPending(provider?: OAuthProviderId): Promise<void> {
  1011. if (!this.pendingState) {
  1012. if (provider && this.oauthFlowStartProvider && this.oauthFlowStartProvider !== provider)
  1013. return;
  1014. this.oauthFlowStartGeneration += 1;
  1015. this.oauthFlowStartProvider = null;
  1016. return;
  1017. }
  1018. if (provider && this.pendingState.provider !== provider) return;
  1019. this.oauthFlowStartGeneration += 1;
  1020. this.oauthFlowStartProvider = null;
  1021. this.clearPendingState();
  1022. }
  1023. private clearPendingState(): void {
  1024. if (!this.pendingState) {
  1025. return;
  1026. }
  1027. clearTimeout(this.pendingState.timeout);
  1028. this.pendingState = null;
  1029. }
  1030. private async notifyProviderLogout(
  1031. provider: OAuthProviderId,
  1032. accountIdentity?: string | null,
  1033. ): Promise<void> {
  1034. if (!this.onProviderLogout) {
  1035. return;
  1036. }
  1037. await this.onProviderLogout(provider, accountIdentity);
  1038. }
  1039. private async notifyProvidersLogout(
  1040. providers: readonly OAuthProviderId[],
  1041. accountIdentities: ReadonlyMap<OAuthProviderId, string | null> = new Map(),
  1042. ): Promise<void> {
  1043. await Promise.all(
  1044. providers.map((provider) =>
  1045. this.notifyProviderLogout(provider, accountIdentities.get(provider)),
  1046. ),
  1047. );
  1048. }
  1049. private getAdapter(provider: OAuthProviderId): OAuthProviderAdapter {
  1050. const adapter = this.adapters.get(provider);
  1051. if (!adapter) {
  1052. throw new Error(`不支持的 OAuth provider: ${provider}`);
  1053. }
  1054. return adapter;
  1055. }
  1056. private getEnabledAdapter(provider: OAuthProviderId): OAuthProviderAdapter {
  1057. const adapter = this.getAdapter(provider);
  1058. if (!adapter.meta.enabled) {
  1059. throw new Error(`OAuth provider 未启用: ${provider}`);
  1060. }
  1061. return adapter;
  1062. }
  1063. private async resolveProvider(provider?: OAuthProviderId): Promise<OAuthProviderId | null> {
  1064. if (provider) {
  1065. return provider;
  1066. }
  1067. return this.repo.getActiveProvider();
  1068. }
  1069. private async runWithAdapterError<T>(
  1070. adapter: OAuthProviderAdapter,
  1071. run: () => Promise<T>,
  1072. ): Promise<T> {
  1073. try {
  1074. return await run();
  1075. } catch (error) {
  1076. throw adapter.normalizeError(error);
  1077. }
  1078. }
  1079. private isUnauthorizedError(error: Error): boolean {
  1080. const lowerMessage = error.message.toLowerCase();
  1081. return (
  1082. /\b401\b|\b403\b/.test(lowerMessage) ||
  1083. lowerMessage.includes("unauthorized") ||
  1084. lowerMessage.includes("forbidden")
  1085. );
  1086. }
  1087. }
  1088. /**
  1089. * 工厂函数:创建 OAuthService 实例
  1090. */
  1091. export function createOAuthService(
  1092. credentialService: ICredentialService,
  1093. dependencies: Omit<OAuthServiceDependencies, "adapters"> = {},
  1094. ): OAuthService {
  1095. return new OAuthService(credentialService, {
  1096. ...dependencies,
  1097. adapters: createOAuthProviderAdapters(createOAuthRuntimeConfig(dependencies.env), {
  1098. apiClient: dependencies.apiClient,
  1099. }),
  1100. });
  1101. }