oauthSessionEvents.test.ts 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. import { afterEach, expect, it, vi } from "vitest";
  2. import { ProxyChannel } from "@zcode/rpc";
  3. import { BIGMODEL_PROVIDER_ID, ZAI_PROVIDER_ID, type OAuthTokenSet } from "@zcode/shared";
  4. import type { IOAuthService } from "#src/oauth/oauth.js";
  5. import { OAuthService } from "#src/oauth/oauthService.js";
  6. const services: OAuthService[] = [];
  7. afterEach(async () => {
  8. await Promise.all(services.splice(0).map((service) => service.cancelPending()));
  9. });
  10. function fixture(onProviderLogout = vi.fn(async () => {})) {
  11. const credentials = new Map<string, string>();
  12. const credentialService = {
  13. load: async (key: string) => credentials.get(key) ?? null,
  14. save: async (key: string, value: string) => {
  15. credentials.set(key, value);
  16. },
  17. delete: async (key: string) => {
  18. credentials.delete(key);
  19. },
  20. };
  21. const exchangeToken = vi.fn(
  22. async (): Promise<OAuthTokenSet> => ({
  23. accessToken: "access",
  24. zcodeJwtToken: "jwt",
  25. }),
  26. );
  27. const service = new OAuthService(credentialService, {
  28. onProviderLogout,
  29. adapters: [
  30. {
  31. providerId: ZAI_PROVIDER_ID,
  32. apiClient: { request: vi.fn<typeof fetch>() },
  33. meta: { id: ZAI_PROVIDER_ID, displayName: "Z.ai", enabled: true, order: 1 },
  34. redirectUri: "zcode://oauth/callback",
  35. buildAuthorizeUrl: ({ state }) => `https://example.com/authorize?state=${state}`,
  36. parseCallbackParams: (url) => ({
  37. state: new URL(url).searchParams.get("state") ?? "",
  38. code: new URL(url).searchParams.get("code") ?? "",
  39. }),
  40. exchangeToken,
  41. fetchUserInfo: async () => ({ id: "user", username: "User", displayName: "User" }),
  42. normalizeError: (error) => (error instanceof Error ? error : new Error(String(error))),
  43. },
  44. ],
  45. });
  46. services.push(service);
  47. const server = ProxyChannel.fromService(service);
  48. const client = ProxyChannel.toService<IOAuthService>({
  49. call: (command, args) => server.call(undefined, command, args),
  50. listen: (event, args) => server.listen(undefined, event, args),
  51. });
  52. async function login() {
  53. const { state } = await client.startOAuth(ZAI_PROVIDER_ID);
  54. return client.handleCallback(`zcode://oauth/callback?state=${state}&code=code`);
  55. }
  56. return { service, client, credentials, credentialService, exchangeToken, login };
  57. }
  58. it("同账号每次凭据落盘均经 RPC 发布完成事件,先于调用结果及 UI 后处理", async () => {
  59. const f = fixture();
  60. const changes: string[] = [];
  61. const subscription = f.client.onDidChangeSession((state) => {
  62. expect(f.credentials.get("zcodejwttoken")).toBe("jwt");
  63. expect(f.credentials.get("oauth:active_provider")).toBe(ZAI_PROVIDER_ID);
  64. changes.push(state);
  65. });
  66. await f.login();
  67. await f.login();
  68. expect(changes).toEqual(["signed-in", "signed-in"]);
  69. subscription.dispose();
  70. });
  71. it.each(["active", "provider", "all"] as const)(
  72. "%s 登出清凭据后立即通知,即使派生 provider 清理失败",
  73. async (mode) => {
  74. const onProviderLogout = vi.fn(async () => {
  75. throw new Error("derived settings failed");
  76. });
  77. const f = fixture(onProviderLogout);
  78. await f.login();
  79. const changes: string[] = [];
  80. const subscription = f.client.onDidChangeSession((state) => {
  81. expect(f.credentials.has("zcodejwttoken")).toBe(false);
  82. expect(onProviderLogout).not.toHaveBeenCalled();
  83. changes.push(state);
  84. });
  85. const logout =
  86. mode === "all"
  87. ? f.client.logoutAll()
  88. : f.client.logout(mode === "provider" ? ZAI_PROVIDER_ID : undefined);
  89. await expect(logout).rejects.toThrow("derived settings failed");
  90. expect(changes).toEqual(["signed-out"]);
  91. subscription.dispose();
  92. },
  93. );
  94. it("取消中的登录和非当前 provider 的 unlink 不发布会话变更", async () => {
  95. const f = fixture();
  96. const changed = vi.fn();
  97. const subscription = f.client.onDidChangeSession(changed);
  98. const exchange = Promise.withResolvers<OAuthTokenSet>();
  99. f.exchangeToken.mockReturnValue(exchange.promise);
  100. const login = f.login();
  101. await vi.waitFor(() => expect(f.exchangeToken).toHaveBeenCalled());
  102. await f.client.cancelPending();
  103. exchange.resolve({ accessToken: "cancelled", zcodeJwtToken: "cancelled" });
  104. await login;
  105. await f.client.logout(BIGMODEL_PROVIDER_ID);
  106. expect(changed).not.toHaveBeenCalled();
  107. subscription.dispose();
  108. });
  109. it("active provider 落盘期间取消并回滚的登录不发布 signed-in", async () => {
  110. const f = fixture();
  111. const saving = Promise.withResolvers<void>();
  112. const continueSave = Promise.withResolvers<void>();
  113. const save = f.credentialService.save;
  114. vi.spyOn(f.credentialService, "save").mockImplementation(async (key, value) => {
  115. await save(key, value);
  116. if (key === "oauth:active_provider") {
  117. saving.resolve();
  118. await continueSave.promise;
  119. }
  120. });
  121. const changed = vi.fn();
  122. const subscription = f.client.onDidChangeSession(changed);
  123. const login = f.login();
  124. const rejected = expect(login).rejects.toThrow("OAuth flow 已取消");
  125. await saving.promise;
  126. await f.client.cancelPending();
  127. continueSave.resolve();
  128. await rejected;
  129. expect(f.credentials.has("zcodejwttoken")).toBe(false);
  130. expect(changed).not.toHaveBeenCalled();
  131. subscription.dispose();
  132. });