auth-application.test.ts 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. import { describe, expect, it, vi } from 'vitest';
  2. import type { LogoutResult } from '@mavis/oauth-core';
  3. import { createLocalAuthFixture } from '../../../oauth-core/test/helpers/local-auth.js';
  4. import type { McodeBusinessEvent } from '../../src/analytics/business-telemetry.js';
  5. import { McodeAuthApplication } from '../../src/auth/application.js';
  6. function sharedCore(status: 'anonymous' | 'authenticated' | 'logout_pending' = 'anonymous') {
  7. return {
  8. getStatus: vi.fn(async () => ({
  9. status,
  10. generation: status === 'authenticated' ? 1 : 0,
  11. scopes: status === 'authenticated' ? ['agent.default'] : [],
  12. })),
  13. // Mirrors the real core: an authenticated session only refreshes, while
  14. // any other state starts a Device Flow and fires the prompt callback.
  15. login: vi.fn(async ({ onDeviceAuthorization } = {}) => {
  16. if (status !== 'authenticated') {
  17. onDeviceAuthorization?.({
  18. userCode: 'ABCD-EFGH',
  19. verificationUri: 'https://account.example.test/device',
  20. expiresInSec: 300,
  21. });
  22. }
  23. return { status: 'authenticated' as const, generation: 1 };
  24. }),
  25. logout: vi.fn(async (): Promise<LogoutResult> => ({ status: 'anonymous', generation: 2 })),
  26. };
  27. }
  28. describe('McodeAuthApplication', () => {
  29. it('uses Shared OAuth Device Flow as its only login path', async () => {
  30. const core = sharedCore();
  31. const onProgress = vi.fn();
  32. const application = new McodeAuthApplication({
  33. dataDir: '/data',
  34. region: 'cn',
  35. buildEnv: 'test',
  36. sharedAuthCore: core,
  37. });
  38. await expect(application.login(onProgress)).resolves.toEqual({
  39. state: 'authenticated',
  40. message: 'Signed in with MiniMax.',
  41. });
  42. expect(core.login).toHaveBeenCalledOnce();
  43. expect(onProgress).toHaveBeenCalledWith({
  44. state: 'device-authorization',
  45. userCode: 'ABCD-EFGH',
  46. verificationUri: 'https://account.example.test/device',
  47. expiresInSec: 300,
  48. });
  49. });
  50. it('lets Core reuse an authenticated session without forcing a refresh', async () => {
  51. const core = sharedCore('authenticated');
  52. const application = new McodeAuthApplication({ dataDir: '/data', sharedAuthCore: core });
  53. await expect(application.login()).resolves.toEqual({
  54. state: 'already-authenticated',
  55. message: 'Already signed in with MiniMax.',
  56. });
  57. expect(core.login).toHaveBeenCalledOnce();
  58. expect(core.login).toHaveBeenCalledWith({ onDeviceAuthorization: expect.any(Function) });
  59. });
  60. it.each(['offline', 'unavailable'] as const)(
  61. 'reuses a healthy session without contacting Account when it is %s',
  62. async (failure) => {
  63. const fixture = await createLocalAuthFixture();
  64. try {
  65. const core = fixture.createManager();
  66. const application = new McodeAuthApplication({
  67. dataDir: fixture.dataDir, sharedAuthCore: core, region: 'cn', buildEnv: 'test',
  68. });
  69. await application.login();
  70. const lease = await core.getAccessToken({ minValidityMs: 30_000 });
  71. fixture.setRefreshFailure(failure);
  72. await expect(application.login()).resolves.toMatchObject({ state: 'already-authenticated' });
  73. await expect(core.getAccessToken({ minValidityMs: 30_000 })).resolves.toEqual(lease);
  74. expect(fixture.calls).toEqual({ device: 1, refresh: 0 });
  75. } finally {
  76. await fixture.cleanup();
  77. }
  78. },
  79. );
  80. it('logs in to another region without replacing the authenticated current region', async () => {
  81. const chinaCore = sharedCore('authenticated');
  82. const globalCore = sharedCore();
  83. const resolveSharedAuthCore = vi.fn(() => globalCore);
  84. const application = new McodeAuthApplication({
  85. dataDir: '/data',
  86. region: 'cn',
  87. buildEnv: 'test',
  88. sharedAuthCore: chinaCore,
  89. resolveSharedAuthCore,
  90. });
  91. await expect(application.login(undefined, 'en')).resolves.toEqual({
  92. state: 'authenticated',
  93. message: 'Signed in with MiniMax Global.',
  94. restartRequired: true,
  95. });
  96. expect(resolveSharedAuthCore).toHaveBeenCalledWith('en');
  97. expect(chinaCore.login).not.toHaveBeenCalled();
  98. expect(globalCore.login).toHaveBeenCalledOnce();
  99. });
  100. it('persists only the non-sensitive selected region after login succeeds', async () => {
  101. const core = sharedCore();
  102. const writeRegionPreference = vi.fn();
  103. const application = new McodeAuthApplication({
  104. dataDir: '/data',
  105. region: 'cn',
  106. buildEnv: 'test',
  107. sharedAuthCore: core,
  108. writeRegionPreference,
  109. });
  110. await application.login(undefined, 'cn');
  111. expect(writeRegionPreference).toHaveBeenCalledWith('/data', {
  112. region: 'cn',
  113. buildEnv: 'test',
  114. });
  115. });
  116. it('reuses an authenticated selected region without starting Device Flow', async () => {
  117. const chinaCore = sharedCore();
  118. const globalCore = sharedCore('authenticated');
  119. const resolveSharedAuthCore = vi.fn(() => globalCore);
  120. const application = new McodeAuthApplication({
  121. dataDir: '/data',
  122. region: 'cn',
  123. buildEnv: 'test',
  124. sharedAuthCore: chinaCore,
  125. resolveSharedAuthCore,
  126. });
  127. await expect(application.login(undefined, 'en')).resolves.toEqual({
  128. state: 'already-authenticated',
  129. message: 'Already signed in with MiniMax Global.',
  130. restartRequired: true,
  131. });
  132. expect(resolveSharedAuthCore).toHaveBeenCalledWith('en');
  133. expect(chinaCore.login).not.toHaveBeenCalled();
  134. expect(globalCore.login).toHaveBeenCalledOnce();
  135. expect(globalCore.login).toHaveBeenCalledWith({ onDeviceAuthorization: expect.any(Function) });
  136. });
  137. it.each([
  138. ['cn', 'dev', 'https://matrix-test.example.invalid'],
  139. ['cn', 'test', 'https://matrix-test.example.invalid'],
  140. ['cn', 'staging', 'https://matrix-pre.example.invalid'],
  141. ['cn', 'prod', 'https://agent.minimax.cn'],
  142. ['en', 'dev', 'https://matrix-overseas-test.example.invalid'],
  143. ['en', 'test', 'https://matrix-overseas-test.example.invalid'],
  144. ['en', 'staging', 'https://matrix-overseas-pre.example.invalid'],
  145. ['en', 'prod', 'https://agent.minimax.io'],
  146. ] as const)(
  147. 'logs out %s/%s with the matching browser logout page',
  148. async (region, buildEnv, origin) => {
  149. const core = sharedCore('authenticated');
  150. const application = new McodeAuthApplication({
  151. dataDir: '/data',
  152. region,
  153. buildEnv,
  154. sharedAuthCore: core,
  155. });
  156. await expect(application.logout()).resolves.toEqual({
  157. state: 'signed-out',
  158. message: `Signed out of MiniMax ${region === 'cn' ? 'China' : 'Global'} on Desktop, CLI/TUI, and embedded mcode-tools.`,
  159. logoutUrl: `${origin}/auth/logout?logout_redirect_uri=${encodeURIComponent(origin)}`,
  160. });
  161. expect(core.logout).toHaveBeenCalledWith({ revoke: true });
  162. },
  163. );
  164. it('treats logout of an already anonymous shared domain as a safe no-op', async () => {
  165. const core = sharedCore();
  166. const application = new McodeAuthApplication({
  167. dataDir: '/data',
  168. sharedAuthCore: core,
  169. region: 'cn',
  170. buildEnv: 'prod',
  171. });
  172. await expect(application.logout()).resolves.toEqual({
  173. state: 'already-signed-out',
  174. message: 'Already signed out of MiniMax.',
  175. logoutUrl:
  176. 'https://agent.minimax.cn/auth/logout?logout_redirect_uri=https%3A%2F%2Fagent.minimax.cn',
  177. });
  178. expect(core.logout).toHaveBeenCalledWith({ revoke: true });
  179. });
  180. it('provides browser logout while server revocation is pending', async () => {
  181. const core = sharedCore('authenticated');
  182. core.logout.mockResolvedValue({ status: 'logout_pending', generation: 2 });
  183. const application = new McodeAuthApplication({
  184. dataDir: '/data',
  185. sharedAuthCore: core,
  186. region: 'en',
  187. buildEnv: 'prod',
  188. });
  189. await expect(application.logout()).resolves.toMatchObject({
  190. state: 'signed-out',
  191. message: expect.stringContaining('Server revocation is pending'),
  192. logoutUrl:
  193. 'https://agent.minimax.io/auth/logout?logout_redirect_uri=https%3A%2F%2Fagent.minimax.io',
  194. });
  195. });
  196. it('reports OAuth telemetry and preserves login failures', async () => {
  197. const events: McodeBusinessEvent[] = [];
  198. const core = sharedCore();
  199. core.login.mockRejectedValueOnce(new Error('OAuth authorization failed.'));
  200. const application = new McodeAuthApplication({
  201. dataDir: '/data',
  202. sharedAuthCore: core,
  203. telemetry: {
  204. track: (event, properties) => events.push({ event, properties } as McodeBusinessEvent),
  205. flush: async () => undefined,
  206. },
  207. telemetrySource: 'mcode_tui',
  208. });
  209. await expect(application.login()).rejects.toThrow('OAuth authorization failed.');
  210. expect(events.at(-1)).toEqual({
  211. event: 'login_result',
  212. properties: {
  213. source: 'mcode_tui',
  214. result_type: '2',
  215. fail_reason: '5',
  216. login_type: 'minimax_oauth',
  217. },
  218. });
  219. });
  220. });