oauthService.test.ts 125 KB

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