oauthService.test.ts 130 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650
  1. import { afterEach, describe, expect, it, vi } from "vitest";
  2. import {
  3. ApiError,
  4. BIGMODEL_PROVIDER_ID,
  5. CREDENTIAL_DECRYPT_ERROR_CODE,
  6. ZCODE_VERSION,
  7. ZAI_PROVIDER_ID,
  8. type ApiClient,
  9. type OAuthProviderId,
  10. type OAuthProviderMeta,
  11. type OAuthTokenSet,
  12. type OAuthUserProfile,
  13. } from "@zcode/shared";
  14. import { BIGMODEL_OAUTH_PROVIDER_CONFIG } from "../src/oauth/providers/bigmodelProviderConfig.js";
  15. import { ZAI_OAUTH_PROVIDER_CONFIG } from "../src/oauth/providers/zaiProviderConfig.js";
  16. import { ZaiProviderAdapter } from "../src/oauth/providers/zaiProviderAdapter.js";
  17. import type { ICredentialService } from "../src/credential/credential.js";
  18. import type { OAuthProviderAdapter } from "../src/oauth/providers/index.js";
  19. import { OAuthService } from "../src/oauth/oauthService.js";
  20. import { OAuthCredentialRepo } from "../src/oauth/repo/oauthCredentialRepo.js";
  21. import { AccountProviderApiKeyResolver } from "../src/model-provider/accountProviderApiKeyResolver.js";
  22. import { createAccountProjectTokenClient } from "../src/model-provider/accountProjectTokenClient.js";
  23. import { resolveAccountTeamPlanRuntimeApiKey } from "../src/model-provider/accountProviderTeamPlanRequestKey.js";
  24. const DESKTOP_OAUTH_CALLBACK_URI = "zcode://oauth/callback";
  25. function buildDesktopOAuthLoginRedirectUri(origin: string): string {
  26. const url = new URL("/app/oauth/login", origin);
  27. url.searchParams.set("redirect", DESKTOP_OAUTH_CALLBACK_URI);
  28. url.searchParams.set("app_version", ZCODE_VERSION);
  29. return url.toString();
  30. }
  31. const PRODUCTION_DESKTOP_OAUTH_LOGIN_REDIRECT_URI =
  32. buildDesktopOAuthLoginRedirectUri("https://zcode.z.ai/");
  33. const TEST_DESKTOP_OAUTH_LOGIN_REDIRECT_URI = buildDesktopOAuthLoginRedirectUri(
  34. "https://zcode.z.ai/",
  35. );
  36. // Windows 机器上设置了 ZAI_TEST_OAUTH_ORIGIN 等环境变量,会覆盖测试预期的 test 端点值
  37. // 过滤掉这些可能污染测试的环境变量
  38. const OAUTH_ENV_KEYS_TO_OMIT = new Set([
  39. "ZCODE_ENV",
  40. "ZCODE_ENDPOINT_ORIGIN",
  41. "ZAI_TEST_OAUTH_ORIGIN",
  42. "ZAI_PRODUCTION_OAUTH_ORIGIN",
  43. "ZAI_OAUTH_ORIGIN",
  44. "ZAI_TEST_OAUTH_CLIENT_ID",
  45. "ZAI_PRODUCTION_OAUTH_CLIENT_ID",
  46. "ZAI_OAUTH_CLIENT_ID",
  47. "BIGMODEL_TEST_API_BASE_URL",
  48. "BIGMODEL_PRODUCTION_API_BASE_URL",
  49. "BIGMODEL_API_BASE_URL",
  50. "ZAI_TEST_BUSINESS_BASE_URL",
  51. "ZAI_PRODUCTION_BUSINESS_BASE_URL",
  52. "ZAI_BUSINESS_BASE_URL",
  53. "ZCODE_TEST_BASE_URL",
  54. "ZCODE_PRODUCTION_BASE_URL",
  55. "ZCODE_BASE_URL",
  56. ]);
  57. const cleanProcessEnv = Object.fromEntries(
  58. Object.entries(process.env).filter(([key]) => !OAUTH_ENV_KEYS_TO_OMIT.has(key)),
  59. ) as Record<string, string | undefined>;
  60. const credentialStore = new Map<string, string>();
  61. const credentialServiceStub: ICredentialService = {
  62. load: async (key: string) => credentialStore.get(key) ?? null,
  63. save: async (key: string, value: string) => {
  64. credentialStore.set(key, value);
  65. },
  66. delete: async (key: string) => {
  67. credentialStore.delete(key);
  68. },
  69. };
  70. const OAUTH_SESSION_CREDENTIAL_KEYS = [
  71. "oauth:active_provider",
  72. "oauth:bigmodel:access_token",
  73. "oauth:bigmodel:refresh_token",
  74. "oauth:bigmodel:user_info",
  75. "oauth:zai:access_token",
  76. "oauth:zai:refresh_token",
  77. "oauth:zai:user_info",
  78. "zcodejwttoken",
  79. ] as const;
  80. function expectDeletedOAuthSessionCredentials(
  81. deletedKeys: string[],
  82. additionalKeys: readonly string[] = [],
  83. ) {
  84. expect(new Set(deletedKeys)).toEqual(
  85. new Set([...OAUTH_SESSION_CREDENTIAL_KEYS, ...additionalKeys]),
  86. );
  87. }
  88. function createMockCredentialDecryptError(message = "Serialized credential decrypt failure") {
  89. return Object.assign(new Error(message), { code: CREDENTIAL_DECRYPT_ERROR_CODE });
  90. }
  91. function expectProviderLogoutNotifications(
  92. onProviderLogout: ReturnType<typeof vi.fn>,
  93. expectedProviders: readonly OAuthProviderId[],
  94. ) {
  95. expect(onProviderLogout).toHaveBeenCalledTimes(expectedProviders.length);
  96. expect(new Set(onProviderLogout.mock.calls.map(([provider]) => provider))).toEqual(
  97. new Set(expectedProviders),
  98. );
  99. }
  100. function createMockApiClient(mockFetch: typeof fetch): ApiClient {
  101. return {
  102. request: mockFetch,
  103. };
  104. }
  105. function createBigModelService(
  106. overrides?: ConstructorParameters<typeof OAuthService>[1],
  107. ): OAuthService {
  108. return new OAuthService(credentialServiceStub, {
  109. env: {
  110. ...cleanProcessEnv,
  111. BIGMODEL_OAUTH_APP_SECRET: "unit-test-secret",
  112. },
  113. apiClient: createMockApiClient(vi.fn<typeof fetch>()),
  114. ...overrides,
  115. });
  116. }
  117. function createZaiBusinessLoginResponse(accessToken = "zai_business_access_token"): Response {
  118. return new Response(
  119. JSON.stringify({
  120. code: 200,
  121. success: true,
  122. data: {
  123. access_token: accessToken,
  124. expires_in: 3600,
  125. },
  126. }),
  127. { status: 200, headers: { "Content-Type": "application/json" } },
  128. );
  129. }
  130. function createUnsignedJwt(payload: Record<string, unknown>): string {
  131. const encode = (value: object) => Buffer.from(JSON.stringify(value)).toString("base64url");
  132. return `${encode({ alg: "none", typ: "JWT" })}.${encode(payload)}.`;
  133. }
  134. function createBigModelZcodeTokenResponse(
  135. token = "bigmodel-zcode-jwt",
  136. accessToken = "bigmodel-business-access-token",
  137. ): Response {
  138. return new Response(
  139. JSON.stringify({
  140. code: 0,
  141. data: {
  142. token,
  143. bigmodel: {
  144. access_token: accessToken,
  145. },
  146. },
  147. }),
  148. { status: 200, headers: { "Content-Type": "application/json" } },
  149. );
  150. }
  151. function createBigModelUserInfoResponse(
  152. nickName: unknown = "BigModel User",
  153. customerNumber: unknown = "bigmodel-u-001",
  154. customerName: unknown = nickName,
  155. ): Response {
  156. return new Response(
  157. JSON.stringify({
  158. data: {
  159. customerNumber,
  160. customerName,
  161. nickName,
  162. },
  163. }),
  164. { status: 200, headers: { "Content-Type": "application/json" } },
  165. );
  166. }
  167. afterEach(() => {
  168. credentialStore.clear();
  169. vi.useRealTimers();
  170. vi.restoreAllMocks();
  171. });
  172. describe("oauthService", () => {
  173. it.each([false, true])("Z.AI polling 先换业务 JWT 再签发 PAT,team=%s", async (team) => {
  174. let now = 2_000_000_000_000;
  175. const requests: Array<{ url: string; init?: RequestInit }> = [];
  176. const mockFetch = vi.fn<typeof fetch>(async (input, init) => {
  177. const url = String(input);
  178. requests.push({ url, init });
  179. if (url.endsWith("/api/v1/oauth/cli/init")) {
  180. return new Response(
  181. JSON.stringify({
  182. code: 0,
  183. msg: "",
  184. data: {
  185. authorize_url:
  186. "https://chat.z.ai/api/oauth/authorize?client_id=zcode&redirect_uri=https%3A%2F%2Fzcode.z.ai%2Fapi%2Fv1%2Foauth%2Fcli%2Fcallback&state=flow-state&response_type=code",
  187. expires_at: 2_000_000_300,
  188. flow_id: "flow-1",
  189. poll_interval_sec: 2,
  190. poll_token: "server-must-not-replace-client-token",
  191. },
  192. }),
  193. { status: 200, headers: { "Content-Type": "application/json" } },
  194. );
  195. }
  196. if (url.endsWith("/api/v1/oauth/cli/poll/flow-1")) {
  197. return new Response(
  198. JSON.stringify({
  199. code: 0,
  200. msg: "",
  201. data: {
  202. status: "ready",
  203. token: "zcode-jwt",
  204. user: {
  205. user_id: "user-1",
  206. name: "Edward",
  207. email: "edward@example.com",
  208. },
  209. zai: { access_token: "zai-oauth-token" },
  210. },
  211. }),
  212. { status: 200, headers: { "Content-Type": "application/json" } },
  213. );
  214. }
  215. if (url.endsWith("/api/auth/z/login")) {
  216. expect(JSON.parse(String(init?.body))).toEqual({
  217. token: "zai-oauth-token",
  218. });
  219. return createZaiBusinessLoginResponse("zai-business-token");
  220. }
  221. if (url.includes("/api/biz/")) {
  222. expect(new Headers(init?.headers).get("authorization")).toBe(
  223. url.endsWith("/getCustomerInfo") ||
  224. (team && url.includes("/api_keys") && !url.endsWith("/access_tokens"))
  225. ? "zai-business-token"
  226. : "Bearer zai-business-token",
  227. );
  228. const data = url.endsWith("/getCustomerInfo")
  229. ? {
  230. organizations: [
  231. {
  232. organizationId: "org",
  233. projects: [{ projectId: "project" }],
  234. },
  235. ],
  236. }
  237. : url.endsWith("/access_tokens")
  238. ? {
  239. accessToken: "project-pat",
  240. tokenType: "Bearer",
  241. expiresIn: 600,
  242. expiresAt: Date.now() / 1000 + 600,
  243. }
  244. : [
  245. {
  246. name: team ? "zcode-team-api-key" : "zcode-api-key",
  247. apiKey: "key",
  248. keyType: 2,
  249. },
  250. ];
  251. return new Response(JSON.stringify({ code: 200, data }), {
  252. headers: { "content-type": "application/json" },
  253. });
  254. }
  255. throw new Error(`Unexpected request: ${url}`);
  256. });
  257. const service = createBigModelService({
  258. apiClient: createMockApiClient(mockFetch),
  259. now: () => now,
  260. });
  261. const started = await service.startOAuthWithPolling(ZAI_PROVIDER_ID);
  262. const authorizeUrl = new URL(started.authorizeUrl);
  263. const redirectUrl = new URL(authorizeUrl.searchParams.get("redirect_uri")!);
  264. const result = await service.pollPendingOAuth();
  265. expect(authorizeUrl.searchParams.get("state")).toBe(started.state);
  266. expect(redirectUrl.origin + redirectUrl.pathname).toBe("https://zcode.z.ai/app/oauth/login");
  267. expect(redirectUrl.searchParams.get("redirect")).toBe("zcode://oauth/callback");
  268. expect(redirectUrl.searchParams.get("app_version")).toBe(ZCODE_VERSION);
  269. expect(result).toEqual({
  270. kind: "session",
  271. provider: ZAI_PROVIDER_ID,
  272. userInfo: {
  273. id: "user-1",
  274. username: "Edward",
  275. displayName: "Edward",
  276. },
  277. });
  278. expect(requests[0]?.init?.headers).toMatchObject({
  279. Authorization: expect.stringMatching(/^Bearer [a-f0-9]{64}$/u),
  280. });
  281. const initAuthorization = (requests[0]!.init!.headers as Record<string, string>).Authorization;
  282. expect(requests[1]?.init?.headers).toMatchObject({
  283. Authorization: initAuthorization,
  284. });
  285. expect(credentialStore.get("oauth:zai:access_token")).toBe("zai-business-token");
  286. expect(credentialStore.get("zcodejwttoken")).toBe("zcode-jwt");
  287. const apiClient = createMockApiClient(mockFetch);
  288. const tokenClient = createAccountProjectTokenClient(apiClient, credentialServiceStub);
  289. const persistedToken = (await credentialServiceStub.load("oauth:zai:access_token"))!;
  290. const pat = team
  291. ? await resolveAccountTeamPlanRuntimeApiKey({
  292. apiClient,
  293. tokenClient,
  294. credentialService: credentialServiceStub,
  295. accountIdentity: "user-1",
  296. access: {
  297. type: "zhipu-account",
  298. family: "zai",
  299. planKind: "team-coding-plan",
  300. organizationId: "org",
  301. projectId: "project",
  302. },
  303. })
  304. : await new AccountProviderApiKeyResolver(
  305. async () => null,
  306. tokenClient,
  307. ).resolveProviderApiKey(ZAI_PROVIDER_ID, persistedToken, "user-1");
  308. expect(pat).toBe("project-pat");
  309. expect(requests.filter(({ url }) => url.endsWith("/api/auth/z/login"))).toHaveLength(1);
  310. expect(requests.slice(2).map(({ url }) => new URL(url).pathname)).toEqual([
  311. "/api/auth/z/login",
  312. "/api/biz/customer/getCustomerInfo",
  313. "/api/biz/v1/organization/org/projects/project/api_keys",
  314. "/api/biz/v1/organization/org/projects/project/api_keys/key/access_tokens",
  315. ]);
  316. await expect(
  317. service.handleCallback(`zcode://oauth/callback?state=${started.state}&code=late-code`),
  318. ).resolves.toEqual({ kind: "duplicate", provider: ZAI_PROVIDER_ID });
  319. await expect(
  320. service.handleCallback("zcode://oauth/callback?state=different-state&code=late-code"),
  321. ).rejects.toThrow("OAuth state 不匹配或已过期");
  322. now += 30_000;
  323. await expect(
  324. service.handleCallback(`zcode://oauth/callback?state=${started.state}&code=too-late-code`),
  325. ).rejects.toThrow("OAuth state 不匹配或已过期");
  326. await expect(service.pollPendingOAuth()).resolves.toBeNull();
  327. expect(mockFetch).toHaveBeenCalledTimes(6);
  328. });
  329. it.each([
  330. ["snake_case", { access_token: "bigmodel-business-token", refresh_token: "bigmodel-refresh" }],
  331. ["camelCase", { accessToken: "bigmodel-business-token", refreshToken: "bigmodel-refresh" }],
  332. ])(
  333. "uses the same backend polling flow for BigModel with %s token fields",
  334. async (_label, bigmodelTokenData) => {
  335. const requests: Array<{ url: string; init?: RequestInit }> = [];
  336. const mockFetch = vi.fn<typeof fetch>(async (input, init) => {
  337. const url = String(input);
  338. requests.push({ url, init });
  339. if (url.endsWith("/api/v1/oauth/cli/init")) {
  340. return new Response(
  341. JSON.stringify({
  342. code: 0,
  343. data: {
  344. authorize_url:
  345. "https://bigmodel.cn/login?appId=zcode&redirect=https%3A%2F%2Fzcode.z.ai%2Fapi%2Fv1%2Foauth%2Fcli%2Fcallback%2Fbigmodel&state=bigmodel-flow",
  346. expires_at: 2_000_000_300,
  347. flow_id: "bigmodel-flow-1",
  348. poll_interval_sec: 2,
  349. poll_token: "ignored",
  350. },
  351. }),
  352. { status: 200, headers: { "Content-Type": "application/json" } },
  353. );
  354. }
  355. return new Response(
  356. JSON.stringify({
  357. code: 0,
  358. data: {
  359. status: "ready",
  360. token: "bigmodel-zcode-jwt",
  361. user: { user_id: "bigmodel-user", name: "BigModel User" },
  362. bigmodel: bigmodelTokenData,
  363. },
  364. }),
  365. { status: 200, headers: { "Content-Type": "application/json" } },
  366. );
  367. });
  368. const service = createBigModelService({
  369. apiClient: createMockApiClient(mockFetch),
  370. now: () => 2_000_000_000_000,
  371. });
  372. const started = await service.startOAuthWithPolling(BIGMODEL_PROVIDER_ID);
  373. const authorizeUrl = new URL(started.authorizeUrl);
  374. const redirectUrl = new URL(authorizeUrl.searchParams.get("redirect")!);
  375. const result = await service.pollPendingOAuth();
  376. expect(JSON.parse(String(requests[0]?.init?.body))).toEqual({
  377. provider: BIGMODEL_PROVIDER_ID,
  378. });
  379. expect(authorizeUrl.origin + authorizeUrl.pathname).toBe("https://bigmodel.cn/login");
  380. expect(redirectUrl.origin + redirectUrl.pathname).toBe("https://zcode.z.ai/app/oauth/login");
  381. expect(redirectUrl.searchParams.get("redirect")).toBe("zcode://oauth/callback");
  382. expect(redirectUrl.searchParams.get("app_version")).toBe(ZCODE_VERSION);
  383. expect(result).toEqual({
  384. kind: "session",
  385. provider: BIGMODEL_PROVIDER_ID,
  386. userInfo: {
  387. id: "bigmodel-user",
  388. username: "BigModel User",
  389. displayName: "BigModel User",
  390. },
  391. });
  392. expect(credentialStore.get("oauth:bigmodel:access_token")).toBe("bigmodel-business-token");
  393. expect(credentialStore.get("oauth:bigmodel:refresh_token")).toBe("bigmodel-refresh");
  394. expect(credentialStore.get("zcodejwttoken")).toBe("bigmodel-zcode-jwt");
  395. expect(started.provider).toBe(BIGMODEL_PROVIDER_ID);
  396. },
  397. );
  398. it("rejects a late polling callback after timeout without persisting credentials", async () => {
  399. vi.useFakeTimers();
  400. let now = 2_000_000_000_000;
  401. const mockFetch = vi.fn<typeof fetch>(async (input) => {
  402. const url = String(input);
  403. if (url.endsWith("/api/v1/oauth/cli/init")) {
  404. return new Response(
  405. JSON.stringify({
  406. code: 0,
  407. data: {
  408. authorize_url: "https://chat.z.ai/api/oauth/authorize?state=expired-polling-state",
  409. expires_at: (now + 5_000) / 1_000,
  410. flow_id: "expired-polling-flow",
  411. poll_interval_sec: 1,
  412. poll_token: "poll-token",
  413. },
  414. }),
  415. { status: 200 },
  416. );
  417. }
  418. throw new Error(`Unexpected request: ${url}`);
  419. });
  420. const baseAdapter = new ZaiProviderAdapter(
  421. {
  422. ...ZAI_OAUTH_PROVIDER_CONFIG,
  423. enabled: true,
  424. },
  425. createMockApiClient(mockFetch),
  426. );
  427. const exchangeToken = vi.spyOn(baseAdapter, "exchangeToken").mockImplementation(async () => {
  428. throw new Error("exchange should not run");
  429. });
  430. const service = createBigModelService({
  431. apiClient: createMockApiClient(mockFetch),
  432. now: () => now,
  433. adapters: [baseAdapter],
  434. });
  435. const started = await service.startOAuthWithPolling(ZAI_PROVIDER_ID);
  436. credentialStore.set("oauth:zai:access_token", "existing-token");
  437. now += 5_000;
  438. await vi.advanceTimersByTimeAsync(5_000);
  439. await expect(
  440. service.handleCallback(`zcode://oauth/callback?state=${started.state}&code=late-code`),
  441. ).rejects.toThrow("OAuth state 不匹配或已过期");
  442. expect(exchangeToken).not.toHaveBeenCalled();
  443. expect(credentialStore.get("oauth:zai:access_token")).toBe("existing-token");
  444. });
  445. it("keeps a pending Z.AI flow until the server polling interval elapses", async () => {
  446. let now = 2_000_000_000_000;
  447. const mockFetch = vi.fn<typeof fetch>(async (input) => {
  448. const url = String(input);
  449. return new Response(
  450. JSON.stringify(
  451. url.endsWith("/init")
  452. ? {
  453. code: 0,
  454. data: {
  455. authorize_url: "https://chat.z.ai/api/oauth/authorize?state=flow-state",
  456. expires_at: 2_000_000_300,
  457. flow_id: "flow-1",
  458. poll_interval_sec: 2,
  459. poll_token: "ignored",
  460. },
  461. }
  462. : { code: 0, data: { status: "pending" } },
  463. ),
  464. { status: 200, headers: { "Content-Type": "application/json" } },
  465. );
  466. });
  467. const service = createBigModelService({
  468. apiClient: createMockApiClient(mockFetch),
  469. now: () => now,
  470. });
  471. await service.startOAuthWithPolling(ZAI_PROVIDER_ID);
  472. await expect(service.pollPendingOAuth()).resolves.toBeNull();
  473. await expect(service.pollPendingOAuth()).resolves.toBeNull();
  474. expect(mockFetch).toHaveBeenCalledTimes(2);
  475. now += 2_000;
  476. await expect(service.pollPendingOAuth()).resolves.toBeNull();
  477. expect(mockFetch).toHaveBeenCalledTimes(3);
  478. });
  479. it.each([
  480. [
  481. "an expired flow",
  482. {
  483. authorize_url: "https://chat.z.ai/api/oauth/authorize?state=flow-state",
  484. expires_at: 2_000_000_000,
  485. flow_id: "flow-1",
  486. poll_interval_sec: 2,
  487. },
  488. ],
  489. [
  490. "a non-HTTPS authorize URL",
  491. {
  492. authorize_url: "http://example.com/oauth?state=flow-state",
  493. expires_at: 2_000_000_300,
  494. flow_id: "flow-1",
  495. poll_interval_sec: 2,
  496. },
  497. ],
  498. [
  499. "a polling interval below one second",
  500. {
  501. authorize_url: "https://chat.z.ai/api/oauth/authorize?state=flow-state",
  502. expires_at: 2_000_000_300,
  503. flow_id: "flow-1",
  504. poll_interval_sec: 0.5,
  505. },
  506. ],
  507. [
  508. "a polling interval longer than the remaining flow lifetime",
  509. {
  510. authorize_url: "https://chat.z.ai/api/oauth/authorize?state=flow-state",
  511. expires_at: 2_000_000_300,
  512. flow_id: "flow-1",
  513. poll_interval_sec: 301,
  514. },
  515. ],
  516. ])("rejects polling init with %s", async (_label, data) => {
  517. const mockFetch = vi.fn<typeof fetch>(
  518. async () =>
  519. new Response(JSON.stringify({ code: 0, data }), {
  520. status: 200,
  521. headers: { "Content-Type": "application/json" },
  522. }),
  523. );
  524. const service = createBigModelService({
  525. apiClient: createMockApiClient(mockFetch),
  526. now: () => 2_000_000_000_000,
  527. });
  528. await expect(service.startOAuthWithPolling(ZAI_PROVIDER_ID)).rejects.toThrow(
  529. "OAuth flow 初始化响应无效",
  530. );
  531. await expect(service.pollPendingOAuth()).resolves.toBeNull();
  532. });
  533. it.each([
  534. ["an unknown status", { status: "completed" }],
  535. [
  536. "malformed ready credential fields",
  537. {
  538. status: "ready",
  539. token: { value: "not-a-string" },
  540. user: { user_id: 42, name: ["not-a-string"] },
  541. zai: { access_token: true },
  542. },
  543. ],
  544. ])("fails polling cleanly for %s", async (_label, pollData) => {
  545. const mockFetch = vi.fn<typeof fetch>(async (input) => {
  546. const data = String(input).endsWith("/init")
  547. ? {
  548. authorize_url: "https://chat.z.ai/api/oauth/authorize?state=flow-state",
  549. expires_at: 2_000_000_300,
  550. flow_id: "flow-1",
  551. poll_interval_sec: 2,
  552. }
  553. : pollData;
  554. return new Response(JSON.stringify({ code: 0, data }), {
  555. status: 200,
  556. headers: { "Content-Type": "application/json" },
  557. });
  558. });
  559. const service = createBigModelService({
  560. apiClient: createMockApiClient(mockFetch),
  561. now: () => 2_000_000_000_000,
  562. });
  563. await service.startOAuthWithPolling(ZAI_PROVIDER_ID);
  564. await expect(service.pollPendingOAuth()).rejects.toThrow("OAuth flow 查询响应无效");
  565. await expect(service.pollPendingOAuth()).resolves.toBeNull();
  566. });
  567. it("keeps the newest polling flow when an older init response arrives late", async () => {
  568. let resolveFirstInit: ((response: Response) => void) | undefined;
  569. const firstInit = new Promise<Response>((resolve) => {
  570. resolveFirstInit = resolve;
  571. });
  572. let initCount = 0;
  573. const polledUrls: string[] = [];
  574. const mockFetch = vi.fn<typeof fetch>(async (input) => {
  575. const url = String(input);
  576. if (url.endsWith("/init")) {
  577. initCount += 1;
  578. if (initCount === 1) {
  579. return firstInit;
  580. }
  581. return new Response(
  582. JSON.stringify({
  583. code: 0,
  584. data: {
  585. authorize_url: "https://bigmodel.cn/login?state=new-flow-state",
  586. expires_at: 2_000_000_300,
  587. flow_id: "new-flow",
  588. poll_interval_sec: 2,
  589. },
  590. }),
  591. { status: 200, headers: { "Content-Type": "application/json" } },
  592. );
  593. }
  594. polledUrls.push(url);
  595. return new Response(JSON.stringify({ code: 0, data: { status: "pending" } }), {
  596. status: 200,
  597. headers: { "Content-Type": "application/json" },
  598. });
  599. });
  600. const service = createBigModelService({
  601. apiClient: createMockApiClient(mockFetch),
  602. now: () => 2_000_000_000_000,
  603. });
  604. const oldStart = service.startOAuthWithPolling(ZAI_PROVIDER_ID);
  605. await vi.waitFor(() => expect(initCount).toBe(1));
  606. const newStart = service.startOAuthWithPolling(BIGMODEL_PROVIDER_ID);
  607. await expect(newStart).resolves.toMatchObject({
  608. provider: BIGMODEL_PROVIDER_ID,
  609. state: "new-flow-state",
  610. });
  611. resolveFirstInit?.(
  612. new Response(
  613. JSON.stringify({
  614. code: 0,
  615. data: {
  616. authorize_url: "https://chat.z.ai/api/oauth/authorize?state=old-flow-state",
  617. expires_at: 2_000_000_300,
  618. flow_id: "old-flow",
  619. poll_interval_sec: 2,
  620. },
  621. }),
  622. { status: 200, headers: { "Content-Type": "application/json" } },
  623. ),
  624. );
  625. await expect(oldStart).rejects.toThrow("OAuth flow 已被新的登录请求替换");
  626. await expect(service.pollPendingOAuth()).resolves.toBeNull();
  627. expect(polledUrls).toEqual([expect.stringContaining("/poll/new-flow")]);
  628. });
  629. it("discards an in-flight init response after the user cancels", async () => {
  630. let resolveInit: ((response: Response) => void) | undefined;
  631. const initResponse = new Promise<Response>((resolve) => {
  632. resolveInit = resolve;
  633. });
  634. const mockFetch = vi.fn<typeof fetch>(() => initResponse);
  635. const service = createBigModelService({
  636. apiClient: createMockApiClient(mockFetch),
  637. now: () => 2_000_000_000_000,
  638. });
  639. const start = service.startOAuthWithPolling(ZAI_PROVIDER_ID);
  640. await vi.waitFor(() => expect(mockFetch).toHaveBeenCalledTimes(1));
  641. await service.cancelPending();
  642. resolveInit?.(
  643. new Response(
  644. JSON.stringify({
  645. code: 0,
  646. data: {
  647. authorize_url: "https://chat.z.ai/api/oauth/authorize?state=cancelled-flow",
  648. expires_at: 2_000_000_300,
  649. flow_id: "cancelled-flow",
  650. poll_interval_sec: 2,
  651. },
  652. }),
  653. { status: 200, headers: { "Content-Type": "application/json" } },
  654. ),
  655. );
  656. await expect(start).rejects.toThrow("OAuth flow 已被新的登录请求替换");
  657. await expect(service.pollPendingOAuth()).resolves.toBeNull();
  658. });
  659. it("does not cancel another provider's in-flight init response", async () => {
  660. let resolveInit: ((response: Response) => void) | undefined;
  661. const initResponse = new Promise<Response>((resolve) => {
  662. resolveInit = resolve;
  663. });
  664. const mockFetch = vi.fn<typeof fetch>(() => initResponse);
  665. const service = createBigModelService({
  666. apiClient: createMockApiClient(mockFetch),
  667. now: () => 2_000_000_000_000,
  668. });
  669. const start = service.startOAuthWithPolling(BIGMODEL_PROVIDER_ID);
  670. await vi.waitFor(() => expect(mockFetch).toHaveBeenCalledTimes(1));
  671. await service.cancelPending(ZAI_PROVIDER_ID);
  672. resolveInit?.(
  673. new Response(
  674. JSON.stringify({
  675. code: 0,
  676. data: {
  677. authorize_url: "https://bigmodel.cn/login?state=bigmodel-flow",
  678. expires_at: 2_000_000_300,
  679. flow_id: "bigmodel-flow",
  680. poll_interval_sec: 2,
  681. },
  682. }),
  683. { status: 200, headers: { "Content-Type": "application/json" } },
  684. ),
  685. );
  686. await expect(start).resolves.toMatchObject({
  687. provider: BIGMODEL_PROVIDER_ID,
  688. state: "bigmodel-flow",
  689. });
  690. });
  691. it("stops polling when the pending Z.AI login is cancelled", async () => {
  692. const mockFetch = vi.fn<typeof fetch>(
  693. async () =>
  694. new Response(
  695. JSON.stringify({
  696. code: 0,
  697. data: {
  698. authorize_url: "https://chat.z.ai/api/oauth/authorize?state=flow-state",
  699. expires_at: 2_000_000_300,
  700. flow_id: "flow-1",
  701. poll_interval_sec: 2,
  702. poll_token: "ignored",
  703. },
  704. }),
  705. { status: 200, headers: { "Content-Type": "application/json" } },
  706. ),
  707. );
  708. const service = createBigModelService({
  709. apiClient: createMockApiClient(mockFetch),
  710. now: () => 2_000_000_000_000,
  711. });
  712. await service.startOAuthWithPolling(ZAI_PROVIDER_ID);
  713. await service.cancelPending(ZAI_PROVIDER_ID);
  714. await expect(service.pollPendingOAuth()).resolves.toBeNull();
  715. expect(mockFetch).toHaveBeenCalledTimes(1);
  716. });
  717. it.each([503, 429])(
  718. "retries a transient Z.AI polling HTTP %i without clearing the flow",
  719. async (transientStatus) => {
  720. let now = 2_000_000_000_000;
  721. let pollAttempts = 0;
  722. const mockFetch = vi.fn<typeof fetch>(async (input) => {
  723. const url = String(input);
  724. if (url.endsWith("/init")) {
  725. return new Response(
  726. JSON.stringify({
  727. code: 0,
  728. data: {
  729. authorize_url: "https://chat.z.ai/api/oauth/authorize?state=flow-state",
  730. expires_at: 2_000_000_300,
  731. flow_id: "flow-1",
  732. poll_interval_sec: 2,
  733. poll_token: "ignored",
  734. },
  735. }),
  736. { status: 200, headers: { "Content-Type": "application/json" } },
  737. );
  738. }
  739. if (url.includes("/poll/")) {
  740. pollAttempts += 1;
  741. if (pollAttempts === 1) {
  742. return new Response("", { status: transientStatus });
  743. }
  744. return new Response(
  745. JSON.stringify({
  746. code: 0,
  747. data: {
  748. status: "ready",
  749. token: "zcode-jwt",
  750. user: { user_id: "user-1", name: "Edward" },
  751. zai: { access_token: "zai-oauth-token" },
  752. },
  753. }),
  754. { status: 200, headers: { "Content-Type": "application/json" } },
  755. );
  756. }
  757. return createZaiBusinessLoginResponse("zai-business-token");
  758. });
  759. const service = createBigModelService({
  760. apiClient: createMockApiClient(mockFetch),
  761. now: () => now,
  762. });
  763. await service.startOAuthWithPolling(ZAI_PROVIDER_ID);
  764. await expect(service.pollPendingOAuth()).resolves.toBeNull();
  765. now += 2_000;
  766. await expect(service.pollPendingOAuth()).resolves.toMatchObject({
  767. kind: "session",
  768. provider: ZAI_PROVIDER_ID,
  769. });
  770. expect(pollAttempts).toBe(2);
  771. },
  772. );
  773. it("clears the flow when ready token normalization fails", async () => {
  774. let now = 2_000_000_000_000;
  775. let pollAttempts = 0;
  776. const mockFetch = vi.fn<typeof fetch>(async (input) => {
  777. const url = String(input);
  778. if (url.endsWith("/init")) {
  779. return new Response(
  780. JSON.stringify({
  781. code: 0,
  782. data: {
  783. authorize_url: "https://chat.z.ai/api/oauth/authorize?state=flow-state",
  784. expires_at: 2_000_000_300,
  785. flow_id: "flow-1",
  786. poll_interval_sec: 2,
  787. },
  788. }),
  789. { status: 200, headers: { "Content-Type": "application/json" } },
  790. );
  791. }
  792. if (url.includes("/poll/")) {
  793. pollAttempts += 1;
  794. return new Response(
  795. JSON.stringify({
  796. code: 0,
  797. data: {
  798. status: "ready",
  799. token: "zcode-jwt",
  800. user: { user_id: "user-1", name: "Edward" },
  801. zai: { access_token: "zai-oauth-token" },
  802. },
  803. }),
  804. { status: 200, headers: { "Content-Type": "application/json" } },
  805. );
  806. }
  807. return new Response(JSON.stringify({ code: 500, msg: "business token failed" }), {
  808. status: 500,
  809. headers: { "Content-Type": "application/json" },
  810. });
  811. });
  812. const service = createBigModelService({
  813. apiClient: createMockApiClient(mockFetch),
  814. now: () => now,
  815. });
  816. await service.startOAuthWithPolling(ZAI_PROVIDER_ID);
  817. await expect(service.pollPendingOAuth()).rejects.toThrow();
  818. now += 2_000;
  819. await expect(service.pollPendingOAuth()).resolves.toBeNull();
  820. expect(pollAttempts).toBe(1);
  821. });
  822. it("clears a failed Z.AI polling flow without persisting credentials", async () => {
  823. const mockFetch = vi.fn<typeof fetch>(async (input) => {
  824. const url = String(input);
  825. return new Response(
  826. JSON.stringify(
  827. url.endsWith("/init")
  828. ? {
  829. code: 0,
  830. data: {
  831. authorize_url: "https://chat.z.ai/api/oauth/authorize?state=flow-state",
  832. expires_at: 2_000_000_300,
  833. flow_id: "flow-1",
  834. poll_interval_sec: 2,
  835. poll_token: "ignored",
  836. },
  837. }
  838. : { code: 0, data: { status: "failed" } },
  839. ),
  840. { status: 200, headers: { "Content-Type": "application/json" } },
  841. );
  842. });
  843. const service = createBigModelService({
  844. apiClient: createMockApiClient(mockFetch),
  845. now: () => 2_000_000_000_000,
  846. });
  847. await service.startOAuthWithPolling(ZAI_PROVIDER_ID);
  848. await expect(service.pollPendingOAuth()).rejects.toThrow("OAuth flow 授权失败");
  849. await expect(service.pollPendingOAuth()).resolves.toBeNull();
  850. expect(credentialStore.get("oauth:zai:access_token")).toBeUndefined();
  851. });
  852. it("persists website attribution without an expiry time", async () => {
  853. const service = createBigModelService({
  854. apiClient: createMockApiClient(vi.fn<typeof fetch>()),
  855. });
  856. const { state } = await service.startOAuth(BIGMODEL_PROVIDER_ID);
  857. await service.handleCallback(
  858. `zcode://oauth/callback?state=${state}&channel_id=douyin&utm_source=wechat`,
  859. );
  860. const repo = new OAuthCredentialRepo(credentialServiceStub);
  861. await expect(repo.loadLoginAttribution()).resolves.toEqual({
  862. channel_id: "douyin",
  863. utm_source: "wechat",
  864. });
  865. });
  866. it("reads the temporary expiring attribution record written by an earlier branch revision", async () => {
  867. await credentialServiceStub.save(
  868. "oauth:login_attribution",
  869. JSON.stringify({
  870. params: { channel_id: "migrated-channel", utm_campaign: "launch" },
  871. expiresAt: 1,
  872. }),
  873. );
  874. const repo = new OAuthCredentialRepo(credentialServiceStub);
  875. await expect(repo.loadLoginAttribution()).resolves.toEqual({
  876. channel_id: "migrated-channel",
  877. utm_campaign: "launch",
  878. });
  879. });
  880. it("缺少 apiClient 注入时会立即报错", () => {
  881. expect(
  882. () =>
  883. new OAuthService(credentialServiceStub, {
  884. env: {
  885. ...process.env,
  886. BIGMODEL_OAUTH_APP_SECRET: "unit-test-secret",
  887. },
  888. }),
  889. ).toThrow(/ApiClient/);
  890. });
  891. it("returns enabled provider metadata", async () => {
  892. const service = createBigModelService();
  893. await expect(service.getProviders()).resolves.toEqual<OAuthProviderMeta[]>([
  894. {
  895. id: BIGMODEL_PROVIDER_ID,
  896. displayName: "BigModel",
  897. enabled: true,
  898. order: 0,
  899. },
  900. {
  901. id: ZAI_PROVIDER_ID,
  902. displayName: "Z.ai",
  903. enabled: true,
  904. order: 1,
  905. },
  906. ]);
  907. });
  908. it("builds authorize URL with provider-specific params", async () => {
  909. const service = createBigModelService();
  910. const { provider, authorizeUrl, state } = await service.startOAuth(BIGMODEL_PROVIDER_ID);
  911. const parsed = new URL(authorizeUrl);
  912. expect(provider).toBe(BIGMODEL_PROVIDER_ID);
  913. expect(parsed.origin + parsed.pathname).toBe(BIGMODEL_OAUTH_PROVIDER_CONFIG.authorizeUrl);
  914. expect(parsed.searchParams.get("redirect")).toBe(PRODUCTION_DESKTOP_OAUTH_LOGIN_REDIRECT_URI);
  915. expect(parsed.searchParams.get("appId")).toBe(BIGMODEL_OAUTH_PROVIDER_CONFIG.appId);
  916. expect(parsed.searchParams.get("state")).toBe(state);
  917. });
  918. it("builds zai authorize URL with backend-token flow params", async () => {
  919. const service = createBigModelService();
  920. const { provider, authorizeUrl, state } = await service.startOAuth(ZAI_PROVIDER_ID);
  921. const parsed = new URL(authorizeUrl);
  922. expect(provider).toBe(ZAI_PROVIDER_ID);
  923. expect(parsed.origin + parsed.pathname).toBe("https://chat.z.ai/api/oauth/authorize");
  924. expect(parsed.searchParams.get("redirect_uri")).toBe(
  925. PRODUCTION_DESKTOP_OAUTH_LOGIN_REDIRECT_URI,
  926. );
  927. expect(parsed.searchParams.get("client_id")).toBe("client_P8X5CMWmlaRO9gyO-KSqtg");
  928. expect(parsed.searchParams.get("state")).toBe(state);
  929. });
  930. it("uses ZAI_OAUTH_ORIGIN and ZAI_OAUTH_CLIENT_ID to build test environment authorize URL", async () => {
  931. const service = createBigModelService({
  932. env: {
  933. ...cleanProcessEnv,
  934. BIGMODEL_OAUTH_APP_SECRET: "unit-test-secret",
  935. ZCODE_ENV: "test",
  936. ZAI_OAUTH_CLIENT_ID: "client_P8X5CMWmlaRO9gyO-KSqtg",
  937. ZAI_OAUTH_ORIGIN: "https://chat.z.ai/",
  938. },
  939. });
  940. const { authorizeUrl } = await service.startOAuth(ZAI_PROVIDER_ID);
  941. const parsed = new URL(authorizeUrl);
  942. expect(parsed.origin + parsed.pathname).toBe(
  943. "https://chat.z.ai/api/oauth/authorize",
  944. );
  945. expect(parsed.searchParams.get("redirect_uri")).toBe(TEST_DESKTOP_OAUTH_LOGIN_REDIRECT_URI);
  946. expect(parsed.searchParams.get("client_id")).toBe("client_P8X5CMWmlaRO9gyO-KSqtg");
  947. });
  948. it("uses test zcode website OAuth login redirect for BigModel in test environment", async () => {
  949. const service = createBigModelService({
  950. env: {
  951. ...cleanProcessEnv,
  952. BIGMODEL_OAUTH_APP_SECRET: "unit-test-secret",
  953. ZCODE_ENV: "test",
  954. },
  955. });
  956. const { authorizeUrl } = await service.startOAuth(BIGMODEL_PROVIDER_ID);
  957. const parsed = new URL(authorizeUrl);
  958. expect(parsed.searchParams.get("redirect")).toBe(TEST_DESKTOP_OAUTH_LOGIN_REDIRECT_URI);
  959. });
  960. it("uses bigmodel.cn to build BigModel authorize URL when ZCODE_ENV=test", async () => {
  961. const service = createBigModelService({
  962. env: {
  963. ...cleanProcessEnv,
  964. BIGMODEL_OAUTH_APP_SECRET: "unit-test-secret",
  965. ZCODE_ENV: "test",
  966. },
  967. });
  968. const { authorizeUrl } = await service.startOAuth(BIGMODEL_PROVIDER_ID);
  969. const parsed = new URL(authorizeUrl);
  970. expect(parsed.origin + parsed.pathname).toBe("https://bigmodel.cn/login");
  971. });
  972. it("uses production bigmodel.cn to build BigModel authorize URL when ZCODE_ENV=production", async () => {
  973. const service = createBigModelService({
  974. env: {
  975. ...process.env,
  976. BIGMODEL_OAUTH_APP_SECRET: "unit-test-secret",
  977. ZCODE_ENV: "production",
  978. },
  979. });
  980. const { authorizeUrl } = await service.startOAuth(BIGMODEL_PROVIDER_ID);
  981. const parsed = new URL(authorizeUrl);
  982. expect(parsed.origin + parsed.pathname).toBe("https://bigmodel.cn/login");
  983. });
  984. it("accepts attribution once and preserves the same state for the final authorization callback", async () => {
  985. const fetchMock = vi.fn<typeof fetch>();
  986. const service = createBigModelService({
  987. apiClient: createMockApiClient(fetchMock),
  988. });
  989. const { state } = await service.startOAuth(BIGMODEL_PROVIDER_ID);
  990. await expect(
  991. service.handleCallback(
  992. `zcode://oauth/callback?state=${state}&channel_id=google_ads&utm_source=google`,
  993. ),
  994. ).resolves.toEqual({
  995. kind: "attribution",
  996. provider: BIGMODEL_PROVIDER_ID,
  997. attribution: {
  998. channel_id: "google_ads",
  999. utm_source: "google",
  1000. },
  1001. });
  1002. expect(await credentialServiceStub.load("oauth:login_attribution")).toBe(
  1003. JSON.stringify({ channel_id: "google_ads", utm_source: "google" }),
  1004. );
  1005. await expect(
  1006. service.handleCallback(
  1007. `zcode://oauth/callback?state=${state}&channel_id=duplicate&utm_source=duplicate`,
  1008. ),
  1009. ).rejects.toThrow("OAuth 归因回调已处理");
  1010. expect(await credentialServiceStub.load("oauth:login_attribution")).toBe(
  1011. JSON.stringify({ channel_id: "google_ads", utm_source: "google" }),
  1012. );
  1013. fetchMock.mockResolvedValueOnce(createBigModelZcodeTokenResponse());
  1014. fetchMock.mockResolvedValueOnce(createBigModelUserInfoResponse());
  1015. await expect(
  1016. service.handleCallback(`zcode://oauth/callback?authCode=auth-code-001&state=${state}`),
  1017. ).resolves.toMatchObject({
  1018. kind: "session",
  1019. provider: BIGMODEL_PROVIDER_ID,
  1020. });
  1021. });
  1022. it("invalidates an attributed state when a new OAuth flow starts", async () => {
  1023. const service = createBigModelService({
  1024. apiClient: createMockApiClient(vi.fn<typeof fetch>()),
  1025. });
  1026. const first = await service.startOAuth(BIGMODEL_PROVIDER_ID);
  1027. await service.handleCallback(
  1028. `zcode://oauth/callback?state=${first.state}&channel_id=google_ads`,
  1029. );
  1030. const second = await service.startOAuth(BIGMODEL_PROVIDER_ID);
  1031. await expect(
  1032. service.handleCallback(`zcode://oauth/callback?authCode=old-code&state=${first.state}`),
  1033. ).rejects.toThrow("OAuth state 不匹配或已过期");
  1034. expect(second.state).not.toBe(first.state);
  1035. await service.cancelPending();
  1036. });
  1037. it("expires an attributed state after the OAuth timeout", async () => {
  1038. vi.useFakeTimers();
  1039. const service = createBigModelService({
  1040. apiClient: createMockApiClient(vi.fn<typeof fetch>()),
  1041. });
  1042. const { state } = await service.startOAuth(BIGMODEL_PROVIDER_ID);
  1043. await service.handleCallback(`zcode://oauth/callback?state=${state}&channel_id=google_ads`);
  1044. await vi.advanceTimersByTimeAsync(5 * 60 * 1000);
  1045. await expect(
  1046. service.handleCallback(`zcode://oauth/callback?authCode=late-code&state=${state}`),
  1047. ).rejects.toThrow("OAuth state 不匹配或已过期");
  1048. });
  1049. // Windows 机器上设置了 ZAI_TEST_OAUTH_ORIGIN 等环境变量,会覆盖测试预期的 test 端点值
  1050. it("uses testZAI endpoints from runtime ZCODE_ENV without explicit origin overrides", async () => {
  1051. const service = createBigModelService({
  1052. env: {
  1053. ...cleanProcessEnv,
  1054. BIGMODEL_OAUTH_APP_SECRET: "unit-test-secret",
  1055. ZCODE_ENV: "test",
  1056. },
  1057. });
  1058. const { authorizeUrl } = await service.startOAuth(ZAI_PROVIDER_ID);
  1059. const parsed = new URL(authorizeUrl);
  1060. expect(parsed.origin + parsed.pathname).toBe(
  1061. "https://chat.z.ai/api/oauth/authorize",
  1062. );
  1063. expect(parsed.searchParams.get("client_id")).toBe("client_P8X5CMWmlaRO9gyO-KSqtg");
  1064. });
  1065. it("stores zai credential keys and active provider after callback", async () => {
  1066. const fetchMock = vi.fn<typeof fetch>();
  1067. const service = createBigModelService({
  1068. apiClient: createMockApiClient(fetchMock),
  1069. });
  1070. const { state } = await service.startOAuth(ZAI_PROVIDER_ID);
  1071. fetchMock.mockResolvedValueOnce(
  1072. new Response(
  1073. JSON.stringify({
  1074. code: 0,
  1075. msg: "",
  1076. data: {
  1077. token: "zcode_backend_jwt",
  1078. zai: {
  1079. access_token: "zai_oauth_access_token",
  1080. },
  1081. expires_in: 86400,
  1082. user: {
  1083. user_id: "zai-u-001",
  1084. email: "user@example.com",
  1085. avatar: "https://example.com/zai-avatar.png",
  1086. created_at: "2026-04-27T10:00:00Z",
  1087. },
  1088. },
  1089. }),
  1090. { status: 200, headers: { "Content-Type": "application/json" } },
  1091. ),
  1092. );
  1093. fetchMock.mockResolvedValueOnce(createZaiBusinessLoginResponse());
  1094. const result = await service.handleCallback(
  1095. `zcode://oauth/callback?code=zai-code-001&state=${state}&channel_id=google_ads&utm_source=google&utm_campaign=brand_search`,
  1096. );
  1097. expect(fetchMock).toHaveBeenCalledTimes(2);
  1098. expect(fetchMock).toHaveBeenNthCalledWith(
  1099. 1,
  1100. ZAI_OAUTH_PROVIDER_CONFIG.tokenUrl,
  1101. expect.objectContaining({
  1102. method: "POST",
  1103. headers: { "Content-Type": "application/json" },
  1104. }),
  1105. );
  1106. const tokenCall = fetchMock.mock.calls[0];
  1107. if (!tokenCall) {
  1108. throw new Error("missing token call");
  1109. }
  1110. const tokenInit = tokenCall[1] as RequestInit;
  1111. expect(JSON.parse(String(tokenInit.body))).toEqual({
  1112. provider: ZAI_PROVIDER_ID,
  1113. code: "zai-code-001",
  1114. redirect_uri: PRODUCTION_DESKTOP_OAUTH_LOGIN_REDIRECT_URI,
  1115. state,
  1116. });
  1117. expect(result).toEqual({
  1118. kind: "session",
  1119. provider: ZAI_PROVIDER_ID,
  1120. userInfo: {
  1121. id: "zai-u-001",
  1122. username: "user@example.com",
  1123. displayName: "user@example.com",
  1124. avatarUrl: "https://example.com/zai-avatar.png",
  1125. },
  1126. });
  1127. expect(await credentialServiceStub.load("oauth:zai:access_token")).toBe(
  1128. "zai_business_access_token",
  1129. );
  1130. expect(await credentialServiceStub.load("oauth:zai:refresh_token")).toBeNull();
  1131. expect(await credentialServiceStub.load("zcodejwttoken")).toBe("zcode_backend_jwt");
  1132. expect(await credentialServiceStub.load("oauth:login_attribution")).toBe(
  1133. JSON.stringify({
  1134. channel_id: "google_ads",
  1135. utm_source: "google",
  1136. utm_campaign: "brand_search",
  1137. }),
  1138. );
  1139. expect(await credentialServiceStub.load("oauth:zai:user_info")).toBe(
  1140. JSON.stringify({
  1141. user_id: "zai-u-001",
  1142. email: "user@example.com",
  1143. avatar: "https://example.com/zai-avatar.png",
  1144. created_at: "2026-04-27T10:00:00Z",
  1145. }),
  1146. );
  1147. expect(await credentialServiceStub.load("oauth:active_provider")).toBe(ZAI_PROVIDER_ID);
  1148. });
  1149. it("uses ZCODE_BASE_URL for zai backend token exchange", async () => {
  1150. const fetchMock = vi.fn<typeof fetch>();
  1151. const service = createBigModelService({
  1152. apiClient: createMockApiClient(fetchMock),
  1153. env: {
  1154. ...process.env,
  1155. BIGMODEL_OAUTH_APP_SECRET: "unit-test-secret",
  1156. ZCODE_BASE_URL: "https://zcode.z.ai",
  1157. },
  1158. });
  1159. const { state } = await service.startOAuth(ZAI_PROVIDER_ID);
  1160. fetchMock.mockResolvedValueOnce(
  1161. new Response(
  1162. JSON.stringify({
  1163. code: 0,
  1164. msg: "",
  1165. data: {
  1166. token: "zcode_backend_jwt",
  1167. zai: { access_token: "zai_oauth_access_token" },
  1168. user: { user_id: "zai-u-001", email: "user@example.com" },
  1169. },
  1170. }),
  1171. { status: 200, headers: { "Content-Type": "application/json" } },
  1172. ),
  1173. );
  1174. fetchMock.mockResolvedValueOnce(createZaiBusinessLoginResponse());
  1175. await service.handleCallback(`zcode://oauth/callback?code=zai-code-001&state=${state}`);
  1176. expect(fetchMock).toHaveBeenNthCalledWith(
  1177. 1,
  1178. "https://zcode.z.ai/api/v1/oauth/token",
  1179. expect.objectContaining({ method: "POST" }),
  1180. );
  1181. });
  1182. it("uses ZAI_BUSINESS_BASE_URL for zai business token exchange", async () => {
  1183. const fetchMock = vi.fn<typeof fetch>();
  1184. const service = createBigModelService({
  1185. apiClient: createMockApiClient(fetchMock),
  1186. env: {
  1187. ...process.env,
  1188. BIGMODEL_OAUTH_APP_SECRET: "unit-test-secret",
  1189. ZAI_BUSINESS_BASE_URL: "https://api.z.ai",
  1190. },
  1191. });
  1192. const { state } = await service.startOAuth(ZAI_PROVIDER_ID);
  1193. fetchMock.mockResolvedValueOnce(
  1194. new Response(
  1195. JSON.stringify({
  1196. code: 0,
  1197. msg: "",
  1198. data: {
  1199. token: "zcode_backend_jwt",
  1200. zai: { access_token: "zai_oauth_access_token" },
  1201. user: { user_id: "zai-u-001", email: "user@example.com" },
  1202. },
  1203. }),
  1204. { status: 200, headers: { "Content-Type": "application/json" } },
  1205. ),
  1206. );
  1207. fetchMock.mockResolvedValueOnce(createZaiBusinessLoginResponse());
  1208. await service.handleCallback(`zcode://oauth/callback?code=zai-code-001&state=${state}`);
  1209. expect(fetchMock).toHaveBeenNthCalledWith(
  1210. 2,
  1211. "https://api.z.ai/api/auth/z/login",
  1212. expect.objectContaining({ method: "POST" }),
  1213. );
  1214. });
  1215. it("uses zai backend user name without prefixing avatar path after callback", async () => {
  1216. const fetchMock = vi.fn<typeof fetch>();
  1217. const service = createBigModelService({
  1218. apiClient: createMockApiClient(fetchMock),
  1219. });
  1220. const { state } = await service.startOAuth(ZAI_PROVIDER_ID);
  1221. fetchMock.mockResolvedValueOnce(
  1222. new Response(
  1223. JSON.stringify({
  1224. code: 0,
  1225. msg: "",
  1226. data: {
  1227. token: "zcode_backend_jwt",
  1228. zai: {
  1229. access_token: "zai_oauth_access_token",
  1230. },
  1231. user: {
  1232. user_id: "zai-u-001",
  1233. email: "13800000000@phone.local",
  1234. avatar: "/user.png",
  1235. name: "旅行者0000",
  1236. },
  1237. },
  1238. }),
  1239. { status: 200, headers: { "Content-Type": "application/json" } },
  1240. ),
  1241. );
  1242. fetchMock.mockResolvedValueOnce(createZaiBusinessLoginResponse());
  1243. await expect(
  1244. service.handleCallback(`zcode://oauth/callback?code=zai-code-001&state=${state}`),
  1245. ).resolves.toEqual({
  1246. kind: "session",
  1247. provider: ZAI_PROVIDER_ID,
  1248. userInfo: {
  1249. id: "zai-u-001",
  1250. username: "旅行者0000",
  1251. displayName: "旅行者0000",
  1252. avatarUrl: "/user.png",
  1253. },
  1254. });
  1255. });
  1256. it("keeps zai backend base64 avatar renderable after callback", async () => {
  1257. const fetchMock = vi.fn<typeof fetch>();
  1258. const service = createBigModelService({
  1259. apiClient: createMockApiClient(fetchMock),
  1260. });
  1261. const { state } = await service.startOAuth(ZAI_PROVIDER_ID);
  1262. const pngBase64 =
  1263. "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=";
  1264. fetchMock.mockResolvedValueOnce(
  1265. new Response(
  1266. JSON.stringify({
  1267. code: 0,
  1268. msg: "",
  1269. data: {
  1270. token: "zcode_backend_jwt",
  1271. zai: {
  1272. access_token: "zai_oauth_access_token",
  1273. },
  1274. user: {
  1275. user_id: "zai-u-002",
  1276. email: "user@example.com",
  1277. avatar: pngBase64,
  1278. name: "Base64 User",
  1279. },
  1280. },
  1281. }),
  1282. { status: 200, headers: { "Content-Type": "application/json" } },
  1283. ),
  1284. );
  1285. fetchMock.mockResolvedValueOnce(createZaiBusinessLoginResponse());
  1286. await expect(
  1287. service.handleCallback(`zcode://oauth/callback?code=zai-code-002&state=${state}`),
  1288. ).resolves.toEqual({
  1289. kind: "session",
  1290. provider: ZAI_PROVIDER_ID,
  1291. userInfo: {
  1292. id: "zai-u-002",
  1293. username: "Base64 User",
  1294. displayName: "Base64 User",
  1295. avatarUrl: `data:image/png;base64,${pngBase64}`,
  1296. },
  1297. });
  1298. });
  1299. it("fails zai backend token exchange when business code is not zero", async () => {
  1300. const fetchMock = vi.fn<typeof fetch>();
  1301. const service = createBigModelService({
  1302. apiClient: createMockApiClient(fetchMock),
  1303. });
  1304. const { state } = await service.startOAuth(ZAI_PROVIDER_ID);
  1305. fetchMock.mockResolvedValueOnce(
  1306. new Response(
  1307. JSON.stringify({
  1308. code: 10001,
  1309. msg: "invalid oauth code",
  1310. data: null,
  1311. }),
  1312. { status: 200, headers: { "Content-Type": "application/json" } },
  1313. ),
  1314. );
  1315. await expect(
  1316. service.handleCallback(`zcode://oauth/callback?code=bad-code&state=${state}`),
  1317. ).rejects.toThrow(/invalid oauth code/);
  1318. expect(await credentialServiceStub.load("oauth:zai:access_token")).toBeNull();
  1319. expect(await credentialServiceStub.load("oauth:active_provider")).toBeNull();
  1320. });
  1321. it("fails zai backend token exchange when response misses data.zai.access_token", async () => {
  1322. const fetchMock = vi.fn<typeof fetch>();
  1323. const service = createBigModelService({
  1324. apiClient: createMockApiClient(fetchMock),
  1325. });
  1326. const { state } = await service.startOAuth(ZAI_PROVIDER_ID);
  1327. fetchMock.mockResolvedValueOnce(
  1328. new Response(
  1329. JSON.stringify({
  1330. code: 0,
  1331. msg: "",
  1332. data: {
  1333. token: "zcode_backend_jwt",
  1334. zai: {},
  1335. expires_in: 86400,
  1336. user: {
  1337. user_id: "zai-u-001",
  1338. email: "user@example.com",
  1339. },
  1340. },
  1341. }),
  1342. { status: 200, headers: { "Content-Type": "application/json" } },
  1343. ),
  1344. );
  1345. await expect(
  1346. service.handleCallback(`zcode://oauth/callback?code=zai-code-001&state=${state}`),
  1347. ).rejects.toThrow(/data.zai.access_token/);
  1348. expect(await credentialServiceStub.load("oauth:zai:access_token")).toBeNull();
  1349. expect(await credentialServiceStub.load("zcodejwttoken")).toBeNull();
  1350. expect(await credentialServiceStub.load("oauth:active_provider")).toBeNull();
  1351. });
  1352. it("fails zai backend token exchange when response misses data token", async () => {
  1353. const fetchMock = vi.fn<typeof fetch>();
  1354. const service = createBigModelService({
  1355. apiClient: createMockApiClient(fetchMock),
  1356. });
  1357. const { state } = await service.startOAuth(ZAI_PROVIDER_ID);
  1358. fetchMock.mockResolvedValueOnce(
  1359. new Response(
  1360. JSON.stringify({
  1361. code: 0,
  1362. msg: "",
  1363. data: {
  1364. zai: {
  1365. access_token: "zai_oauth_access_token",
  1366. },
  1367. user: {
  1368. user_id: "zai-u-001",
  1369. email: "user@example.com",
  1370. },
  1371. },
  1372. }),
  1373. { status: 200, headers: { "Content-Type": "application/json" } },
  1374. ),
  1375. );
  1376. await expect(
  1377. service.handleCallback(`zcode://oauth/callback?code=zai-code-001&state=${state}`),
  1378. ).rejects.toThrow(/data.token/);
  1379. expect(await credentialServiceStub.load("oauth:zai:access_token")).toBeNull();
  1380. expect(await credentialServiceStub.load("zcodejwttoken")).toBeNull();
  1381. expect(await credentialServiceStub.load("oauth:active_provider")).toBeNull();
  1382. });
  1383. it("falls back to zai userinfo when backend token response misses user", async () => {
  1384. const fetchMock = vi.fn<typeof fetch>();
  1385. const service = createBigModelService({
  1386. apiClient: createMockApiClient(fetchMock),
  1387. });
  1388. const { state } = await service.startOAuth(ZAI_PROVIDER_ID);
  1389. fetchMock.mockResolvedValueOnce(
  1390. new Response(
  1391. JSON.stringify({
  1392. code: 0,
  1393. msg: "",
  1394. data: {
  1395. token: "zcode_backend_jwt",
  1396. zai: {
  1397. access_token: "zai_oauth_access_token",
  1398. },
  1399. },
  1400. }),
  1401. { status: 200, headers: { "Content-Type": "application/json" } },
  1402. ),
  1403. );
  1404. fetchMock.mockResolvedValueOnce(createZaiBusinessLoginResponse());
  1405. fetchMock.mockResolvedValueOnce(
  1406. new Response(
  1407. JSON.stringify({
  1408. sub: "zai-u-003",
  1409. name: "Fallback User",
  1410. picture: "https://example.com/fallback-avatar.png",
  1411. }),
  1412. { status: 200, headers: { "Content-Type": "application/json" } },
  1413. ),
  1414. );
  1415. await expect(
  1416. service.handleCallback(`zcode://oauth/callback?code=zai-code-003&state=${state}`),
  1417. ).resolves.toEqual({
  1418. kind: "session",
  1419. provider: ZAI_PROVIDER_ID,
  1420. userInfo: {
  1421. id: "zai-u-003",
  1422. username: "Fallback User",
  1423. displayName: "Fallback User",
  1424. avatarUrl: "https://example.com/fallback-avatar.png",
  1425. },
  1426. });
  1427. expect(fetchMock).toHaveBeenCalledTimes(3);
  1428. expect(fetchMock).toHaveBeenNthCalledWith(
  1429. 3,
  1430. ZAI_OAUTH_PROVIDER_CONFIG.userinfoUrl,
  1431. expect.objectContaining({
  1432. method: "GET",
  1433. headers: {
  1434. Authorization: "Bearer zai_business_access_token",
  1435. "Content-Type": "application/json",
  1436. },
  1437. }),
  1438. );
  1439. });
  1440. it("maps zai backend expires_in into OAuthTokenSet expiresAt", async () => {
  1441. const fetchMock = vi.fn<typeof fetch>();
  1442. const adapter = new ZaiProviderAdapter(
  1443. {
  1444. ...ZAI_OAUTH_PROVIDER_CONFIG,
  1445. enabled: true,
  1446. },
  1447. createMockApiClient(fetchMock),
  1448. );
  1449. const now = 1_800_000_000_000;
  1450. fetchMock.mockResolvedValueOnce(
  1451. new Response(
  1452. JSON.stringify({
  1453. code: 0,
  1454. msg: "",
  1455. data: {
  1456. token: "zcode_backend_jwt",
  1457. zai: {
  1458. access_token: "zai_oauth_access_token",
  1459. },
  1460. expires_in: 86400,
  1461. },
  1462. }),
  1463. { status: 200, headers: { "Content-Type": "application/json" } },
  1464. ),
  1465. );
  1466. fetchMock.mockResolvedValueOnce(createZaiBusinessLoginResponse());
  1467. await expect(
  1468. adapter.exchangeToken(
  1469. { code: "zai-code-001", state: "state-001" },
  1470. {
  1471. providerId: ZAI_PROVIDER_ID,
  1472. state: "state-001",
  1473. redirectUri: ZAI_OAUTH_PROVIDER_CONFIG.redirectUri,
  1474. now: () => now,
  1475. },
  1476. ),
  1477. ).resolves.toEqual({
  1478. accessToken: "zai_business_access_token",
  1479. zcodeJwtToken: "zcode_backend_jwt",
  1480. expiresAt: now + 86400 * 1000,
  1481. });
  1482. });
  1483. it("logs zai backend token request without exposing full oauth code", async () => {
  1484. const fetchMock = vi.fn<typeof fetch>();
  1485. const consoleLogSpy = vi.spyOn(console, "log").mockImplementation(() => {});
  1486. const adapter = new ZaiProviderAdapter(
  1487. {
  1488. ...ZAI_OAUTH_PROVIDER_CONFIG,
  1489. enabled: true,
  1490. },
  1491. createMockApiClient(fetchMock),
  1492. );
  1493. const fullCode = "abcdefghijklmnopqrstuvwxyz";
  1494. fetchMock.mockResolvedValueOnce(
  1495. new Response(
  1496. JSON.stringify({
  1497. code: 0,
  1498. msg: "",
  1499. data: {
  1500. token: "zcode_backend_jwt",
  1501. zai: {
  1502. access_token: "zai_oauth_access_token",
  1503. },
  1504. },
  1505. }),
  1506. { status: 200, headers: { "Content-Type": "application/json" } },
  1507. ),
  1508. );
  1509. fetchMock.mockResolvedValueOnce(createZaiBusinessLoginResponse());
  1510. await adapter.exchangeToken(
  1511. { code: fullCode, state: "state-001" },
  1512. {
  1513. providerId: ZAI_PROVIDER_ID,
  1514. state: "state-001",
  1515. redirectUri: ZAI_OAUTH_PROVIDER_CONFIG.redirectUri,
  1516. now: () => 1_800_000_000_000,
  1517. },
  1518. );
  1519. expect(consoleLogSpy).toHaveBeenCalledWith(
  1520. expect.stringContaining("[zaiOAuth]"),
  1521. "token request",
  1522. {
  1523. method: "POST",
  1524. url: ZAI_OAUTH_PROVIDER_CONFIG.tokenUrl,
  1525. headers: { "Content-Type": "application/json" },
  1526. body: {
  1527. provider: ZAI_PROVIDER_ID,
  1528. code: "abcd...wxyz",
  1529. codeLength: 26,
  1530. redirect_uri: ZAI_OAUTH_PROVIDER_CONFIG.redirectUri,
  1531. state: "state-001",
  1532. },
  1533. },
  1534. );
  1535. expect(JSON.stringify(consoleLogSpy.mock.calls)).not.toContain(fullCode);
  1536. });
  1537. it("logs zai final token response body without exposing full token", async () => {
  1538. const fetchMock = vi.fn<typeof fetch>();
  1539. const consoleLogSpy = vi.spyOn(console, "log").mockImplementation(() => {});
  1540. const adapter = new ZaiProviderAdapter(
  1541. {
  1542. ...ZAI_OAUTH_PROVIDER_CONFIG,
  1543. enabled: true,
  1544. },
  1545. createMockApiClient(fetchMock),
  1546. );
  1547. const fullToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.mock-signature";
  1548. const fullZaiAccessToken = "zai_oauth_access_token_should_not_leak";
  1549. fetchMock.mockResolvedValueOnce(
  1550. new Response(
  1551. JSON.stringify({
  1552. code: 0,
  1553. msg: "",
  1554. data: {
  1555. token: fullToken,
  1556. zai: {
  1557. access_token: fullZaiAccessToken,
  1558. },
  1559. expires_in: 86400,
  1560. user: {
  1561. user_id: "u_xxxxx",
  1562. email: "user@example.com",
  1563. avatar: "https://example.com/avatar.png",
  1564. created_at: "2026-04-27T10:00:00Z",
  1565. },
  1566. },
  1567. }),
  1568. { status: 200, headers: { "Content-Type": "application/json" } },
  1569. ),
  1570. );
  1571. fetchMock.mockResolvedValueOnce(createZaiBusinessLoginResponse());
  1572. await adapter.exchangeToken(
  1573. { code: "zai-code-001", state: "state-001" },
  1574. {
  1575. providerId: ZAI_PROVIDER_ID,
  1576. state: "state-001",
  1577. redirectUri: ZAI_OAUTH_PROVIDER_CONFIG.redirectUri,
  1578. now: () => 1_800_000_000_000,
  1579. },
  1580. );
  1581. expect(consoleLogSpy).toHaveBeenCalledWith(
  1582. expect.stringContaining("[zaiOAuth]"),
  1583. "token final response body",
  1584. {
  1585. code: 0,
  1586. msg: "",
  1587. data: {
  1588. token: "eyJh...ture",
  1589. tokenLength: fullToken.length,
  1590. zai: {
  1591. access_token: "zai_...leak",
  1592. accessTokenLength: fullZaiAccessToken.length,
  1593. },
  1594. expires_in: 86400,
  1595. user: {
  1596. user_id: "u_xxxxx",
  1597. email: "user@example.com",
  1598. avatar: "https://example.com/avatar.png",
  1599. created_at: "2026-04-27T10:00:00Z",
  1600. },
  1601. },
  1602. },
  1603. );
  1604. expect(JSON.stringify(consoleLogSpy.mock.calls)).not.toContain(fullToken);
  1605. expect(JSON.stringify(consoleLogSpy.mock.calls)).not.toContain(fullZaiAccessToken);
  1606. });
  1607. it("logs zai token response request id on backend error", async () => {
  1608. const fetchMock = vi.fn<typeof fetch>();
  1609. const consoleLogSpy = vi.spyOn(console, "log").mockImplementation(() => {});
  1610. const adapter = new ZaiProviderAdapter(
  1611. {
  1612. ...ZAI_OAUTH_PROVIDER_CONFIG,
  1613. enabled: true,
  1614. },
  1615. createMockApiClient(fetchMock),
  1616. );
  1617. fetchMock.mockResolvedValueOnce(
  1618. new Response("404 page not found", {
  1619. status: 404,
  1620. headers: {
  1621. "Content-Type": "text/plain",
  1622. "set-cookie": "visitor_id=secret",
  1623. "x-request-id": "req-404",
  1624. "x-span-id": "span-404",
  1625. "x-trace-id": "trace-404",
  1626. },
  1627. }),
  1628. );
  1629. await expect(
  1630. adapter.exchangeToken(
  1631. { code: "authorization-code", state: "state-404" },
  1632. {
  1633. providerId: ZAI_PROVIDER_ID,
  1634. state: "state-404",
  1635. redirectUri: ZAI_OAUTH_PROVIDER_CONFIG.redirectUri,
  1636. now: () => 1_800_000_000_000,
  1637. },
  1638. ),
  1639. ).rejects.toEqual(
  1640. expect.objectContaining<ApiError>({
  1641. name: "ApiError",
  1642. method: "POST",
  1643. status: 404,
  1644. url: ZAI_OAUTH_PROVIDER_CONFIG.tokenUrl,
  1645. }),
  1646. );
  1647. expect(consoleLogSpy).toHaveBeenCalledWith(
  1648. expect.stringContaining("[zaiOAuth]"),
  1649. "token response error",
  1650. {
  1651. method: "POST",
  1652. url: ZAI_OAUTH_PROVIDER_CONFIG.tokenUrl,
  1653. status: 404,
  1654. responseHeaders: {
  1655. "x-request-id": "req-404",
  1656. "x-span-id": "span-404",
  1657. "x-trace-id": "trace-404",
  1658. },
  1659. },
  1660. );
  1661. expect(JSON.stringify(consoleLogSpy.mock.calls)).not.toContain("visitor_id=secret");
  1662. });
  1663. it("stores namespaced credential keys and active provider after callback", async () => {
  1664. const fetchMock = vi.fn<typeof fetch>();
  1665. const service = createBigModelService({
  1666. apiClient: createMockApiClient(fetchMock),
  1667. });
  1668. const { state } = await service.startOAuth(BIGMODEL_PROVIDER_ID);
  1669. fetchMock.mockResolvedValueOnce(createBigModelZcodeTokenResponse());
  1670. fetchMock.mockResolvedValueOnce(createBigModelUserInfoResponse());
  1671. const result = await service.handleCallback(
  1672. `zcode://oauth/callback?authCode=auth-code-001&state=${state}&utm_source=google`,
  1673. );
  1674. expect(fetchMock).toHaveBeenNthCalledWith(
  1675. 1,
  1676. "https://zcode.z.ai/api/v1/oauth/token",
  1677. expect.objectContaining({ method: "POST", headers: { "Content-Type": "application/json" } }),
  1678. );
  1679. const zcodeTokenCall = fetchMock.mock.calls[0];
  1680. if (!zcodeTokenCall) {
  1681. throw new Error("missing zcode token call");
  1682. }
  1683. const zcodeTokenInit = zcodeTokenCall[1] as RequestInit;
  1684. expect(JSON.parse(String(zcodeTokenInit.body))).toEqual({
  1685. provider: BIGMODEL_PROVIDER_ID,
  1686. code: "auth-code-001",
  1687. redirect_uri: PRODUCTION_DESKTOP_OAUTH_LOGIN_REDIRECT_URI,
  1688. state,
  1689. });
  1690. expect(result).toEqual({
  1691. kind: "session",
  1692. provider: BIGMODEL_PROVIDER_ID,
  1693. userInfo: {
  1694. id: "bigmodel-u-001",
  1695. username: "BigModel User",
  1696. displayName: "BigModel User",
  1697. },
  1698. });
  1699. expect(fetchMock).toHaveBeenCalledTimes(2);
  1700. expect(fetchMock).toHaveBeenNthCalledWith(
  1701. 2,
  1702. BIGMODEL_OAUTH_PROVIDER_CONFIG.userinfoUrl,
  1703. expect.objectContaining({
  1704. method: "GET",
  1705. headers: {
  1706. Authorization: "bigmodel-business-access-token",
  1707. "Content-Type": "application/json",
  1708. },
  1709. }),
  1710. );
  1711. expect(await credentialServiceStub.load("oauth:bigmodel:access_token")).toBe(
  1712. "bigmodel-business-access-token",
  1713. );
  1714. expect(await credentialServiceStub.load("oauth:bigmodel:refresh_token")).toBeNull();
  1715. expect(await credentialServiceStub.load("zcodejwttoken")).toBe("bigmodel-zcode-jwt");
  1716. expect(await credentialServiceStub.load("oauth:login_attribution")).toBe(
  1717. JSON.stringify({ utm_source: "google" }),
  1718. );
  1719. expect(await credentialServiceStub.load("oauth:bigmodel:user_info")).toBe(
  1720. JSON.stringify({
  1721. ...result.userInfo,
  1722. rawProfile: { zcodeProfileSchemaVersion: 2 },
  1723. }),
  1724. );
  1725. expect(await credentialServiceStub.load("oauth:active_provider")).toBe(BIGMODEL_PROVIDER_ID);
  1726. expect(await credentialServiceStub.load("auth_token")).toBeNull();
  1727. expect(await credentialServiceStub.load("refresh_token")).toBeNull();
  1728. expect(await credentialServiceStub.load("user_info")).toBeNull();
  1729. });
  1730. it("uses BigModel customerName before nickName for user display", async () => {
  1731. const fetchMock = vi.fn<typeof fetch>();
  1732. const service = createBigModelService({
  1733. apiClient: createMockApiClient(fetchMock),
  1734. });
  1735. const { state } = await service.startOAuth(BIGMODEL_PROVIDER_ID);
  1736. fetchMock.mockResolvedValueOnce(createBigModelZcodeTokenResponse());
  1737. fetchMock.mockResolvedValueOnce(
  1738. createBigModelUserInfoResponse("Nickname User", "bigmodel-u-001", "Customer User"),
  1739. );
  1740. const result = await service.handleCallback(
  1741. `zcode://oauth/callback?authCode=auth-code-001&state=${state}`,
  1742. );
  1743. expect(result.userInfo).toEqual({
  1744. id: "bigmodel-u-001",
  1745. username: "Customer User",
  1746. displayName: "Customer User",
  1747. });
  1748. expect(await credentialServiceStub.load("oauth:bigmodel:user_info")).toBe(
  1749. JSON.stringify({
  1750. ...result.userInfo,
  1751. rawProfile: { zcodeProfileSchemaVersion: 2 },
  1752. }),
  1753. );
  1754. });
  1755. it.each([
  1756. ["empty customerName", ""],
  1757. ["blank customerName", " "],
  1758. ])("falls back to BigModel nickName when %s is returned", async (_label, customerName) => {
  1759. const fetchMock = vi.fn<typeof fetch>();
  1760. const service = createBigModelService({
  1761. apiClient: createMockApiClient(fetchMock),
  1762. });
  1763. const { state } = await service.startOAuth(BIGMODEL_PROVIDER_ID);
  1764. fetchMock.mockResolvedValueOnce(createBigModelZcodeTokenResponse());
  1765. fetchMock.mockResolvedValueOnce(
  1766. createBigModelUserInfoResponse("Nickname User", "bigmodel-u-001", customerName),
  1767. );
  1768. const result = await service.handleCallback(
  1769. `zcode://oauth/callback?authCode=auth-code-001&state=${state}`,
  1770. );
  1771. expect(result.userInfo).toEqual({
  1772. id: "bigmodel-u-001",
  1773. username: "Nickname User",
  1774. displayName: "Nickname User",
  1775. });
  1776. });
  1777. it("falls back to BigModel nickName when customerName has malformed type", async () => {
  1778. const fetchMock = vi.fn<typeof fetch>();
  1779. const service = createBigModelService({
  1780. apiClient: createMockApiClient(fetchMock),
  1781. });
  1782. const { state } = await service.startOAuth(BIGMODEL_PROVIDER_ID);
  1783. fetchMock.mockResolvedValueOnce(createBigModelZcodeTokenResponse());
  1784. fetchMock.mockResolvedValueOnce(
  1785. createBigModelUserInfoResponse("Nickname User", "bigmodel-u-001", 123),
  1786. );
  1787. const result = await service.handleCallback(
  1788. `zcode://oauth/callback?authCode=auth-code-001&state=${state}`,
  1789. );
  1790. expect(result.userInfo).toEqual({
  1791. id: "bigmodel-u-001",
  1792. username: "Nickname User",
  1793. displayName: "Nickname User",
  1794. });
  1795. });
  1796. it("falls back to default BigModel username when display fields have malformed types", async () => {
  1797. const fetchMock = vi.fn<typeof fetch>();
  1798. const service = createBigModelService({
  1799. apiClient: createMockApiClient(fetchMock),
  1800. });
  1801. const { state } = await service.startOAuth(BIGMODEL_PROVIDER_ID);
  1802. fetchMock.mockResolvedValueOnce(createBigModelZcodeTokenResponse());
  1803. fetchMock.mockResolvedValueOnce(
  1804. createBigModelUserInfoResponse({ value: "Nickname User" }, "bigmodel-u-001", 123),
  1805. );
  1806. const result = await service.handleCallback(
  1807. `zcode://oauth/callback?authCode=auth-code-001&state=${state}`,
  1808. );
  1809. expect(result.userInfo).toEqual({
  1810. id: "bigmodel-u-001",
  1811. username: "user",
  1812. displayName: "user",
  1813. });
  1814. });
  1815. it("uses ZCODE_BASE_URL for bigmodel backend token exchange", async () => {
  1816. const fetchMock = vi.fn<typeof fetch>();
  1817. const service = createBigModelService({
  1818. apiClient: createMockApiClient(fetchMock),
  1819. env: {
  1820. ...process.env,
  1821. BIGMODEL_OAUTH_APP_SECRET: "unit-test-secret",
  1822. ZCODE_BASE_URL: "https://zcode.z.ai",
  1823. },
  1824. });
  1825. const { state } = await service.startOAuth(BIGMODEL_PROVIDER_ID);
  1826. fetchMock.mockResolvedValueOnce(createBigModelZcodeTokenResponse());
  1827. fetchMock.mockResolvedValueOnce(createBigModelUserInfoResponse());
  1828. await service.handleCallback(`zcode://oauth/callback?authCode=auth-code-001&state=${state}`);
  1829. expect(fetchMock).toHaveBeenNthCalledWith(
  1830. 1,
  1831. "https://zcode.z.ai/api/v1/oauth/token",
  1832. expect.objectContaining({ method: "POST" }),
  1833. );
  1834. });
  1835. // Windows 机器上设置了 ZCODE_TEST_BASE_URL 等环境变量,会覆盖测试预期的 test 端点值
  1836. it("uses test product endpoints for bigmodel token exchange and userinfo", async () => {
  1837. const fetchMock = vi.fn<typeof fetch>();
  1838. const service = createBigModelService({
  1839. apiClient: createMockApiClient(fetchMock),
  1840. env: {
  1841. ...cleanProcessEnv,
  1842. BIGMODEL_OAUTH_APP_SECRET: "unit-test-secret",
  1843. ZCODE_ENV: "test",
  1844. },
  1845. });
  1846. const { state } = await service.startOAuth(BIGMODEL_PROVIDER_ID);
  1847. fetchMock.mockResolvedValueOnce(createBigModelZcodeTokenResponse());
  1848. fetchMock.mockResolvedValueOnce(createBigModelUserInfoResponse());
  1849. await service.handleCallback(`zcode://oauth/callback?authCode=auth-code-001&state=${state}`);
  1850. expect(fetchMock).toHaveBeenNthCalledWith(
  1851. 1,
  1852. "https://zcode.z.ai/api/v1/oauth/token",
  1853. expect.objectContaining({ method: "POST" }),
  1854. );
  1855. expect(fetchMock).toHaveBeenNthCalledWith(
  1856. 2,
  1857. "https://bigmodel.cn/api/biz/customer/getCustomerInfo",
  1858. expect.objectContaining({ method: "GET" }),
  1859. );
  1860. });
  1861. it("bigmodel zcode token 非 2xx 时中止登录并记录后端 msg", async () => {
  1862. const fetchMock = vi.fn<typeof fetch>();
  1863. const consoleWarnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
  1864. const service = createBigModelService({
  1865. apiClient: createMockApiClient(fetchMock),
  1866. });
  1867. const { state } = await service.startOAuth(BIGMODEL_PROVIDER_ID);
  1868. fetchMock.mockResolvedValueOnce(
  1869. new Response(JSON.stringify({ code: 2007, msg: "http error" }), {
  1870. status: 500,
  1871. headers: {
  1872. "Content-Type": "application/json",
  1873. "x-request-id": "req-zcode-500",
  1874. },
  1875. }),
  1876. );
  1877. await expect(
  1878. service.handleCallback(`zcode://oauth/callback?authCode=auth-code-500&state=${state}`),
  1879. ).rejects.toMatchObject<ApiError>({
  1880. name: "ApiError",
  1881. method: "POST",
  1882. status: 500,
  1883. url: "https://zcode.z.ai/api/v1/oauth/token",
  1884. message: "http error",
  1885. });
  1886. expect(await credentialServiceStub.load("oauth:bigmodel:access_token")).toBeNull();
  1887. expect(await credentialServiceStub.load("zcodejwttoken")).toBeNull();
  1888. expect(JSON.stringify(consoleWarnSpy.mock.calls)).toContain("http error");
  1889. expect(JSON.stringify(consoleWarnSpy.mock.calls)).toContain("req-zcode-500");
  1890. });
  1891. it("keeps polling available when deep-link token exchange fails", async () => {
  1892. let rejectExchange!: (error: Error) => void;
  1893. const exchangeStarted = new Promise<never>((_, reject) => {
  1894. rejectExchange = reject;
  1895. });
  1896. const fetchMock = vi.fn<typeof fetch>(async (input) => {
  1897. const url = String(input);
  1898. if (url.endsWith("/api/v1/oauth/cli/init")) {
  1899. return new Response(
  1900. JSON.stringify({
  1901. code: 0,
  1902. data: {
  1903. authorize_url: "https://example.com/authorize?state=flow-state",
  1904. expires_at: 2_000_000_300,
  1905. flow_id: "flow-1",
  1906. poll_interval_sec: 1,
  1907. poll_token: "poll-token",
  1908. },
  1909. }),
  1910. { status: 200, headers: { "Content-Type": "application/json" } },
  1911. );
  1912. }
  1913. if (url.endsWith("/api/v1/oauth/cli/poll/flow-1")) {
  1914. return new Response(
  1915. JSON.stringify({
  1916. code: 0,
  1917. data: {
  1918. status: "ready",
  1919. token: "poll-jwt",
  1920. user: { user_id: "poll-user", name: "Poll User" },
  1921. bigmodel: { access_token: "poll-provider-token" },
  1922. },
  1923. }),
  1924. { status: 200, headers: { "Content-Type": "application/json" } },
  1925. );
  1926. }
  1927. throw new Error(`Unexpected request: ${url}`);
  1928. });
  1929. const service = new OAuthService(credentialServiceStub, {
  1930. apiClient: createMockApiClient(fetchMock),
  1931. adapters: [
  1932. {
  1933. providerId: BIGMODEL_PROVIDER_ID,
  1934. meta: { id: BIGMODEL_PROVIDER_ID, displayName: "BigModel", enabled: true, order: 1 },
  1935. redirectUri: DESKTOP_OAUTH_CALLBACK_URI,
  1936. buildAuthorizeUrl: ({ state }) => `https://example.com/authorize?state=${state}`,
  1937. parseCallbackParams: (url) => ({
  1938. code: new URL(url).searchParams.get("code") ?? "",
  1939. state: new URL(url).searchParams.get("state") ?? "",
  1940. }),
  1941. exchangeToken: async () => exchangeStarted,
  1942. normalizePolledTokenSet: async ({ accessToken, zcodeJwtToken }) => ({
  1943. accessToken,
  1944. zcodeJwtToken,
  1945. }),
  1946. normalizeError: (error: unknown) =>
  1947. error instanceof Error ? error : new Error(String(error)),
  1948. },
  1949. ],
  1950. now: () => 2_000_000_000_000,
  1951. });
  1952. const started = await service.startOAuthWithPolling(BIGMODEL_PROVIDER_ID);
  1953. const deepLink = service.handleCallback(
  1954. `zcode://oauth/callback?state=${started.state}&code=deep-link-code`,
  1955. );
  1956. await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
  1957. rejectExchange(new Error("deep-link exchange failed"));
  1958. await expect(deepLink).rejects.toThrow("deep-link exchange failed");
  1959. await expect(service.pollPendingOAuth()).resolves.toEqual({
  1960. kind: "session",
  1961. provider: BIGMODEL_PROVIDER_ID,
  1962. userInfo: { id: "poll-user", username: "Poll User", displayName: "Poll User" },
  1963. });
  1964. expect(await credentialServiceStub.load("oauth:bigmodel:access_token")).toBe(
  1965. "poll-provider-token",
  1966. );
  1967. });
  1968. it("does not persist a deep-link result after cancellation", async () => {
  1969. let resolveExchange!: (tokenSet: OAuthTokenSet) => void;
  1970. const exchange = new Promise<OAuthTokenSet>((resolve) => {
  1971. resolveExchange = resolve;
  1972. });
  1973. const service = new OAuthService(credentialServiceStub, {
  1974. adapters: [
  1975. {
  1976. providerId: BIGMODEL_PROVIDER_ID,
  1977. meta: { id: BIGMODEL_PROVIDER_ID, displayName: "BigModel", enabled: true, order: 1 },
  1978. redirectUri: DESKTOP_OAUTH_CALLBACK_URI,
  1979. buildAuthorizeUrl: ({ state }) => `https://example.com/authorize?state=${state}`,
  1980. parseCallbackParams: (url) => ({
  1981. code: new URL(url).searchParams.get("code") ?? "",
  1982. state: new URL(url).searchParams.get("state") ?? "",
  1983. }),
  1984. exchangeToken: async () => exchange,
  1985. normalizeError: (error: unknown) =>
  1986. error instanceof Error ? error : new Error(String(error)),
  1987. },
  1988. ],
  1989. });
  1990. const { state } = await service.startOAuth(BIGMODEL_PROVIDER_ID);
  1991. const callback = service.handleCallback(`zcode://oauth/callback?state=${state}&code=late`);
  1992. await Promise.resolve();
  1993. await service.cancelPending();
  1994. resolveExchange({ accessToken: "cancelled-token" });
  1995. await expect(callback).resolves.toBeNull();
  1996. expect(await credentialServiceStub.load("oauth:active_provider")).toBeNull();
  1997. expect(await credentialServiceStub.load("zcodejwttoken")).toBeNull();
  1998. });
  1999. it("clears the opposite OAuth provider when switching App login provider", async () => {
  2000. const fetchMock = vi.fn<typeof fetch>();
  2001. const service = createBigModelService({
  2002. apiClient: createMockApiClient(fetchMock),
  2003. });
  2004. await credentialServiceStub.save("oauth:zai:access_token", "old-zai-token");
  2005. await credentialServiceStub.save(
  2006. "oauth:zai:user_info",
  2007. JSON.stringify({
  2008. id: "zai-old",
  2009. username: "zai-old",
  2010. displayName: "ZAI Old",
  2011. }),
  2012. );
  2013. await credentialServiceStub.save("zcodejwttoken", "old-zcode-jwt");
  2014. const { state } = await service.startOAuth(BIGMODEL_PROVIDER_ID);
  2015. fetchMock.mockResolvedValueOnce(
  2016. createBigModelZcodeTokenResponse("new-bigmodel-zcode-jwt", "new-bigmodel-business-token"),
  2017. );
  2018. fetchMock.mockResolvedValueOnce(createBigModelUserInfoResponse());
  2019. await service.handleCallback(`zcode://oauth/callback?authCode=switch-code&state=${state}`);
  2020. expect(await credentialServiceStub.load("oauth:active_provider")).toBe(BIGMODEL_PROVIDER_ID);
  2021. expect(await credentialServiceStub.load("oauth:bigmodel:access_token")).toBe(
  2022. "new-bigmodel-business-token",
  2023. );
  2024. expect(await credentialServiceStub.load("oauth:zai:access_token")).toBeNull();
  2025. expect(await credentialServiceStub.load("oauth:zai:user_info")).toBeNull();
  2026. expect(await credentialServiceStub.load("zcodejwttoken")).toBe("new-bigmodel-zcode-jwt");
  2027. });
  2028. it("BigModel zcode token 响应缺少 token 时中止登录", async () => {
  2029. const fetchMock = vi.fn<typeof fetch>();
  2030. const service = createBigModelService({
  2031. apiClient: createMockApiClient(fetchMock),
  2032. });
  2033. const { state } = await service.startOAuth(BIGMODEL_PROVIDER_ID);
  2034. fetchMock.mockResolvedValueOnce(
  2035. new Response(
  2036. JSON.stringify({
  2037. code: 0,
  2038. data: {},
  2039. }),
  2040. { status: 200, headers: { "Content-Type": "application/json" } },
  2041. ),
  2042. );
  2043. await expect(
  2044. service.handleCallback(`zcode://oauth/callback?authCode=auth-code-missing&state=${state}`),
  2045. ).rejects.toThrow(/缺少 data.token/);
  2046. expect(await credentialServiceStub.load("oauth:bigmodel:access_token")).toBeNull();
  2047. expect(await credentialServiceStub.load("zcodejwttoken")).toBeNull();
  2048. });
  2049. it("BigModel zcode token 业务失败时透出 msg", async () => {
  2050. const fetchMock = vi.fn<typeof fetch>();
  2051. const service = createBigModelService({
  2052. apiClient: createMockApiClient(fetchMock),
  2053. });
  2054. const { state } = await service.startOAuth(BIGMODEL_PROVIDER_ID);
  2055. fetchMock.mockResolvedValueOnce(
  2056. new Response(
  2057. JSON.stringify({
  2058. code: 10002,
  2059. msg: "authCode 已过期",
  2060. data: null,
  2061. }),
  2062. { status: 200, headers: { "Content-Type": "application/json" } },
  2063. ),
  2064. );
  2065. await expect(
  2066. service.handleCallback(`zcode://oauth/callback?authCode=auth-code-expired&state=${state}`),
  2067. ).rejects.toThrow(/authCode 已过期/);
  2068. expect(await credentialServiceStub.load("oauth:bigmodel:access_token")).toBeNull();
  2069. });
  2070. it("兼容 BigModel callback code 字段并只消费一次授权码", async () => {
  2071. const fetchMock = vi.fn<typeof fetch>();
  2072. const service = createBigModelService({
  2073. apiClient: createMockApiClient(fetchMock),
  2074. });
  2075. const { state } = await service.startOAuth(BIGMODEL_PROVIDER_ID);
  2076. fetchMock.mockResolvedValueOnce(createBigModelZcodeTokenResponse("code-field-zcode-jwt"));
  2077. fetchMock.mockResolvedValueOnce(createBigModelUserInfoResponse());
  2078. await service.handleCallback(`zcode://oauth/callback?code=oauth-code-002&state=${state}`);
  2079. expect(fetchMock).toHaveBeenCalledTimes(2);
  2080. expect(fetchMock).toHaveBeenNthCalledWith(
  2081. 1,
  2082. "https://zcode.z.ai/api/v1/oauth/token",
  2083. expect.objectContaining({ method: "POST", headers: { "Content-Type": "application/json" } }),
  2084. );
  2085. const tokenCall = fetchMock.mock.calls[0];
  2086. if (!tokenCall) {
  2087. throw new Error("missing token call");
  2088. }
  2089. const tokenInit = tokenCall[1] as RequestInit;
  2090. expect(JSON.parse(String(tokenInit.body))).toEqual({
  2091. provider: BIGMODEL_PROVIDER_ID,
  2092. code: "oauth-code-002",
  2093. redirect_uri: PRODUCTION_DESKTOP_OAUTH_LOGIN_REDIRECT_URI,
  2094. state,
  2095. });
  2096. expect(await credentialServiceStub.load("zcodejwttoken")).toBe("code-field-zcode-jwt");
  2097. });
  2098. it("App OAuth 入口切换 active provider", async () => {
  2099. const fetchMock = vi.fn<typeof fetch>();
  2100. const service = createBigModelService({
  2101. apiClient: createMockApiClient(fetchMock),
  2102. });
  2103. await credentialServiceStub.save("oauth:active_provider", ZAI_PROVIDER_ID);
  2104. await credentialServiceStub.save(
  2105. "oauth:zai:user_info",
  2106. JSON.stringify({
  2107. id: "zai-u-keep",
  2108. username: "existing-zai-user",
  2109. displayName: "Existing ZAI User",
  2110. }),
  2111. );
  2112. const { state } = await service.startOAuth(BIGMODEL_PROVIDER_ID);
  2113. fetchMock.mockResolvedValueOnce(
  2114. createBigModelZcodeTokenResponse(
  2115. "subscription-zcode-jwt",
  2116. "subscription-business-access-token",
  2117. ),
  2118. );
  2119. fetchMock.mockResolvedValueOnce(createBigModelUserInfoResponse());
  2120. const result = await service.handleCallback(
  2121. `zcode://oauth/callback?authCode=subscription-code-001&state=${state}`,
  2122. );
  2123. expect(result).toEqual({
  2124. kind: "session",
  2125. provider: BIGMODEL_PROVIDER_ID,
  2126. userInfo: {
  2127. id: "bigmodel-u-001",
  2128. username: "BigModel User",
  2129. displayName: "BigModel User",
  2130. },
  2131. });
  2132. expect(fetchMock).toHaveBeenCalledTimes(2);
  2133. expect(await credentialServiceStub.load("oauth:bigmodel:access_token")).toBe(
  2134. "subscription-business-access-token",
  2135. );
  2136. expect(await credentialServiceStub.load("oauth:bigmodel:refresh_token")).toBeNull();
  2137. expect(await credentialServiceStub.load("zcodejwttoken")).toBe("subscription-zcode-jwt");
  2138. expect(await credentialServiceStub.load("oauth:bigmodel:user_info")).toBe(
  2139. JSON.stringify({
  2140. id: "bigmodel-u-001",
  2141. username: "BigModel User",
  2142. displayName: "BigModel User",
  2143. rawProfile: { zcodeProfileSchemaVersion: 2 },
  2144. }),
  2145. );
  2146. expect(await credentialServiceStub.load("oauth:active_provider")).toBe(BIGMODEL_PROVIDER_ID);
  2147. expect(await credentialServiceStub.load("oauth:zai:user_info")).toBeNull();
  2148. });
  2149. it("keeps single pending state and invalidates older flow", async () => {
  2150. const fetchMock = vi.fn<typeof fetch>();
  2151. const service = createBigModelService({
  2152. apiClient: createMockApiClient(fetchMock),
  2153. });
  2154. const first = await service.startOAuth(BIGMODEL_PROVIDER_ID);
  2155. const second = await service.startOAuth(BIGMODEL_PROVIDER_ID);
  2156. await expect(
  2157. service.handleCallback(`zcode://oauth/callback?authCode=first&state=${first.state}`),
  2158. ).rejects.toThrow(/state/);
  2159. fetchMock.mockResolvedValueOnce(createBigModelZcodeTokenResponse("token-2"));
  2160. fetchMock.mockResolvedValueOnce(createBigModelUserInfoResponse());
  2161. await expect(
  2162. service.handleCallback(`zcode://oauth/callback?authCode=second&state=${second.state}`),
  2163. ).resolves.toEqual({
  2164. kind: "session",
  2165. provider: BIGMODEL_PROVIDER_ID,
  2166. userInfo: {
  2167. id: "bigmodel-u-001",
  2168. username: "BigModel User",
  2169. displayName: "BigModel User",
  2170. },
  2171. });
  2172. });
  2173. it("does not infer active provider from legacy token keys", async () => {
  2174. const service = createBigModelService();
  2175. await credentialServiceStub.save("auth_token", "legacy-token");
  2176. await expect(service.getActiveProvider()).resolves.toBeNull();
  2177. await expect(credentialServiceStub.load("oauth:active_provider")).resolves.toBeNull();
  2178. });
  2179. it("clears OAuth login credentials when active provider cannot be decrypted", async () => {
  2180. const onProviderLogout = vi.fn(async () => {});
  2181. const deletedKeys: string[] = [];
  2182. const brokenCredentialService: ICredentialService = {
  2183. load: async (key: string) => {
  2184. if (key === "oauth:active_provider") {
  2185. throw createMockCredentialDecryptError();
  2186. }
  2187. return `${key}-value`;
  2188. },
  2189. save: async () => {},
  2190. delete: async (key: string) => {
  2191. deletedKeys.push(key);
  2192. },
  2193. };
  2194. const service = new OAuthService(brokenCredentialService, {
  2195. adapters: [],
  2196. onProviderLogout,
  2197. });
  2198. await expect(service.getActiveProvider()).resolves.toBeNull();
  2199. expectDeletedOAuthSessionCredentials(deletedKeys);
  2200. expectProviderLogoutNotifications(onProviderLogout, [BIGMODEL_PROVIDER_ID, ZAI_PROVIDER_ID]);
  2201. });
  2202. it("keeps corrupt OAuth recovery successful when derived provider cleanup fails", async () => {
  2203. const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
  2204. const onProviderLogout = vi.fn(async () => {
  2205. throw new Error("model provider config write failed");
  2206. });
  2207. const deletedKeys: string[] = [];
  2208. const brokenCredentialService: ICredentialService = {
  2209. load: async (key: string) => {
  2210. if (key === "oauth:active_provider") {
  2211. throw createMockCredentialDecryptError();
  2212. }
  2213. return `${key}-value`;
  2214. },
  2215. save: async () => {},
  2216. delete: async (key: string) => {
  2217. deletedKeys.push(key);
  2218. },
  2219. };
  2220. const service = new OAuthService(brokenCredentialService, {
  2221. adapters: [],
  2222. onProviderLogout,
  2223. });
  2224. await expect(service.getActiveProvider()).resolves.toBeNull();
  2225. expectDeletedOAuthSessionCredentials(deletedKeys);
  2226. expectProviderLogoutNotifications(onProviderLogout, [BIGMODEL_PROVIDER_ID, ZAI_PROVIDER_ID]);
  2227. expect(warnSpy).toHaveBeenCalled();
  2228. });
  2229. it("clears OAuth login credentials when cached user info cannot be decrypted", async () => {
  2230. const onProviderLogout = vi.fn(async () => {});
  2231. const deletedKeys: string[] = [];
  2232. const brokenCredentialService: ICredentialService = {
  2233. load: async (key: string) => {
  2234. if (key === "oauth:active_provider") {
  2235. return ZAI_PROVIDER_ID;
  2236. }
  2237. if (key === "oauth:zai:user_info") {
  2238. throw createMockCredentialDecryptError();
  2239. }
  2240. return `${key}-value`;
  2241. },
  2242. save: async () => {},
  2243. delete: async (key: string) => {
  2244. deletedKeys.push(key);
  2245. },
  2246. };
  2247. const service = new OAuthService(brokenCredentialService, {
  2248. adapters: [
  2249. {
  2250. providerId: ZAI_PROVIDER_ID,
  2251. meta: {
  2252. id: ZAI_PROVIDER_ID,
  2253. displayName: "Z.ai",
  2254. enabled: true,
  2255. order: 1,
  2256. },
  2257. redirectUri: DESKTOP_OAUTH_CALLBACK_URI,
  2258. parseCallbackParams: () => ({ code: "", state: "" }),
  2259. buildAuthorizeUrl: () => "https://example.com/auth",
  2260. exchangeToken: async () => ({ accessToken: "unused" }),
  2261. normalizeError: (error: unknown) =>
  2262. error instanceof Error ? error : new Error(String(error)),
  2263. },
  2264. ],
  2265. onProviderLogout,
  2266. });
  2267. await expect(service.restoreCachedSession()).resolves.toBeNull();
  2268. expectDeletedOAuthSessionCredentials(deletedKeys);
  2269. expectProviderLogoutNotifications(onProviderLogout, [BIGMODEL_PROVIDER_ID, ZAI_PROVIDER_ID]);
  2270. });
  2271. it("clears registered OAuth provider credentials when cached user info cannot be decrypted", async () => {
  2272. const customProviderId = "custom-oauth" as OAuthProviderId;
  2273. const onProviderLogout = vi.fn(async () => {});
  2274. const deletedKeys: string[] = [];
  2275. const brokenCredentialService: ICredentialService = {
  2276. load: async (key: string) => {
  2277. if (key === "oauth:active_provider") {
  2278. return customProviderId;
  2279. }
  2280. if (key === `oauth:${customProviderId}:user_info`) {
  2281. throw createMockCredentialDecryptError();
  2282. }
  2283. return `${key}-value`;
  2284. },
  2285. save: async () => {},
  2286. delete: async (key: string) => {
  2287. deletedKeys.push(key);
  2288. },
  2289. };
  2290. const service = new OAuthService(brokenCredentialService, {
  2291. adapters: [
  2292. {
  2293. providerId: customProviderId,
  2294. meta: {
  2295. id: customProviderId,
  2296. displayName: "Custom OAuth",
  2297. enabled: true,
  2298. order: 9,
  2299. },
  2300. redirectUri: "zcode://custom-auth/callback",
  2301. parseCallbackParams: () => ({ code: "", state: "" }),
  2302. buildAuthorizeUrl: () => "https://example.com/auth",
  2303. exchangeToken: async () => ({ accessToken: "unused" }),
  2304. normalizeError: (error: unknown) =>
  2305. error instanceof Error ? error : new Error(String(error)),
  2306. },
  2307. ],
  2308. onProviderLogout,
  2309. });
  2310. await expect(service.restoreCachedSession()).resolves.toBeNull();
  2311. expectDeletedOAuthSessionCredentials(deletedKeys, [
  2312. `oauth:${customProviderId}:access_token`,
  2313. `oauth:${customProviderId}:refresh_token`,
  2314. `oauth:${customProviderId}:user_info`,
  2315. ]);
  2316. expectProviderLogoutNotifications(onProviderLogout, [
  2317. BIGMODEL_PROVIDER_ID,
  2318. ZAI_PROVIDER_ID,
  2319. customProviderId,
  2320. ]);
  2321. });
  2322. it("refresh only reads namespaced keys and ignores legacy keys", async () => {
  2323. const refreshAdapter: OAuthProviderAdapter = {
  2324. providerId: BIGMODEL_PROVIDER_ID,
  2325. meta: {
  2326. id: BIGMODEL_PROVIDER_ID,
  2327. displayName: "BigModel",
  2328. enabled: true,
  2329. order: 0,
  2330. },
  2331. redirectUri: DESKTOP_OAUTH_CALLBACK_URI,
  2332. parseCallbackParams: () => ({ code: "", state: "" }),
  2333. buildAuthorizeUrl: () => "https://example.com/auth",
  2334. exchangeToken: async () => ({ accessToken: "unused" }),
  2335. refreshToken: async (tokenSet: OAuthTokenSet) => ({
  2336. accessToken: `${tokenSet.accessToken}-refreshed`,
  2337. refreshToken: tokenSet.refreshToken,
  2338. }),
  2339. fetchUserInfo: async (): Promise<OAuthUserProfile> => ({
  2340. id: "u-1",
  2341. username: "tester",
  2342. displayName: "Tester",
  2343. }),
  2344. normalizeError: (error: unknown) =>
  2345. error instanceof Error ? error : new Error(String(error)),
  2346. };
  2347. const service = createBigModelService({ adapters: [refreshAdapter] });
  2348. await credentialServiceStub.save("oauth:active_provider", BIGMODEL_PROVIDER_ID);
  2349. await credentialServiceStub.save("auth_token", "legacy-access");
  2350. await credentialServiceStub.save("refresh_token", "legacy-refresh");
  2351. await expect(service.refreshToken()).rejects.toThrow(/refresh_token/);
  2352. expect(await credentialServiceStub.load("oauth:bigmodel:access_token")).toBeNull();
  2353. expect(await credentialServiceStub.load("oauth:bigmodel:refresh_token")).toBeNull();
  2354. expect(await credentialServiceStub.load("auth_token")).toBe("legacy-access");
  2355. expect(await credentialServiceStub.load("refresh_token")).toBe("legacy-refresh");
  2356. });
  2357. it("restores cached session from stored user info without remote validation", async () => {
  2358. const fetchMock = vi.fn<typeof fetch>();
  2359. const service = createBigModelService({
  2360. apiClient: createMockApiClient(fetchMock),
  2361. });
  2362. const cachedUser = {
  2363. id: "u-cached-001",
  2364. username: "CachedNick",
  2365. displayName: "CachedNick",
  2366. rawProfile: { zcodeProfileSchemaVersion: 2 },
  2367. };
  2368. await credentialServiceStub.save("oauth:active_provider", BIGMODEL_PROVIDER_ID);
  2369. await credentialServiceStub.save("oauth:bigmodel:access_token", "expired-token");
  2370. await credentialServiceStub.save("oauth:bigmodel:user_info", JSON.stringify(cachedUser));
  2371. await expect(service.restoreCachedSession()).resolves.toEqual({
  2372. id: "u-cached-001",
  2373. username: "CachedNick",
  2374. displayName: "CachedNick",
  2375. });
  2376. expect(fetchMock).not.toHaveBeenCalled();
  2377. });
  2378. it("does not migrate cached bigmodel profile with newer schema version", async () => {
  2379. const fetchMock = vi.fn<typeof fetch>();
  2380. const service = createBigModelService({
  2381. apiClient: createMockApiClient(fetchMock),
  2382. });
  2383. const cachedUser = {
  2384. id: "u-cached-001",
  2385. username: "FutureName",
  2386. displayName: "FutureName",
  2387. rawProfile: { zcodeProfileSchemaVersion: 3, futureField: "keep" },
  2388. };
  2389. await credentialServiceStub.save("oauth:active_provider", BIGMODEL_PROVIDER_ID);
  2390. await credentialServiceStub.save("oauth:bigmodel:access_token", "session-access-token");
  2391. await credentialServiceStub.save("oauth:bigmodel:user_info", JSON.stringify(cachedUser));
  2392. await expect(service.restoreCachedSession()).resolves.toEqual({
  2393. id: "u-cached-001",
  2394. username: "FutureName",
  2395. displayName: "FutureName",
  2396. });
  2397. expect(fetchMock).not.toHaveBeenCalled();
  2398. expect(await credentialServiceStub.load("oauth:bigmodel:user_info")).toBe(
  2399. JSON.stringify(cachedUser),
  2400. );
  2401. });
  2402. it("refreshes legacy cached bigmodel profile once and keeps login state when refresh succeeds", async () => {
  2403. const fetchMock = vi.fn<typeof fetch>();
  2404. const service = createBigModelService({
  2405. apiClient: createMockApiClient(fetchMock),
  2406. });
  2407. const cachedUser = {
  2408. id: "bigmodel-u-001",
  2409. username: "CachedNick",
  2410. displayName: "CachedNick",
  2411. };
  2412. await credentialServiceStub.save("oauth:active_provider", BIGMODEL_PROVIDER_ID);
  2413. await credentialServiceStub.save("oauth:bigmodel:access_token", "session-access-token");
  2414. await credentialServiceStub.save("oauth:bigmodel:user_info", JSON.stringify(cachedUser));
  2415. fetchMock.mockResolvedValueOnce(
  2416. createBigModelUserInfoResponse("CachedNick", "bigmodel-u-001", "Account Center Name"),
  2417. );
  2418. await expect(service.restoreCachedSession()).resolves.toEqual(cachedUser);
  2419. await vi.waitFor(() => {
  2420. expect(fetchMock).toHaveBeenCalledWith(
  2421. BIGMODEL_OAUTH_PROVIDER_CONFIG.userinfoUrl,
  2422. expect.objectContaining({
  2423. method: "GET",
  2424. headers: {
  2425. Authorization: "session-access-token",
  2426. "Content-Type": "application/json",
  2427. },
  2428. }),
  2429. );
  2430. });
  2431. expect(await credentialServiceStub.load("oauth:active_provider")).toBe(BIGMODEL_PROVIDER_ID);
  2432. await vi.waitFor(async () => {
  2433. expect(await credentialServiceStub.load("oauth:bigmodel:user_info")).toBe(
  2434. JSON.stringify({
  2435. id: "bigmodel-u-001",
  2436. username: "Account Center Name",
  2437. displayName: "Account Center Name",
  2438. rawProfile: { zcodeProfileSchemaVersion: 2 },
  2439. }),
  2440. );
  2441. });
  2442. });
  2443. it("keeps legacy cached bigmodel profile when refresh fails", async () => {
  2444. const fetchMock = vi.fn<typeof fetch>();
  2445. const service = createBigModelService({
  2446. apiClient: createMockApiClient(fetchMock),
  2447. });
  2448. const cachedUser = {
  2449. id: "bigmodel-u-001",
  2450. username: "CachedNick",
  2451. displayName: "CachedNick",
  2452. };
  2453. await credentialServiceStub.save("oauth:active_provider", BIGMODEL_PROVIDER_ID);
  2454. await credentialServiceStub.save("oauth:bigmodel:access_token", "expired-token");
  2455. await credentialServiceStub.save("oauth:bigmodel:user_info", JSON.stringify(cachedUser));
  2456. fetchMock.mockResolvedValueOnce(
  2457. new Response(JSON.stringify({ message: "Unauthorized" }), {
  2458. status: 401,
  2459. headers: { "Content-Type": "application/json" },
  2460. }),
  2461. );
  2462. await expect(service.restoreCachedSession()).resolves.toEqual(cachedUser);
  2463. expect(await credentialServiceStub.load("oauth:active_provider")).toBe(BIGMODEL_PROVIDER_ID);
  2464. expect(await credentialServiceStub.load("oauth:bigmodel:access_token")).toBe("expired-token");
  2465. await vi.waitFor(async () => {
  2466. expect(await credentialServiceStub.load("oauth:bigmodel:user_info")).toBe(
  2467. JSON.stringify({
  2468. ...cachedUser,
  2469. rawProfile: { zcodeProfileSchemaVersion: 2 },
  2470. }),
  2471. );
  2472. });
  2473. fetchMock.mockClear();
  2474. await expect(service.restoreCachedSession()).resolves.toEqual(cachedUser);
  2475. expect(fetchMock).not.toHaveBeenCalled();
  2476. });
  2477. it("keeps legacy cached bigmodel profile when access token is polluted by zcode jwt", async () => {
  2478. const fetchMock = vi.fn<typeof fetch>();
  2479. const service = createBigModelService({
  2480. apiClient: createMockApiClient(fetchMock),
  2481. });
  2482. const cachedUser = {
  2483. id: "bigmodel-u-001",
  2484. username: "CachedNick",
  2485. displayName: "CachedNick",
  2486. };
  2487. await credentialServiceStub.save("oauth:active_provider", BIGMODEL_PROVIDER_ID);
  2488. await credentialServiceStub.save("oauth:bigmodel:access_token", "polluted-zcode-jwt");
  2489. await credentialServiceStub.save("zcodejwttoken", "polluted-zcode-jwt");
  2490. await credentialServiceStub.save("oauth:bigmodel:user_info", JSON.stringify(cachedUser));
  2491. await expect(service.restoreCachedSession()).resolves.toEqual(cachedUser);
  2492. expect(fetchMock).not.toHaveBeenCalled();
  2493. expect(await credentialServiceStub.load("oauth:active_provider")).toBe(BIGMODEL_PROVIDER_ID);
  2494. await vi.waitFor(async () => {
  2495. expect(await credentialServiceStub.load("oauth:bigmodel:user_info")).toBe(
  2496. JSON.stringify({
  2497. ...cachedUser,
  2498. rawProfile: { zcodeProfileSchemaVersion: 2 },
  2499. }),
  2500. );
  2501. });
  2502. });
  2503. it("retries legacy cached bigmodel profile after transient userinfo failure", async () => {
  2504. const fetchMock = vi.fn<typeof fetch>();
  2505. let now = 1_000;
  2506. const service = createBigModelService({
  2507. apiClient: createMockApiClient(fetchMock),
  2508. now: () => now,
  2509. });
  2510. const cachedUser = {
  2511. id: "bigmodel-u-001",
  2512. username: "CachedNick",
  2513. displayName: "CachedNick",
  2514. };
  2515. await credentialServiceStub.save("oauth:active_provider", BIGMODEL_PROVIDER_ID);
  2516. await credentialServiceStub.save("oauth:bigmodel:access_token", "session-access-token");
  2517. await credentialServiceStub.save("oauth:bigmodel:user_info", JSON.stringify(cachedUser));
  2518. fetchMock.mockResolvedValueOnce(
  2519. new Response(JSON.stringify({ message: "Server error" }), {
  2520. status: 500,
  2521. headers: { "Content-Type": "application/json" },
  2522. }),
  2523. );
  2524. await expect(service.restoreCachedSession()).resolves.toEqual(cachedUser);
  2525. let retryAfter = 0;
  2526. await vi.waitFor(async () => {
  2527. const stored = JSON.parse(
  2528. (await credentialServiceStub.load("oauth:bigmodel:user_info")) ?? "{}",
  2529. ) as OAuthUserProfile;
  2530. retryAfter =
  2531. typeof stored.rawProfile?.zcodeProfileMigrationRetryAfter === "number"
  2532. ? stored.rawProfile.zcodeProfileMigrationRetryAfter
  2533. : 0;
  2534. expect(retryAfter).toBeGreaterThan(now);
  2535. expect(stored.rawProfile?.zcodeProfileSchemaVersion).toBeUndefined();
  2536. });
  2537. fetchMock.mockClear();
  2538. await expect(service.restoreCachedSession()).resolves.toEqual(cachedUser);
  2539. expect(fetchMock).not.toHaveBeenCalled();
  2540. now = retryAfter + 1;
  2541. fetchMock.mockResolvedValueOnce(
  2542. createBigModelUserInfoResponse("CachedNick", "bigmodel-u-001", "Account Center Name"),
  2543. );
  2544. await expect(service.restoreCachedSession()).resolves.toEqual(cachedUser);
  2545. await vi.waitFor(async () => {
  2546. expect(await credentialServiceStub.load("oauth:bigmodel:user_info")).toBe(
  2547. JSON.stringify({
  2548. id: "bigmodel-u-001",
  2549. username: "Account Center Name",
  2550. displayName: "Account Center Name",
  2551. rawProfile: { zcodeProfileSchemaVersion: 2 },
  2552. }),
  2553. );
  2554. });
  2555. });
  2556. it("returns legacy cached bigmodel profile without waiting for slow refresh", async () => {
  2557. const fetchMock = vi.fn<typeof fetch>();
  2558. const service = createBigModelService({
  2559. apiClient: createMockApiClient(fetchMock),
  2560. });
  2561. const cachedUser = {
  2562. id: "bigmodel-u-001",
  2563. username: "CachedNick",
  2564. displayName: "CachedNick",
  2565. };
  2566. await credentialServiceStub.save("oauth:active_provider", BIGMODEL_PROVIDER_ID);
  2567. await credentialServiceStub.save("oauth:bigmodel:access_token", "session-access-token");
  2568. await credentialServiceStub.save("oauth:bigmodel:user_info", JSON.stringify(cachedUser));
  2569. fetchMock.mockReturnValueOnce(new Promise<Response>(() => {}));
  2570. const result = await Promise.race([
  2571. service.restoreCachedSession().then((userInfo) => ({ kind: "restored", userInfo })),
  2572. new Promise<{ kind: "timeout"; userInfo: null }>((resolve) =>
  2573. setTimeout(() => resolve({ kind: "timeout", userInfo: null }), 0),
  2574. ),
  2575. ]);
  2576. expect(result).toEqual({ kind: "restored", userInfo: cachedUser });
  2577. await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
  2578. });
  2579. it("does not overwrite zai profile when BigModel cached migration finishes after provider switch", async () => {
  2580. const fetchMock = vi.fn<typeof fetch>();
  2581. const service = createBigModelService({
  2582. apiClient: createMockApiClient(fetchMock),
  2583. });
  2584. let resolveUserInfo!: (response: Response) => void;
  2585. const cachedUser = {
  2586. id: "bigmodel-u-001",
  2587. username: "CachedNick",
  2588. displayName: "CachedNick",
  2589. };
  2590. const zaiUserInfo = {
  2591. user_id: "zai-u-001",
  2592. email: "zai@example.com",
  2593. name: "ZAI Current",
  2594. };
  2595. await credentialServiceStub.save("oauth:active_provider", BIGMODEL_PROVIDER_ID);
  2596. await credentialServiceStub.save("oauth:bigmodel:access_token", "session-access-token");
  2597. await credentialServiceStub.save("oauth:bigmodel:user_info", JSON.stringify(cachedUser));
  2598. fetchMock.mockReturnValueOnce(
  2599. new Promise<Response>((resolve) => {
  2600. resolveUserInfo = resolve;
  2601. }),
  2602. );
  2603. await expect(service.restoreCachedSession()).resolves.toEqual(cachedUser);
  2604. await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
  2605. await credentialServiceStub.delete("oauth:bigmodel:access_token");
  2606. await credentialServiceStub.delete("oauth:bigmodel:user_info");
  2607. await credentialServiceStub.save("oauth:active_provider", ZAI_PROVIDER_ID);
  2608. await credentialServiceStub.save("oauth:zai:access_token", "zai-session-token");
  2609. await credentialServiceStub.save("zcodejwttoken", "zai-zcode-jwt");
  2610. await credentialServiceStub.save("oauth:zai:user_info", JSON.stringify(zaiUserInfo));
  2611. const loadSpy = vi.spyOn(credentialServiceStub, "load");
  2612. const loadCallCountBeforeResolve = loadSpy.mock.calls.length;
  2613. resolveUserInfo(
  2614. createBigModelUserInfoResponse("CachedNick", "bigmodel-u-001", "Account Center Name"),
  2615. );
  2616. await vi.waitFor(() => {
  2617. expect(loadSpy.mock.calls.length).toBeGreaterThan(loadCallCountBeforeResolve);
  2618. });
  2619. expect(await credentialServiceStub.load("oauth:zai:user_info")).toBe(
  2620. JSON.stringify(zaiUserInfo),
  2621. );
  2622. expect(await credentialServiceStub.load("oauth:bigmodel:user_info")).toBeNull();
  2623. });
  2624. it("does not restore BigModel profile when cached migration finishes after logout", async () => {
  2625. const fetchMock = vi.fn<typeof fetch>();
  2626. const service = createBigModelService({
  2627. apiClient: createMockApiClient(fetchMock),
  2628. });
  2629. let resolveUserInfo!: (response: Response) => void;
  2630. const cachedUser = {
  2631. id: "bigmodel-u-001",
  2632. username: "CachedNick",
  2633. displayName: "CachedNick",
  2634. };
  2635. await credentialServiceStub.save("oauth:active_provider", BIGMODEL_PROVIDER_ID);
  2636. await credentialServiceStub.save("oauth:bigmodel:access_token", "session-access-token");
  2637. await credentialServiceStub.save("oauth:bigmodel:user_info", JSON.stringify(cachedUser));
  2638. fetchMock.mockReturnValueOnce(
  2639. new Promise<Response>((resolve) => {
  2640. resolveUserInfo = resolve;
  2641. }),
  2642. );
  2643. await expect(service.restoreCachedSession()).resolves.toEqual(cachedUser);
  2644. await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
  2645. await service.logout();
  2646. resolveUserInfo(
  2647. createBigModelUserInfoResponse("CachedNick", "bigmodel-u-001", "Account Center Name"),
  2648. );
  2649. await new Promise((resolve) => setTimeout(resolve, 0));
  2650. expect(await credentialServiceStub.load("oauth:active_provider")).toBeNull();
  2651. expect(await credentialServiceStub.load("oauth:bigmodel:user_info")).toBeNull();
  2652. });
  2653. it("does not send zai token to BigModel when migration token load races with provider switch", async () => {
  2654. const bigModelFetchMock = vi.fn<typeof fetch>();
  2655. const migrationService = createBigModelService({
  2656. apiClient: createMockApiClient(bigModelFetchMock),
  2657. });
  2658. let markTokenLoadStarted!: () => void;
  2659. let releaseTokenLoad!: () => void;
  2660. const tokenLoadStarted = new Promise<void>((resolve) => {
  2661. markTokenLoadStarted = resolve;
  2662. });
  2663. const tokenLoadCanFinish = new Promise<void>((resolve) => {
  2664. releaseTokenLoad = resolve;
  2665. });
  2666. const cachedUser = {
  2667. id: "bigmodel-u-001",
  2668. username: "CachedNick",
  2669. displayName: "CachedNick",
  2670. };
  2671. await credentialServiceStub.save("oauth:active_provider", BIGMODEL_PROVIDER_ID);
  2672. await credentialServiceStub.save("oauth:bigmodel:access_token", "bigmodel-session-token");
  2673. await credentialServiceStub.save("oauth:bigmodel:user_info", JSON.stringify(cachedUser));
  2674. let blockedBigModelTokenLoad = false;
  2675. let businessTokenReads = 0;
  2676. vi.spyOn(credentialServiceStub, "load").mockImplementation(async (key) => {
  2677. // 首次读取用于本地有效期检查;这里暂停第二次、属于后台资料迁移的读取。
  2678. if (
  2679. key === "oauth:bigmodel:access_token" &&
  2680. ++businessTokenReads === 2 &&
  2681. !blockedBigModelTokenLoad
  2682. ) {
  2683. blockedBigModelTokenLoad = true;
  2684. markTokenLoadStarted();
  2685. await tokenLoadCanFinish;
  2686. }
  2687. return credentialStore.get(key) ?? null;
  2688. });
  2689. await expect(migrationService.restoreCachedSession()).resolves.toEqual(cachedUser);
  2690. await tokenLoadStarted;
  2691. const zaiFetchMock = vi.fn<typeof fetch>();
  2692. const zaiService = createBigModelService({
  2693. apiClient: createMockApiClient(zaiFetchMock),
  2694. });
  2695. const { state } = await zaiService.startOAuth(ZAI_PROVIDER_ID);
  2696. zaiFetchMock.mockResolvedValueOnce(
  2697. new Response(
  2698. JSON.stringify({
  2699. code: 0,
  2700. msg: "",
  2701. data: {
  2702. token: "zai-zcode-jwt",
  2703. zai: { access_token: "zai-oauth-token" },
  2704. user: { user_id: "zai-u-001", email: "zai@example.com" },
  2705. },
  2706. }),
  2707. { status: 200, headers: { "Content-Type": "application/json" } },
  2708. ),
  2709. );
  2710. zaiFetchMock.mockResolvedValueOnce(createZaiBusinessLoginResponse("zai-business-token"));
  2711. await zaiService.handleCallback(`zcode://zai-auth/callback?code=zai-code&state=${state}`);
  2712. releaseTokenLoad();
  2713. await new Promise((resolve) => setTimeout(resolve, 0));
  2714. expect(bigModelFetchMock).not.toHaveBeenCalled();
  2715. expect(await credentialServiceStub.load("oauth:active_provider")).toBe(ZAI_PROVIDER_ID);
  2716. expect(await credentialServiceStub.load("oauth:zai:access_token")).toBe("zai-business-token");
  2717. });
  2718. it("does not leave BigModel profile when logout waits for cached migration save", async () => {
  2719. const fetchMock = vi.fn<typeof fetch>();
  2720. const service = createBigModelService({
  2721. apiClient: createMockApiClient(fetchMock),
  2722. });
  2723. let resolveUserInfo!: (response: Response) => void;
  2724. let markSaveStarted!: () => void;
  2725. let unblockSave!: () => void;
  2726. const saveStarted = new Promise<void>((resolve) => {
  2727. markSaveStarted = resolve;
  2728. });
  2729. const saveCanFinish = new Promise<void>((resolve) => {
  2730. unblockSave = resolve;
  2731. });
  2732. const cachedUser = {
  2733. id: "bigmodel-u-001",
  2734. username: "CachedNick",
  2735. displayName: "CachedNick",
  2736. };
  2737. await credentialServiceStub.save("oauth:active_provider", BIGMODEL_PROVIDER_ID);
  2738. await credentialServiceStub.save("oauth:bigmodel:access_token", "session-access-token");
  2739. await credentialServiceStub.save("oauth:bigmodel:user_info", JSON.stringify(cachedUser));
  2740. fetchMock.mockReturnValueOnce(
  2741. new Promise<Response>((resolve) => {
  2742. resolveUserInfo = resolve;
  2743. }),
  2744. );
  2745. await expect(service.restoreCachedSession()).resolves.toEqual(cachedUser);
  2746. await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
  2747. vi.spyOn(credentialServiceStub, "save").mockImplementation(async (key, value) => {
  2748. if (key === "oauth:bigmodel:user_info" && value.includes("Account Center Name")) {
  2749. markSaveStarted();
  2750. await saveCanFinish;
  2751. }
  2752. credentialStore.set(key, value);
  2753. });
  2754. resolveUserInfo(
  2755. createBigModelUserInfoResponse("CachedNick", "bigmodel-u-001", "Account Center Name"),
  2756. );
  2757. await saveStarted;
  2758. const logoutPromise = service.logout();
  2759. unblockSave();
  2760. await logoutPromise;
  2761. expect(await credentialServiceStub.load("oauth:active_provider")).toBeNull();
  2762. expect(await credentialServiceStub.load("oauth:bigmodel:user_info")).toBeNull();
  2763. });
  2764. it("restores cached zai session from raw backend user info", async () => {
  2765. const fetchMock = vi.fn<typeof fetch>();
  2766. const service = createBigModelService({
  2767. apiClient: createMockApiClient(fetchMock),
  2768. });
  2769. const pngBase64 =
  2770. "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=";
  2771. await credentialServiceStub.save("oauth:active_provider", ZAI_PROVIDER_ID);
  2772. await credentialServiceStub.save("oauth:zai:access_token", "zai-session-token");
  2773. await credentialServiceStub.save("zcodejwttoken", "zcode_backend_jwt");
  2774. await credentialServiceStub.save(
  2775. "oauth:zai:user_info",
  2776. JSON.stringify({
  2777. user_id: "zai-u-cached",
  2778. email: "13800000000@phone.local",
  2779. avatar: pngBase64,
  2780. name: "旅行者0000",
  2781. }),
  2782. );
  2783. await expect(service.restoreCachedSession()).resolves.toEqual({
  2784. id: "zai-u-cached",
  2785. username: "旅行者0000",
  2786. displayName: "旅行者0000",
  2787. avatarUrl: `data:image/png;base64,${pngBase64}`,
  2788. });
  2789. expect(fetchMock).not.toHaveBeenCalled();
  2790. });
  2791. it.each(
  2792. [BIGMODEL_PROVIDER_ID, ZAI_PROVIDER_ID].flatMap((provider) =>
  2793. ["business", "shared"].map((kind) => ({ provider, kind })),
  2794. ),
  2795. )(
  2796. "$provider 启动 $kind token 解密失败时清理 OAuth,保留独立凭据且不启动资料迁移",
  2797. async ({ provider, kind }) => {
  2798. const onProviderLogout = vi.fn(async () => {});
  2799. const fetchMock = vi.fn<typeof fetch>();
  2800. const service = createBigModelService({
  2801. onProviderLogout,
  2802. apiClient: createMockApiClient(fetchMock),
  2803. });
  2804. await credentialServiceStub.save("oauth:active_provider", provider);
  2805. await credentialServiceStub.save(`oauth:${provider}:access_token`, "corrupt-token");
  2806. await credentialServiceStub.save("zcodejwttoken", createUnsignedJwt({ exp: 9_999_999_999 }));
  2807. await credentialServiceStub.save(
  2808. `oauth:${provider}:user_info`,
  2809. JSON.stringify(
  2810. provider === ZAI_PROVIDER_ID
  2811. ? { user_id: "cached-user", name: "Fixture User" }
  2812. : { id: "cached-user", username: "Fixture User", displayName: "Fixture User" },
  2813. ),
  2814. );
  2815. await credentialServiceStub.save("bot:independent:token", "bot-token");
  2816. await credentialServiceStub.save("independent-pat", "pat-token");
  2817. const originalLoad = credentialServiceStub.load;
  2818. vi.spyOn(credentialServiceStub, "load").mockImplementation(async (key) => {
  2819. if (key === (kind === "business" ? `oauth:${provider}:access_token` : "zcodejwttoken"))
  2820. throw createMockCredentialDecryptError();
  2821. return originalLoad(key);
  2822. });
  2823. await expect(service.restoreCachedSessionState()).resolves.toEqual({ status: "signed-out" });
  2824. for (const key of OAUTH_SESSION_CREDENTIAL_KEYS) expect(credentialStore.has(key)).toBe(false);
  2825. expect(credentialStore.get("bot:independent:token")).toBe("bot-token");
  2826. expect(credentialStore.get("independent-pat")).toBe("pat-token");
  2827. expectProviderLogoutNotifications(onProviderLogout, [BIGMODEL_PROVIDER_ID, ZAI_PROVIDER_ID]);
  2828. expect(fetchMock).not.toHaveBeenCalled();
  2829. },
  2830. );
  2831. it("启动 token 读取普通 IO 错误时保留凭据并传播异常", async () => {
  2832. const onProviderLogout = vi.fn(async () => {});
  2833. const service = createBigModelService({ onProviderLogout });
  2834. await credentialServiceStub.save("oauth:active_provider", ZAI_PROVIDER_ID);
  2835. await credentialServiceStub.save("oauth:zai:access_token", "business-token");
  2836. await credentialServiceStub.save("zcodejwttoken", "backend-token");
  2837. await credentialServiceStub.save(
  2838. "oauth:zai:user_info",
  2839. JSON.stringify({ user_id: "cached-user", name: "Fixture User" }),
  2840. );
  2841. const originalLoad = credentialServiceStub.load;
  2842. const failure = new Error("credential RPC unavailable");
  2843. vi.spyOn(credentialServiceStub, "load").mockImplementation(async (key) => {
  2844. if (key === "oauth:zai:access_token") throw failure;
  2845. return originalLoad(key);
  2846. });
  2847. await expect(service.restoreCachedSessionState()).rejects.toBe(failure);
  2848. expect(credentialStore.get("oauth:active_provider")).toBe(ZAI_PROVIDER_ID);
  2849. expect(credentialStore.get("zcodejwttoken")).toBe("backend-token");
  2850. expect(onProviderLogout).not.toHaveBeenCalled();
  2851. });
  2852. it("invalidates an expired zcode JWT and requests reauthentication", async () => {
  2853. const onProviderLogout = vi.fn(async () => {
  2854. throw new Error("derived provider cleanup failed");
  2855. });
  2856. const service = createBigModelService({
  2857. now: () => 2_000_000,
  2858. onProviderLogout,
  2859. });
  2860. await credentialServiceStub.save("oauth:active_provider", ZAI_PROVIDER_ID);
  2861. await credentialServiceStub.save("oauth:zai:access_token", "zai-session-token");
  2862. await credentialServiceStub.save("zcodejwttoken", createUnsignedJwt({ exp: 1_000 }));
  2863. await credentialServiceStub.save(
  2864. "oauth:zai:user_info",
  2865. JSON.stringify({ user_id: "zai-u-cached", name: "Ada" }),
  2866. );
  2867. await expect(service.restoreCachedSessionState()).resolves.toEqual({
  2868. status: "reauthentication-required",
  2869. reason: "jwt-expired",
  2870. });
  2871. expect(await credentialServiceStub.load("oauth:active_provider")).toBeNull();
  2872. expect(await credentialServiceStub.load("oauth:zai:access_token")).toBeNull();
  2873. expect(await credentialServiceStub.load("oauth:zai:user_info")).toBeNull();
  2874. expect(await credentialServiceStub.load("zcodejwttoken")).toBeNull();
  2875. expect(onProviderLogout).toHaveBeenCalledWith(ZAI_PROVIDER_ID, "zai-u-cached");
  2876. });
  2877. it.each([BIGMODEL_PROVIDER_ID, ZAI_PROVIDER_ID])(
  2878. "%s 业务 JWT 明确过期时不恢复缓存登录,即使共享 JWT 有效",
  2879. async (provider) => {
  2880. const onProviderLogout = vi.fn(async () => {});
  2881. const service = createBigModelService({ now: () => 2_000_000, onProviderLogout });
  2882. await credentialServiceStub.save("oauth:active_provider", provider);
  2883. await credentialServiceStub.save(
  2884. `oauth:${provider}:access_token`,
  2885. createUnsignedJwt({ exp: 1000 }),
  2886. );
  2887. await credentialServiceStub.save("zcodejwttoken", createUnsignedJwt({ exp: 3000 }));
  2888. await credentialServiceStub.save(
  2889. `oauth:${provider}:user_info`,
  2890. JSON.stringify(
  2891. provider === ZAI_PROVIDER_ID
  2892. ? { user_id: "synthetic-account", name: "Fixture User" }
  2893. : { id: "synthetic-account", username: "Fixture User", displayName: "Fixture User" },
  2894. ),
  2895. );
  2896. await expect(service.restoreCachedSessionState()).resolves.toEqual({
  2897. status: "reauthentication-required",
  2898. reason: "jwt-expired",
  2899. });
  2900. expect(await credentialServiceStub.load("oauth:active_provider")).toBeNull();
  2901. expect(await credentialServiceStub.load(`oauth:${provider}:access_token`)).toBeNull();
  2902. expect(onProviderLogout).toHaveBeenCalledWith(provider, "synthetic-account");
  2903. },
  2904. );
  2905. it("does not clear a new login completed while an expired cached session is being restored", async () => {
  2906. const expiredJwt = createUnsignedJwt({ exp: 1_000 });
  2907. let releaseExpiredJwtRead = () => undefined;
  2908. let didBlockExpiredJwtRead = false;
  2909. const expiredJwtReadStarted = new Promise<void>((resolve) => {
  2910. const originalLoad = credentialServiceStub.load;
  2911. vi.spyOn(credentialServiceStub, "load").mockImplementation(async (key) => {
  2912. if (key !== "zcodejwttoken" || didBlockExpiredJwtRead) {
  2913. return originalLoad(key);
  2914. }
  2915. didBlockExpiredJwtRead = true;
  2916. const snapshot = await originalLoad(key);
  2917. resolve();
  2918. await new Promise<void>((release) => {
  2919. releaseExpiredJwtRead = release;
  2920. });
  2921. return snapshot;
  2922. });
  2923. });
  2924. const fetchMock = vi.fn<typeof fetch>();
  2925. const service = createBigModelService({
  2926. now: () => 2_000_000,
  2927. apiClient: createMockApiClient(fetchMock),
  2928. });
  2929. await credentialServiceStub.save("oauth:active_provider", BIGMODEL_PROVIDER_ID);
  2930. await credentialServiceStub.save("oauth:bigmodel:access_token", "old-token");
  2931. await credentialServiceStub.save("zcodejwttoken", expiredJwt);
  2932. await credentialServiceStub.save(
  2933. "oauth:bigmodel:user_info",
  2934. JSON.stringify({ id: "old-user", username: "Old", displayName: "Old" }),
  2935. );
  2936. const restorePromise = service.restoreCachedSessionState();
  2937. await expiredJwtReadStarted;
  2938. const { state } = await service.startOAuth(BIGMODEL_PROVIDER_ID);
  2939. fetchMock.mockResolvedValueOnce(createBigModelZcodeTokenResponse("new-zcode-jwt", "new-token"));
  2940. fetchMock.mockResolvedValueOnce(createBigModelUserInfoResponse());
  2941. await service.handleCallback(`zcode://oauth/callback?authCode=new-login&state=${state}`);
  2942. releaseExpiredJwtRead();
  2943. await expect(restorePromise).resolves.toMatchObject({ status: "authenticated" });
  2944. expect(await credentialServiceStub.load("oauth:active_provider")).toBe(BIGMODEL_PROVIDER_ID);
  2945. expect(await credentialServiceStub.load("oauth:bigmodel:access_token")).toBe("new-token");
  2946. expect(await credentialServiceStub.load("zcodejwttoken")).toBe("new-zcode-jwt");
  2947. });
  2948. it("旧启动读取的解密失败不会清理已提交的新登录", async () => {
  2949. let release!: () => void;
  2950. let started!: () => void;
  2951. const reading = new Promise<void>((resolve) => {
  2952. started = resolve;
  2953. });
  2954. const originalLoad = credentialServiceStub.load;
  2955. let first = true;
  2956. vi.spyOn(credentialServiceStub, "load").mockImplementation(async (key) => {
  2957. if (key === "oauth:bigmodel:access_token" && first) {
  2958. first = false;
  2959. started();
  2960. await new Promise<void>((resolve) => {
  2961. release = resolve;
  2962. });
  2963. throw createMockCredentialDecryptError();
  2964. }
  2965. return originalLoad(key);
  2966. });
  2967. const fetchMock = vi.fn<typeof fetch>();
  2968. const service = createBigModelService({ apiClient: createMockApiClient(fetchMock) });
  2969. await credentialServiceStub.save("oauth:active_provider", BIGMODEL_PROVIDER_ID);
  2970. await credentialServiceStub.save("oauth:bigmodel:access_token", "old-token");
  2971. await credentialServiceStub.save("zcodejwttoken", "old-jwt");
  2972. await credentialServiceStub.save(
  2973. "oauth:bigmodel:user_info",
  2974. JSON.stringify({ id: "old-user", username: "Old", displayName: "Old" }),
  2975. );
  2976. const restore = service.restoreCachedSessionState();
  2977. await reading;
  2978. const { state } = await service.startOAuth(BIGMODEL_PROVIDER_ID);
  2979. fetchMock.mockResolvedValueOnce(createBigModelZcodeTokenResponse("new-jwt", "new-token"));
  2980. fetchMock.mockResolvedValueOnce(createBigModelUserInfoResponse());
  2981. await service.handleCallback(`zcode://oauth/callback?authCode=new-login&state=${state}`);
  2982. release();
  2983. await expect(restore).resolves.toMatchObject({ status: "authenticated" });
  2984. expect(credentialStore.get("oauth:bigmodel:access_token")).toBe("new-token");
  2985. expect(credentialStore.get("zcodejwttoken")).toBe("new-jwt");
  2986. });
  2987. it("does not clear a newly selected provider while another provider restore is expiring", async () => {
  2988. const expiredJwt = createUnsignedJwt({ exp: 1_000 });
  2989. let releaseExpiredJwtRead = () => undefined;
  2990. let didBlockExpiredJwtRead = false;
  2991. const expiredJwtReadStarted = new Promise<void>((resolve) => {
  2992. const originalLoad = credentialServiceStub.load;
  2993. vi.spyOn(credentialServiceStub, "load").mockImplementation(async (key) => {
  2994. if (key !== "zcodejwttoken" || didBlockExpiredJwtRead) {
  2995. return originalLoad(key);
  2996. }
  2997. didBlockExpiredJwtRead = true;
  2998. const snapshot = await originalLoad(key);
  2999. resolve();
  3000. await new Promise<void>((release) => {
  3001. releaseExpiredJwtRead = release;
  3002. });
  3003. return snapshot;
  3004. });
  3005. });
  3006. const fetchMock = vi.fn<typeof fetch>();
  3007. const service = createBigModelService({
  3008. now: () => 2_000_000,
  3009. apiClient: createMockApiClient(fetchMock),
  3010. });
  3011. await credentialServiceStub.save("oauth:active_provider", ZAI_PROVIDER_ID);
  3012. await credentialServiceStub.save("oauth:zai:access_token", "old-zai-token");
  3013. await credentialServiceStub.save("zcodejwttoken", expiredJwt);
  3014. await credentialServiceStub.save(
  3015. "oauth:zai:user_info",
  3016. JSON.stringify({ user_id: "old-zai-user", name: "Old ZAI" }),
  3017. );
  3018. const restorePromise = service.restoreCachedSessionState();
  3019. await expiredJwtReadStarted;
  3020. const { state } = await service.startOAuth(BIGMODEL_PROVIDER_ID);
  3021. fetchMock.mockResolvedValueOnce(
  3022. createBigModelZcodeTokenResponse("new-bigmodel-jwt", "new-bigmodel-token"),
  3023. );
  3024. fetchMock.mockResolvedValueOnce(createBigModelUserInfoResponse());
  3025. await service.handleCallback(`zcode://oauth/callback?authCode=switch-login&state=${state}`);
  3026. releaseExpiredJwtRead();
  3027. await expect(restorePromise).resolves.toMatchObject({ status: "authenticated" });
  3028. expect(await credentialServiceStub.load("oauth:active_provider")).toBe(BIGMODEL_PROVIDER_ID);
  3029. expect(await credentialServiceStub.load("oauth:bigmodel:access_token")).toBe(
  3030. "new-bigmodel-token",
  3031. );
  3032. expect(await credentialServiceStub.load("zcodejwttoken")).toBe("new-bigmodel-jwt");
  3033. });
  3034. it("restores an authenticated cached session when zcode JWT is not expired", async () => {
  3035. const service = createBigModelService({ now: () => 1_000_000 });
  3036. await credentialServiceStub.save("oauth:active_provider", ZAI_PROVIDER_ID);
  3037. await credentialServiceStub.save("oauth:zai:access_token", "zai-session-token");
  3038. await credentialServiceStub.save("zcodejwttoken", createUnsignedJwt({ exp: 2_000 }));
  3039. await credentialServiceStub.save(
  3040. "oauth:zai:user_info",
  3041. JSON.stringify({ user_id: "zai-u-cached", name: "Ada" }),
  3042. );
  3043. await expect(service.restoreCachedSessionState()).resolves.toEqual({
  3044. status: "authenticated",
  3045. userInfo: {
  3046. id: "zai-u-cached",
  3047. username: "Ada",
  3048. displayName: "Ada",
  3049. },
  3050. });
  3051. });
  3052. it("invalidates an expired BigModel zcode JWT before cached profile migration", async () => {
  3053. const service = createBigModelService({ now: () => 2_000_000 });
  3054. await credentialServiceStub.save("oauth:active_provider", BIGMODEL_PROVIDER_ID);
  3055. await credentialServiceStub.save("oauth:bigmodel:access_token", "bigmodel-session-token");
  3056. await credentialServiceStub.save("zcodejwttoken", createUnsignedJwt({ exp: 1_000 }));
  3057. await credentialServiceStub.save(
  3058. "oauth:bigmodel:user_info",
  3059. JSON.stringify({ id: "bigmodel-u-cached", username: "Ada", displayName: "Ada" }),
  3060. );
  3061. await expect(service.restoreCachedSessionState()).resolves.toEqual({
  3062. status: "reauthentication-required",
  3063. reason: "jwt-expired",
  3064. });
  3065. expect(await credentialServiceStub.load("oauth:active_provider")).toBeNull();
  3066. expect(await credentialServiceStub.load("oauth:bigmodel:user_info")).toBeNull();
  3067. expect(await credentialServiceStub.load("zcodejwttoken")).toBeNull();
  3068. });
  3069. it("returns null when restoring zai session without zcodejwttoken", async () => {
  3070. const fetchMock = vi.fn<typeof fetch>();
  3071. const service = createBigModelService({
  3072. apiClient: createMockApiClient(fetchMock),
  3073. });
  3074. await credentialServiceStub.save("oauth:active_provider", ZAI_PROVIDER_ID);
  3075. await credentialServiceStub.save("oauth:zai:access_token", "zai-session-token");
  3076. await credentialServiceStub.save(
  3077. "oauth:zai:user_info",
  3078. JSON.stringify({
  3079. user_id: "zai-u-cached",
  3080. email: "13800000000@phone.local",
  3081. name: "旅行者0000",
  3082. }),
  3083. );
  3084. await expect(service.restoreCachedSession()).resolves.toBeNull();
  3085. expect(fetchMock).not.toHaveBeenCalled();
  3086. });
  3087. it("restoreCachedSession returns null when cached user info is missing", async () => {
  3088. const fetchMock = vi.fn<typeof fetch>();
  3089. const service = createBigModelService({
  3090. apiClient: createMockApiClient(fetchMock),
  3091. });
  3092. await credentialServiceStub.save("oauth:active_provider", BIGMODEL_PROVIDER_ID);
  3093. await credentialServiceStub.save("oauth:bigmodel:access_token", "session-access-token");
  3094. await expect(service.restoreCachedSession()).resolves.toBeNull();
  3095. expect(fetchMock).not.toHaveBeenCalled();
  3096. });
  3097. it("restores session by validating active provider access token", async () => {
  3098. const fetchMock = vi.fn<typeof fetch>();
  3099. const service = createBigModelService({
  3100. apiClient: createMockApiClient(fetchMock),
  3101. });
  3102. await credentialServiceStub.save("oauth:active_provider", BIGMODEL_PROVIDER_ID);
  3103. await credentialServiceStub.save("oauth:bigmodel:access_token", "session-access-token");
  3104. fetchMock.mockResolvedValueOnce(
  3105. new Response(
  3106. JSON.stringify({
  3107. data: {
  3108. customerNumber: "u-restore-001",
  3109. customerName: "Restore User",
  3110. nickName: "RestoreNick",
  3111. },
  3112. }),
  3113. { status: 200, headers: { "Content-Type": "application/json" } },
  3114. ),
  3115. );
  3116. await expect(service.restoreSession()).resolves.toEqual({
  3117. id: "u-restore-001",
  3118. username: "Restore User",
  3119. displayName: "Restore User",
  3120. });
  3121. expect(fetchMock).toHaveBeenCalledWith(
  3122. BIGMODEL_OAUTH_PROVIDER_CONFIG.userinfoUrl,
  3123. expect.objectContaining({
  3124. method: "GET",
  3125. headers: {
  3126. Authorization: "session-access-token",
  3127. "Content-Type": "application/json",
  3128. },
  3129. }),
  3130. );
  3131. });
  3132. it("restores bigmodel session from legacy auth_token and migrates to namespaced key", async () => {
  3133. const fetchMock = vi.fn<typeof fetch>();
  3134. const service = createBigModelService({
  3135. apiClient: createMockApiClient(fetchMock),
  3136. });
  3137. await credentialServiceStub.save("oauth:active_provider", BIGMODEL_PROVIDER_ID);
  3138. await credentialServiceStub.save("auth_token", "legacy-access-token");
  3139. fetchMock.mockResolvedValueOnce(
  3140. new Response(
  3141. JSON.stringify({
  3142. data: {
  3143. customerNumber: "u-legacy-001",
  3144. customerName: "Legacy User",
  3145. nickName: "LegacyNick",
  3146. },
  3147. }),
  3148. { status: 200, headers: { "Content-Type": "application/json" } },
  3149. ),
  3150. );
  3151. await expect(service.restoreSession()).resolves.toEqual({
  3152. id: "u-legacy-001",
  3153. username: "Legacy User",
  3154. displayName: "Legacy User",
  3155. });
  3156. expect(await credentialServiceStub.load("oauth:bigmodel:access_token")).toBe(
  3157. "legacy-access-token",
  3158. );
  3159. });
  3160. it("logouts active provider when startup validation reports unauthorized", async () => {
  3161. const fetchMock = vi.fn<typeof fetch>();
  3162. const service = createBigModelService({
  3163. apiClient: createMockApiClient(fetchMock),
  3164. });
  3165. await credentialServiceStub.save("oauth:active_provider", BIGMODEL_PROVIDER_ID);
  3166. await credentialServiceStub.save("oauth:bigmodel:access_token", "expired-token");
  3167. await credentialServiceStub.save("oauth:bigmodel:refresh_token", "refresh-token");
  3168. await credentialServiceStub.save(
  3169. "oauth:bigmodel:user_info",
  3170. JSON.stringify({ id: "u", username: "u", displayName: "u" }),
  3171. );
  3172. fetchMock.mockResolvedValueOnce(
  3173. new Response(JSON.stringify({ message: "Unauthorized" }), {
  3174. status: 401,
  3175. headers: { "Content-Type": "application/json" },
  3176. }),
  3177. );
  3178. await expect(service.restoreSession()).resolves.toBeNull();
  3179. expect(await credentialServiceStub.load("oauth:active_provider")).toBeNull();
  3180. expect(await credentialServiceStub.load("oauth:bigmodel:access_token")).toBeNull();
  3181. expect(await credentialServiceStub.load("oauth:bigmodel:refresh_token")).toBeNull();
  3182. expect(await credentialServiceStub.load("oauth:bigmodel:user_info")).toBeNull();
  3183. });
  3184. it("app logout clears active provider credentials", async () => {
  3185. const onProviderLogout = vi.fn(async () => {});
  3186. const service = createBigModelService({ onProviderLogout });
  3187. await credentialServiceStub.save("oauth:active_provider", ZAI_PROVIDER_ID);
  3188. await credentialServiceStub.save("oauth:zai:access_token", "token");
  3189. await credentialServiceStub.save("oauth:zai:refresh_token", "refresh");
  3190. await credentialServiceStub.save(
  3191. "oauth:zai:user_info",
  3192. JSON.stringify({ user_id: "account-a", name: "Ada" }),
  3193. );
  3194. await credentialServiceStub.save("zcodejwttoken", "zai-jwt");
  3195. await credentialServiceStub.save(
  3196. "oauth:login_attribution",
  3197. JSON.stringify({ channel_id: "google_ads" }),
  3198. );
  3199. await service.logout();
  3200. expect(await credentialServiceStub.load("oauth:active_provider")).toBeNull();
  3201. expect(await credentialServiceStub.load("oauth:zai:access_token")).toBeNull();
  3202. expect(await credentialServiceStub.load("oauth:zai:refresh_token")).toBeNull();
  3203. expect(await credentialServiceStub.load("oauth:zai:user_info")).toBeNull();
  3204. expect(await credentialServiceStub.load("zcodejwttoken")).toBeNull();
  3205. expect(await credentialServiceStub.load("oauth:login_attribution")).toBe(
  3206. JSON.stringify({ channel_id: "google_ads" }),
  3207. );
  3208. expect(onProviderLogout).toHaveBeenCalledWith(ZAI_PROVIDER_ID, "account-a");
  3209. });
  3210. it("provider unlink logs out the matching active provider", async () => {
  3211. const onProviderLogout = vi.fn(async () => {});
  3212. const service = createBigModelService({ onProviderLogout });
  3213. await credentialServiceStub.save("oauth:active_provider", BIGMODEL_PROVIDER_ID);
  3214. await credentialServiceStub.save("oauth:bigmodel:access_token", "token");
  3215. await credentialServiceStub.save("oauth:bigmodel:refresh_token", "refresh");
  3216. await credentialServiceStub.save(
  3217. "oauth:bigmodel:user_info",
  3218. JSON.stringify({ id: "account-b", username: "Ada", displayName: "Ada" }),
  3219. );
  3220. await credentialServiceStub.save("zcodejwttoken", "bigmodel-jwt");
  3221. await service.logout(BIGMODEL_PROVIDER_ID);
  3222. expect(await credentialServiceStub.load("oauth:active_provider")).toBeNull();
  3223. expect(await credentialServiceStub.load("oauth:bigmodel:access_token")).toBeNull();
  3224. expect(await credentialServiceStub.load("oauth:bigmodel:refresh_token")).toBeNull();
  3225. expect(await credentialServiceStub.load("oauth:bigmodel:user_info")).toBeNull();
  3226. expect(await credentialServiceStub.load("zcodejwttoken")).toBeNull();
  3227. expect(onProviderLogout).toHaveBeenCalledWith(BIGMODEL_PROVIDER_ID, "account-b");
  3228. });
  3229. it("provider unlink does not clear non-active provider credentials", async () => {
  3230. const onProviderLogout = vi.fn(async () => {});
  3231. const service = createBigModelService({ onProviderLogout });
  3232. await credentialServiceStub.save("oauth:active_provider", ZAI_PROVIDER_ID);
  3233. await credentialServiceStub.save("oauth:zai:access_token", "zai-token");
  3234. await credentialServiceStub.save("oauth:bigmodel:access_token", "bigmodel-token");
  3235. await service.logout(BIGMODEL_PROVIDER_ID);
  3236. expect(await credentialServiceStub.load("oauth:active_provider")).toBe(ZAI_PROVIDER_ID);
  3237. expect(await credentialServiceStub.load("oauth:zai:access_token")).toBe("zai-token");
  3238. expect(await credentialServiceStub.load("oauth:bigmodel:access_token")).toBe("bigmodel-token");
  3239. expect(onProviderLogout).not.toHaveBeenCalled();
  3240. });
  3241. it("throws clear error when provider does not support refresh", async () => {
  3242. const service = createBigModelService();
  3243. await credentialServiceStub.save("oauth:active_provider", BIGMODEL_PROVIDER_ID);
  3244. await expect(service.refreshToken()).rejects.toThrow(/请重新登录/);
  3245. });
  3246. it("bigmodel zcode token 非 2xx 时会抛出统一的 ApiError", async () => {
  3247. const fetchMock = vi.fn<typeof fetch>();
  3248. const service = createBigModelService({
  3249. apiClient: createMockApiClient(fetchMock),
  3250. });
  3251. const { state } = await service.startOAuth(BIGMODEL_PROVIDER_ID);
  3252. fetchMock.mockResolvedValueOnce(
  3253. new Response(JSON.stringify({ message: "Unauthorized" }), {
  3254. status: 401,
  3255. headers: { "Content-Type": "application/json" },
  3256. }),
  3257. );
  3258. await expect(
  3259. service.handleCallback(`zcode://oauth/callback?authCode=auth-code-401&state=${state}`),
  3260. ).rejects.toMatchObject<ApiError>({
  3261. name: "ApiError",
  3262. method: "POST",
  3263. status: 401,
  3264. url: "https://zcode.z.ai/api/v1/oauth/token",
  3265. message: "Unauthorized",
  3266. });
  3267. });
  3268. it("zai userinfo 非法 JSON 时会向上抛出统一的 ApiError", async () => {
  3269. const fetchMock = vi.fn<typeof fetch>();
  3270. const service = createBigModelService({
  3271. apiClient: createMockApiClient(fetchMock),
  3272. });
  3273. await credentialServiceStub.save("oauth:active_provider", ZAI_PROVIDER_ID);
  3274. await credentialServiceStub.save("oauth:zai:access_token", "zai-session-token");
  3275. fetchMock.mockResolvedValueOnce(
  3276. new Response("not-json", {
  3277. status: 200,
  3278. headers: { "Content-Type": "application/json" },
  3279. }),
  3280. );
  3281. await expect(service.restoreSession()).rejects.toMatchObject<ApiError>({
  3282. name: "ApiError",
  3283. method: "GET",
  3284. status: 200,
  3285. url: ZAI_OAUTH_PROVIDER_CONFIG.userinfoUrl,
  3286. });
  3287. });
  3288. });