zai-business-token-refresh-fixture.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { vi } from "vitest";
  2. import { type HttpClientPort } from "@zcode/contracts";
  3. import { createCodingPlanApiKeyResolver } from "../src/auth/coding-plan-api-key.js";
  4. export function fixture(
  5. options: { jwtTtl?: number; expiresIn?: number; failures?: number[] } = {},
  6. ) {
  7. let logins = 0;
  8. let issues = 0;
  9. const failures = [...(options.failures ?? [])];
  10. const request = vi.fn(async (req: { url: string }) => {
  11. let body: unknown;
  12. let status = 200;
  13. if (req.url.endsWith("/api/auth/z/login")) {
  14. logins++;
  15. const claims = { exp: Date.now() / 1000 + (options.jwtTtl ?? 600), sub: String(logins) };
  16. const token = `header.${Buffer.from(JSON.stringify(claims)).toString("base64url")}.signature`;
  17. body = {
  18. code: 200,
  19. data: {
  20. access_token: token,
  21. ...(options.expiresIn === undefined ? {} : { expires_in: options.expiresIn }),
  22. },
  23. };
  24. } else if (req.url.endsWith("/getCustomerInfo")) {
  25. body = {
  26. code: 200,
  27. data: {
  28. organizations: [
  29. {
  30. organizationId: "org",
  31. organizationName: "默认机构",
  32. projects: [{ projectId: "project", projectName: "默认项目" }],
  33. },
  34. ],
  35. },
  36. };
  37. } else if (req.url.endsWith("/api_keys")) {
  38. body = { code: 200, data: [{ apiKey: "key", name: "zcode-api-key" }] };
  39. } else {
  40. issues++;
  41. status = failures.shift() ?? 200;
  42. body = {
  43. code: status,
  44. data: {
  45. accessToken: `pat-${issues}`,
  46. tokenType: "Bearer",
  47. expiresIn: 1,
  48. expiresAt: Date.now() / 1000 + 1,
  49. },
  50. };
  51. }
  52. return { status, body: new TextEncoder().encode(JSON.stringify(body)) };
  53. });
  54. const resolver = createCodingPlanApiKeyResolver({
  55. httpClient: { request } as unknown as HttpClientPort,
  56. });
  57. const input = { family: "zai", accessToken: "oauth", accountIdentity: "user" } as const;
  58. return {
  59. resolve: () => resolver.resolve(input),
  60. clear: () => resolver.clear(),
  61. logins: () => logins,
  62. issues: () => issues,
  63. request,
  64. };
  65. }