|
| 1 | +import { mkdtempSync, rmSync } from "node:fs"; |
| 2 | +import { tmpdir } from "node:os"; |
| 3 | +import { join } from "node:path"; |
| 4 | +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; |
| 5 | +import { type Credentials, CredentialsStore } from "./credentials.js"; |
| 6 | +import type { OAuthConfig } from "./flow.js"; |
| 7 | +import { TokenManager } from "./token-manager.js"; |
| 8 | + |
| 9 | +const OAUTH: OAuthConfig = { |
| 10 | + authorizationUrl: "https://example.test/login", |
| 11 | + tokenUrl: "https://example.test/token", |
| 12 | + refreshUrl: "https://example.test/refresh", |
| 13 | + revokeUrl: "https://example.test/revoke", |
| 14 | + clientId: "test-client", |
| 15 | + scopes: ["read", "write"], |
| 16 | +}; |
| 17 | + |
| 18 | +function freshCreds(overrides: Partial<Credentials> = {}): Omit<Credentials, "version"> { |
| 19 | + return { |
| 20 | + accessToken: "access-current", |
| 21 | + refreshToken: "refresh-current", |
| 22 | + expiresAt: Date.now() + 60 * 60 * 1000, |
| 23 | + scopes: ["read", "write"], |
| 24 | + source: "codebase", |
| 25 | + userId: "u-1", |
| 26 | + email: "u@example.test", |
| 27 | + ...overrides, |
| 28 | + }; |
| 29 | +} |
| 30 | + |
| 31 | +describe("TokenManager", () => { |
| 32 | + let dataRoot: string; |
| 33 | + let store: CredentialsStore; |
| 34 | + |
| 35 | + beforeEach(() => { |
| 36 | + dataRoot = mkdtempSync(join(tmpdir(), "tm-test-")); |
| 37 | + store = new CredentialsStore({ dataRoot }); |
| 38 | + }); |
| 39 | + |
| 40 | + afterEach(() => { |
| 41 | + rmSync(dataRoot, { recursive: true, force: true }); |
| 42 | + vi.restoreAllMocks(); |
| 43 | + }); |
| 44 | + |
| 45 | + it("returns the cached access token when not near expiry", async () => { |
| 46 | + store.save(freshCreds()); |
| 47 | + const tm = new TokenManager({ store, oauthConfig: OAUTH }); |
| 48 | + const fetchSpy = vi.spyOn(globalThis, "fetch"); |
| 49 | + await expect(tm.getAccessToken()).resolves.toBe("access-current"); |
| 50 | + expect(fetchSpy).not.toHaveBeenCalled(); |
| 51 | + }); |
| 52 | + |
| 53 | + it("refreshes and persists when the stored token is within the skew window", async () => { |
| 54 | + store.save(freshCreds({ expiresAt: Date.now() + 10_000 })); // 10s left, under 60s skew |
| 55 | + vi.spyOn(globalThis, "fetch").mockResolvedValueOnce( |
| 56 | + new Response(JSON.stringify({ access_token: "access-NEW", refresh_token: "refresh-NEW", expires_in: 3600 }), { |
| 57 | + status: 200, |
| 58 | + headers: { "Content-Type": "application/json" }, |
| 59 | + }), |
| 60 | + ); |
| 61 | + const tm = new TokenManager({ store, oauthConfig: OAUTH }); |
| 62 | + await expect(tm.getAccessToken()).resolves.toBe("access-NEW"); |
| 63 | + const persisted = store.load(); |
| 64 | + expect(persisted?.accessToken).toBe("access-NEW"); |
| 65 | + expect(persisted?.refreshToken).toBe("refresh-NEW"); |
| 66 | + // Metadata that the refresh endpoint doesn't echo back is preserved. |
| 67 | + expect(persisted?.email).toBe("u@example.test"); |
| 68 | + expect(persisted?.source).toBe("codebase"); |
| 69 | + }); |
| 70 | + |
| 71 | + it("preserves the existing refresh token when the refresh response omits it", async () => { |
| 72 | + store.save(freshCreds({ expiresAt: Date.now() + 5_000 })); |
| 73 | + vi.spyOn(globalThis, "fetch").mockResolvedValueOnce( |
| 74 | + new Response(JSON.stringify({ access_token: "access-NEW", expires_in: 3600 }), { |
| 75 | + status: 200, |
| 76 | + headers: { "Content-Type": "application/json" }, |
| 77 | + }), |
| 78 | + ); |
| 79 | + const tm = new TokenManager({ store, oauthConfig: OAUTH }); |
| 80 | + await tm.getAccessToken(); |
| 81 | + expect(store.load()?.refreshToken).toBe("refresh-current"); |
| 82 | + }); |
| 83 | + |
| 84 | + it("single-flights concurrent refresh calls into one network round-trip", async () => { |
| 85 | + store.save(freshCreds({ expiresAt: Date.now() + 5_000 })); |
| 86 | + const fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation( |
| 87 | + () => |
| 88 | + new Promise((resolve) => { |
| 89 | + setTimeout( |
| 90 | + () => |
| 91 | + resolve( |
| 92 | + new Response(JSON.stringify({ access_token: "access-NEW", expires_in: 3600 }), { |
| 93 | + status: 200, |
| 94 | + headers: { "Content-Type": "application/json" }, |
| 95 | + }), |
| 96 | + ), |
| 97 | + 20, |
| 98 | + ); |
| 99 | + }), |
| 100 | + ); |
| 101 | + const tm = new TokenManager({ store, oauthConfig: OAUTH }); |
| 102 | + const results = await Promise.all([tm.getAccessToken(), tm.getAccessToken(), tm.getAccessToken()]); |
| 103 | + expect(results).toEqual(["access-NEW", "access-NEW", "access-NEW"]); |
| 104 | + expect(fetchSpy).toHaveBeenCalledTimes(1); |
| 105 | + }); |
| 106 | + |
| 107 | + it("subsequent calls AFTER a refresh resolve hit the cached path again", async () => { |
| 108 | + store.save(freshCreds({ expiresAt: Date.now() + 5_000 })); |
| 109 | + const fetchSpy = vi.spyOn(globalThis, "fetch").mockResolvedValueOnce( |
| 110 | + new Response(JSON.stringify({ access_token: "access-NEW", expires_in: 3600 }), { |
| 111 | + status: 200, |
| 112 | + headers: { "Content-Type": "application/json" }, |
| 113 | + }), |
| 114 | + ); |
| 115 | + const tm = new TokenManager({ store, oauthConfig: OAUTH }); |
| 116 | + await tm.getAccessToken(); |
| 117 | + // Now the stored token has a fresh 1h lifetime — should not re-refresh. |
| 118 | + await tm.getAccessToken(); |
| 119 | + expect(fetchSpy).toHaveBeenCalledTimes(1); |
| 120 | + }); |
| 121 | + |
| 122 | + it("throws a sign-in-needed error when no credentials exist", async () => { |
| 123 | + const tm = new TokenManager({ store, oauthConfig: OAUTH }); |
| 124 | + await expect(tm.getAccessToken()).rejects.toThrow(/codebase auth login/); |
| 125 | + }); |
| 126 | + |
| 127 | + it("throws when the token expired but no refresh token was saved", async () => { |
| 128 | + store.save(freshCreds({ expiresAt: Date.now() + 5_000, refreshToken: undefined })); |
| 129 | + const tm = new TokenManager({ store, oauthConfig: OAUTH }); |
| 130 | + await expect(tm.getAccessToken()).rejects.toThrow(/codebase auth login/); |
| 131 | + }); |
| 132 | + |
| 133 | + it("treats undefined expiresAt as never-expires (no refresh attempted)", async () => { |
| 134 | + store.save(freshCreds({ expiresAt: undefined })); |
| 135 | + const fetchSpy = vi.spyOn(globalThis, "fetch"); |
| 136 | + const tm = new TokenManager({ store, oauthConfig: OAUTH }); |
| 137 | + await expect(tm.getAccessToken()).resolves.toBe("access-current"); |
| 138 | + expect(fetchSpy).not.toHaveBeenCalled(); |
| 139 | + }); |
| 140 | +}); |
0 commit comments