auth-storage-fetch.test.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { describe, expect, it, vi } from "vitest";
  2. import { AuthStorage } from "../src/core/auth-storage.ts";
  3. function jsonResponse(body: unknown, status: number = 200): Response {
  4. return new Response(JSON.stringify(body), {
  5. status,
  6. headers: { "Content-Type": "application/json" },
  7. });
  8. }
  9. function createOpenAICodexAccessToken(accountId: string): string {
  10. const header = Buffer.from(JSON.stringify({ alg: "none" })).toString("base64");
  11. const payload = Buffer.from(
  12. JSON.stringify({
  13. "https://api.openai.com/auth": {
  14. chatgpt_account_id: accountId,
  15. },
  16. }),
  17. ).toString("base64");
  18. return `${header}.${payload}.signature`;
  19. }
  20. describe("AuthStorage fetch injection", () => {
  21. it("refreshes expired OAuth credentials through the injected fetch implementation", async () => {
  22. const accessToken = createOpenAICodexAccessToken("account-auth-storage");
  23. const authStorage = AuthStorage.inMemory({
  24. "openai-codex": {
  25. type: "oauth",
  26. access: "expired-access-token",
  27. refresh: "refresh-token",
  28. expires: 0,
  29. },
  30. });
  31. const injectedFetch = vi.fn(async (_input: string | URL | Request, init?: RequestInit) => {
  32. const params = new URLSearchParams(String(init?.body));
  33. expect(params.get("grant_type")).toBe("refresh_token");
  34. expect(params.get("refresh_token")).toBe("refresh-token");
  35. return jsonResponse({
  36. access_token: accessToken,
  37. refresh_token: "next-refresh-token",
  38. expires_in: 3600,
  39. });
  40. });
  41. const globalFetch = vi.spyOn(globalThis, "fetch").mockImplementation(async () => {
  42. throw new Error("global fetch should not be used");
  43. });
  44. await expect(
  45. authStorage.getApiKey("openai-codex", {
  46. includeFallback: false,
  47. fetch: injectedFetch as unknown as typeof fetch,
  48. }),
  49. ).resolves.toBe(accessToken);
  50. expect(injectedFetch).toHaveBeenCalledTimes(1);
  51. expect(globalFetch).not.toHaveBeenCalled();
  52. globalFetch.mockRestore();
  53. });
  54. });