local-auth.ts 3.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import { mkdtemp, rm } from 'node:fs/promises';
  2. import { tmpdir } from 'node:os';
  3. import { join } from 'node:path';
  4. import { MCodeOAuthCore } from '../../src/auth-core.js';
  5. import { FileStore } from '../../src/credential-store/file-store.js';
  6. import { createAuthNamespace } from '../../src/namespace.js';
  7. import { HttpOAuthClient } from '../../src/oauth-client.js';
  8. import { createAuthManager } from '../../src/token-provider.js';
  9. /** Real Core, file store and lock; only Account HTTP responses are simulated. */
  10. export async function createLocalAuthFixture(options: {
  11. beforeDeviceTokenResponse?: () => Promise<void>;
  12. } = {}) {
  13. const dataDir = await mkdtemp(join(tmpdir(), 'mcode-auth-recovery-'));
  14. const namespace = createAuthNamespace({ dataDir, buildEnv: 'test', region: 'cn' });
  15. let now = 1_800_000_000_000;
  16. let serial = 0;
  17. let refreshFailure:
  18. | 'offline'
  19. | 'unavailable'
  20. | 'invalid_grant'
  21. | 'invalid_client'
  22. | 'unauthorized_client'
  23. | 'invalid_grant_503'
  24. | undefined;
  25. const calls = { device: 0, refresh: 0 };
  26. const createCore = () =>
  27. new MCodeOAuthCore({
  28. namespace,
  29. credentialStore: new FileStore({ authHome: namespace.namespaceHome }),
  30. now: () => now,
  31. oauthClient: new HttpOAuthClient({
  32. deviceAuthorizationEndpoint: 'https://account.example.test/device',
  33. tokenEndpoint: 'https://account.example.test/token',
  34. revocationEndpoint: 'https://account.example.test/revoke',
  35. now: () => now,
  36. fetchImpl: async (url, init) => {
  37. if (String(url).endsWith('/device')) {
  38. calls.device += 1;
  39. return Response.json({
  40. user_code: 'TEST-CODE',
  41. verification_uri: 'https://account.example.test/verify',
  42. expired_in: now + 300_000,
  43. interval: 5_000,
  44. });
  45. }
  46. if (String(url).endsWith('/revoke')) return new Response(null, { status: 200 });
  47. if ((init?.body as URLSearchParams).get('grant_type') === 'refresh_token') {
  48. calls.refresh += 1;
  49. if (refreshFailure === 'offline') throw new TypeError('fetch failed');
  50. if (refreshFailure) {
  51. return Response.json(
  52. {
  53. error:
  54. refreshFailure === 'unavailable'
  55. ? 'temporarily_unavailable'
  56. : refreshFailure === 'invalid_grant_503'
  57. ? 'invalid_grant'
  58. : refreshFailure,
  59. },
  60. {
  61. status:
  62. refreshFailure === 'unavailable' || refreshFailure === 'invalid_grant_503'
  63. ? 503
  64. : 400,
  65. },
  66. );
  67. }
  68. } else {
  69. await options.beforeDeviceTokenResponse?.();
  70. }
  71. serial += 1;
  72. return Response.json({
  73. access_token: `test-access-${serial}`,
  74. refresh_token: `test-refresh-${serial}`,
  75. token_type: 'Bearer',
  76. scope: 'agent.default',
  77. expires_in: 3_600,
  78. });
  79. },
  80. }),
  81. });
  82. return {
  83. dataDir,
  84. namespace,
  85. calls,
  86. createCore,
  87. createManager: () => createAuthManager(createCore()),
  88. setRefreshFailure: (failure: typeof refreshFailure) => {
  89. refreshFailure = failure;
  90. },
  91. advanceTime: (ms: number) => {
  92. now += ms;
  93. },
  94. cleanup: () => rm(dataDir, { recursive: true, force: true }),
  95. };
  96. }