Skip to content

Context7 Platform -- Up-to-date docs for AI agents

fix(cli): add token refresh and centralize auth constants (#2210)

Fahreddin Özcan18b3292d012a
diff --git a/.changeset/spicy-parrots-juggle.md b/.changeset/spicy-parrots-juggle.md
new file mode 100644
index 00000000..c02c16fd
--- /dev/null
+++ b/.changeset/spicy-parrots-juggle.md
@@ -0,0 +1,5 @@
+---
+"ctx7": patch
+---
+
+Add token refresh support, centralize auth constants, switch whoami to internal API endpoint with teamspace display, and add unit tests for CLI auth utilities and commands
diff --git a/packages/cli/eslint.config.js b/packages/cli/eslint.config.js
index fe7c0fb7..f91d98c6 100644
--- a/packages/cli/eslint.config.js
+++ b/packages/cli/eslint.config.js
@@ -5,7 +5,7 @@ import eslintPluginPrettier from "eslint-plugin-prettier";
export default defineConfig(
{
// Base ESLint configuration
- ignores: ["node_modules/**", "build/**", "dist/**", ".git/**", ".github/**", "tsup.config.ts"],
+ ignores: ["node_modules/**", "build/**", "dist/**", ".git/**", ".github/**", "tsup.config.ts", "vitest.config.ts"],
},
{
files: ["**/*.ts", "**/*.tsx"],
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 38451370..853d31a3 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -17,7 +17,9 @@
"lint:check": "eslint src",
"format": "prettier --write src",
"format:check": "prettier --check src",
- "clean": "rm -rf dist node_modules"
+ "clean": "rm -rf dist node_modules",
+ "test": "vitest run",
+ "test:watch": "vitest"
},
"dependencies": {
"@inquirer/prompts": "^8.2.0",
@@ -37,7 +39,8 @@
"prettier": "^3.6.2",
"tsup": "^8.5.0",
"typescript": "^5.8.2",
- "typescript-eslint": "^8.28.0"
+ "typescript-eslint": "^8.28.0",
+ "vitest": "^4.0.13"
},
"keywords": [
"context7",
diff --git a/packages/cli/src/__tests__/auth-commands.test.ts b/packages/cli/src/__tests__/auth-commands.test.ts
new file mode 100644
index 00000000..0358eca7
--- /dev/null
+++ b/packages/cli/src/__tests__/auth-commands.test.ts
@@ -0,0 +1,258 @@
+import { describe, test, expect, vi, beforeEach, afterEach } from "vitest";
+import { Command } from "commander";
+
+const mockGetValidAccessToken = vi.fn();
+const mockClearTokens = vi.fn();
+const mockSaveTokens = vi.fn();
+const mockGeneratePKCE = vi.fn();
+const mockGenerateState = vi.fn();
+const mockCreateCallbackServer = vi.fn();
+const mockExchangeCodeForTokens = vi.fn();
+const mockBuildAuthorizationUrl = vi.fn();
+
+vi.mock("../utils/auth.js", () => ({
+ getValidAccessToken: (...args: unknown[]) => mockGetValidAccessToken(...args),
+ clearTokens: (...args: unknown[]) => mockClearTokens(...args),
+ saveTokens: (...args: unknown[]) => mockSaveTokens(...args),
+ generatePKCE: (...args: unknown[]) => mockGeneratePKCE(...args),
+ generateState: (...args: unknown[]) => mockGenerateState(...args),
+ createCallbackServer: (...args: unknown[]) => mockCreateCallbackServer(...args),
+ exchangeCodeForTokens: (...args: unknown[]) => mockExchangeCodeForTokens(...args),
+ buildAuthorizationUrl: (...args: unknown[]) => mockBuildAuthorizationUrl(...args),
+}));
+
+vi.mock("../utils/tracking.js", () => ({
+ trackEvent: vi.fn(),
+}));
+
+const mockSpinner = {
+ start: vi.fn().mockReturnThis(),
+ stop: vi.fn().mockReturnThis(),
+ succeed: vi.fn().mockReturnThis(),
+ fail: vi.fn().mockReturnThis(),
+ text: "",
+};
+vi.mock("ora", () => ({ default: () => mockSpinner }));
+
+const mockOpen = vi.fn().mockResolvedValue(undefined);
+vi.mock("open", () => ({ default: (...args: unknown[]) => mockOpen(...args) }));
+
+vi.mock("../constants.js", () => ({ CLI_CLIENT_ID: "test-client-id" }));
+vi.mock("../utils/api.js", () => ({ getBaseUrl: () => "https://test.context7.com" }));
+
+import { registerAuthCommands, performLogin } from "../commands/auth.js";
+import { trackEvent } from "../utils/tracking.js";
+
+let logOutput: string[];
+let errorOutput: string[];
+let originalExit: typeof process.exit;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ logOutput = [];
+ errorOutput = [];
+ vi.spyOn(console, "log").mockImplementation((...args: unknown[]) => {
+ logOutput.push(args.join(" "));
+ });
+ vi.spyOn(console, "error").mockImplementation((...args: unknown[]) => {
+ errorOutput.push(args.join(" "));
+ });
+ originalExit = process.exit;
+ process.exit = vi.fn() as never;
+
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(() => {
+ throw new Error("fetch not mocked");
+ })
+ );
+});
+
+afterEach(() => {
+ process.exit = originalExit;
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+async function runCommand(...args: string[]): Promise<void> {
+ const program = new Command();
+ program.exitOverride(); // throw instead of process.exit on commander errors
+ registerAuthCommands(program);
+ await program.parseAsync(["node", "test", ...args]);
+}
+
+describe("login command", () => {
+ test("skips login when valid token exists", async () => {
+ mockGetValidAccessToken.mockResolvedValue("existing-token");
+ await runCommand("login");
+ expect(logOutput.some((l) => l.includes("already logged in"))).toBe(true);
+ });
+
+ test("tracks login event", async () => {
+ mockGetValidAccessToken.mockResolvedValue("existing-token");
+ await runCommand("login");
+ expect(trackEvent).toHaveBeenCalledWith("command", { name: "login" });
+ });
+
+ test("calls process.exit(1) when login fails", async () => {
+ mockGetValidAccessToken.mockResolvedValue(null);
+ mockClearTokens.mockReturnValue(false);
+ // Mock performLogin to fail by making createCallbackServer reject
+ mockGeneratePKCE.mockReturnValue({ codeVerifier: "v", codeChallenge: "c" });
+ mockGenerateState.mockReturnValue("state");
+ mockCreateCallbackServer.mockReturnValue({
+ port: Promise.resolve(52417),
+ result: Promise.reject(new Error("timeout")),
+ close: vi.fn(),
+ });
+ mockBuildAuthorizationUrl.mockReturnValue("https://example.com/auth");
+
+ await runCommand("login").catch(() => {});
+ expect(process.exit).toHaveBeenCalledWith(1);
+ });
+});
+
+describe("logout command", () => {
+ test("logs success when tokens were cleared", async () => {
+ mockClearTokens.mockReturnValue(true);
+ await runCommand("logout");
+ expect(logOutput.some((l) => l.includes("Logged out successfully"))).toBe(true);
+ });
+
+ test("logs 'not logged in' when no tokens existed", async () => {
+ mockClearTokens.mockReturnValue(false);
+ await runCommand("logout");
+ expect(logOutput.some((l) => l.includes("You are not logged in"))).toBe(true);
+ });
+
+ test("tracks logout event", async () => {
+ mockClearTokens.mockReturnValue(false);
+ await runCommand("logout");
+ expect(trackEvent).toHaveBeenCalledWith("command", { name: "logout" });
+ });
+});
+
+describe("whoami command", () => {
+ test("shows 'Not logged in' when no valid token", async () => {
+ mockGetValidAccessToken.mockResolvedValue(null);
+ await runCommand("whoami");
+ expect(logOutput.some((l) => l.includes("Not logged in"))).toBe(true);
+ });
+
+ test("fetches and displays user info when logged in", async () => {
+ mockGetValidAccessToken.mockResolvedValue("valid-token");
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({
+ ok: true,
+ json: () =>
+ Promise.resolve({
+ success: true,
+ name: "Test User",
+ email: "[email protected]",
+ teamspace: null,
+ }),
+ })
+ );
+
+ await runCommand("whoami");
+ expect(logOutput.some((l) => l.includes("Logged in"))).toBe(true);
+ expect(logOutput.some((l) => l.includes("Test User"))).toBe(true);
+ expect(logOutput.some((l) => l.includes("[email protected]"))).toBe(true);
+ });
+
+ test("shows session expired hint when fetch fails", async () => {
+ mockGetValidAccessToken.mockResolvedValue("valid-token");
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({
+ ok: false,
+ json: () => Promise.reject(new Error("fail")),
+ })
+ );
+
+ await runCommand("whoami");
+ expect(logOutput.some((l) => l.includes("Session may be expired"))).toBe(true);
+ });
+
+ test("tracks whoami event", async () => {
+ mockGetValidAccessToken.mockResolvedValue(null);
+ await runCommand("whoami");
+ expect(trackEvent).toHaveBeenCalledWith("command", { name: "whoami" });
+ });
+});
+
+describe("performLogin", () => {
+ test("returns access_token on success", async () => {
+ const mockClose = vi.fn();
+ mockGeneratePKCE.mockReturnValue({ codeVerifier: "verifier", codeChallenge: "challenge" });
+ mockGenerateState.mockReturnValue("state");
+ mockCreateCallbackServer.mockReturnValue({
+ port: Promise.resolve(52417),
+ result: Promise.resolve({ code: "auth-code", state: "state" }),
+ close: mockClose,
+ });
+ mockBuildAuthorizationUrl.mockReturnValue("https://example.com/auth");
+ mockExchangeCodeForTokens.mockResolvedValue({
+ access_token: "new-token",
+ token_type: "bearer",
+ });
+
+ const result = await performLogin();
+ expect(result).toBe("new-token");
+ expect(mockSaveTokens).toHaveBeenCalled();
+ expect(mockClose).toHaveBeenCalled();
+ });
+
+ test("opens browser by default", async () => {
+ mockGeneratePKCE.mockReturnValue({ codeVerifier: "v", codeChallenge: "c" });
+ mockGenerateState.mockReturnValue("s");
+ mockCreateCallbackServer.mockReturnValue({
+ port: Promise.resolve(52417),
+ result: Promise.resolve({ code: "code", state: "s" }),
+ close: vi.fn(),
+ });
+ mockBuildAuthorizationUrl.mockReturnValue("https://example.com/auth");
+ mockExchangeCodeForTokens.mockResolvedValue({
+ access_token: "tok",
+ token_type: "bearer",
+ });
+
+ await performLogin(true);
+ expect(mockOpen).toHaveBeenCalledWith("https://example.com/auth");
+ });
+
+ test("skips browser open when openBrowser=false", async () => {
+ mockGeneratePKCE.mockReturnValue({ codeVerifier: "v", codeChallenge: "c" });
+ mockGenerateState.mockReturnValue("s");
+ mockCreateCallbackServer.mockReturnValue({
+ port: Promise.resolve(52417),
+ result: Promise.resolve({ code: "code", state: "s" }),
+ close: vi.fn(),
+ });
+ mockBuildAuthorizationUrl.mockReturnValue("https://example.com/auth");
+ mockExchangeCodeForTokens.mockResolvedValue({
+ access_token: "tok",
+ token_type: "bearer",
+ });
+
+ await performLogin(false);
+ expect(mockOpen).not.toHaveBeenCalled();
+ });
+
+ test("returns null on callback failure", async () => {
+ const mockClose = vi.fn();
+ mockGeneratePKCE.mockReturnValue({ codeVerifier: "v", codeChallenge: "c" });
+ mockGenerateState.mockReturnValue("s");
+ mockCreateCallbackServer.mockReturnValue({
+ port: Promise.resolve(52417),
+ result: Promise.reject(new Error("User cancelled")),
+ close: mockClose,
+ });
+ mockBuildAuthorizationUrl.mockReturnValue("https://example.com/auth");
+
+ const result = await performLogin();
+ expect(result).toBeNull();
+ expect(mockClose).toHaveBeenCalled();
+ });
+});
diff --git a/packages/cli/src/__tests__/auth-utils.test.ts b/packages/cli/src/__tests__/auth-utils.test.ts
new file mode 100644
index 00000000..f48f541b
--- /dev/null
+++ b/packages/cli/src/__tests__/auth-utils.test.ts
@@ -0,0 +1,423 @@
+import { describe, test, expect, vi, beforeEach, afterEach } from "vitest";
+import * as crypto from "crypto";
+
+vi.mock("os", () => ({ homedir: () => "/fake-home", default: { homedir: () => "/fake-home" } }));
+
+vi.mock("fs", () => {
+ const fns = {
+ existsSync: vi.fn(),
+ mkdirSync: vi.fn(),
+ writeFileSync: vi.fn(),
+ readFileSync: vi.fn(),
+ unlinkSync: vi.fn(),
+ };
+ return { ...fns, default: fns };
+});
+
+vi.mock("../constants.js", () => ({ CLI_CLIENT_ID: "test-client-id" }));
+vi.mock("../utils/api.js", () => ({ getBaseUrl: () => "https://test.context7.com" }));
+
+import * as fs from "fs";
+import {
+ generatePKCE,
+ generateState,
+ saveTokens,
+ loadTokens,
+ clearTokens,
+ isTokenExpired,
+ getValidAccessToken,
+ exchangeCodeForTokens,
+ buildAuthorizationUrl,
+ createCallbackServer,
+ type TokenData,
+} from "../utils/auth.js";
+
+const mfs = vi.mocked(fs);
+const CREDENTIALS_PATH = "/fake-home/.context7/credentials.json";
+const CONFIG_DIR_PATH = "/fake-home/.context7";
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(() => {
+ throw new Error("fetch not mocked for this test");
+ })
+ );
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe("generatePKCE", () => {
+ test("returns codeVerifier and codeChallenge with correct SHA-256 relationship", () => {
+ const { codeVerifier, codeChallenge } = generatePKCE();
+ const expected = crypto.createHash("sha256").update(codeVerifier).digest("base64url");
+ expect(codeChallenge).toBe(expected);
+ });
+
+ test("generates unique values on each call", () => {
+ const a = generatePKCE();
+ const b = generatePKCE();
+ expect(a.codeVerifier).not.toBe(b.codeVerifier);
+ });
+});
+
+describe("generateState", () => {
+ test("returns a base64url string", () => {
+ const state = generateState();
+ expect(state).toMatch(/^[A-Za-z0-9_-]+$/);
+ });
+
+ test("generates unique values on each call", () => {
+ expect(generateState()).not.toBe(generateState());
+ });
+});
+
+describe("saveTokens", () => {
+ test("creates config directory if it does not exist", () => {
+ mfs.existsSync.mockReturnValue(false);
+ saveTokens({ access_token: "tok", token_type: "bearer" });
+ expect(mfs.mkdirSync).toHaveBeenCalledWith(CONFIG_DIR_PATH, { recursive: true, mode: 0o700 });
+ });
+
+ test("skips directory creation if it already exists", () => {
+ mfs.existsSync.mockReturnValue(true);
+ saveTokens({ access_token: "tok", token_type: "bearer" });
+ expect(mfs.mkdirSync).not.toHaveBeenCalled();
+ });
+
+ test("writes credentials file with 0o600 permissions", () => {
+ mfs.existsSync.mockReturnValue(true);
+ saveTokens({ access_token: "tok", token_type: "bearer" });
+ expect(mfs.writeFileSync).toHaveBeenCalledWith(CREDENTIALS_PATH, expect.any(String), {
+ mode: 0o600,
+ });
+ });
+
+ test("computes expires_at from expires_in when expires_at is absent", () => {
+ mfs.existsSync.mockReturnValue(true);
+ const now = 1000000;
+ vi.spyOn(Date, "now").mockReturnValue(now);
+ saveTokens({ access_token: "tok", token_type: "bearer", expires_in: 3600 });
+ const written = JSON.parse(mfs.writeFileSync.mock.calls[0][1] as string);
+ expect(written.expires_at).toBe(now + 3600 * 1000);
+ });
+
+ test("preserves existing expires_at if already set", () => {
+ mfs.existsSync.mockReturnValue(true);
+ saveTokens({ access_token: "tok", token_type: "bearer", expires_at: 999, expires_in: 3600 });
+ const written = JSON.parse(mfs.writeFileSync.mock.calls[0][1] as string);
+ expect(written.expires_at).toBe(999);
+ });
+});
+
+describe("loadTokens", () => {
+ test("returns null when credentials file does not exist", () => {
+ mfs.existsSync.mockReturnValue(false);
+ expect(loadTokens()).toBeNull();
+ });
+
+ test("returns parsed TokenData when file exists", () => {
+ const tokens: TokenData = { access_token: "tok", token_type: "bearer" };
+ mfs.existsSync.mockReturnValue(true);
+ mfs.readFileSync.mockReturnValue(JSON.stringify(tokens));
+ expect(loadTokens()).toEqual(tokens);
+ });
+
+ test("returns null on malformed JSON", () => {
+ mfs.existsSync.mockReturnValue(true);
+ mfs.readFileSync.mockReturnValue("not json");
+ expect(loadTokens()).toBeNull();
+ });
+});
+
+describe("clearTokens", () => {
+ test("deletes file and returns true when it exists", () => {
+ mfs.existsSync.mockReturnValue(true);
+ expect(clearTokens()).toBe(true);
+ expect(mfs.unlinkSync).toHaveBeenCalledWith(CREDENTIALS_PATH);
+ });
+
+ test("returns false when file does not exist", () => {
+ mfs.existsSync.mockReturnValue(false);
+ expect(clearTokens()).toBe(false);
+ expect(mfs.unlinkSync).not.toHaveBeenCalled();
+ });
+});
+
+describe("isTokenExpired", () => {
+ test("returns false when no expires_at is set", () => {
+ expect(isTokenExpired({ access_token: "tok", token_type: "bearer" })).toBe(false);
+ });
+
+ test("returns false when well before expiry", () => {
+ expect(
+ isTokenExpired({
+ access_token: "tok",
+ token_type: "bearer",
+ expires_at: Date.now() + 120_000,
+ })
+ ).toBe(false);
+ });
+
+ test("returns true when past expiry", () => {
+ expect(
+ isTokenExpired({ access_token: "tok", token_type: "bearer", expires_at: Date.now() - 1000 })
+ ).toBe(true);
+ });
+
+ test("returns true within 60s buffer window", () => {
+ expect(
+ isTokenExpired({ access_token: "tok", token_type: "bearer", expires_at: Date.now() + 30_000 })
+ ).toBe(true);
+ });
+
+ test("returns false at exactly 60s before expiry", () => {
+ const now = 1000000;
+ vi.spyOn(Date, "now").mockReturnValue(now);
+ expect(
+ isTokenExpired({ access_token: "tok", token_type: "bearer", expires_at: now + 60_000 })
+ ).toBe(false);
+ });
+});
+
+describe("getValidAccessToken", () => {
+ test("returns null when no tokens stored", async () => {
+ mfs.existsSync.mockReturnValue(false);
+ expect(await getValidAccessToken()).toBeNull();
+ });
+
+ test("returns access_token when not expired", async () => {
+ const tokens: TokenData = {
+ access_token: "valid-tok",
+ token_type: "bearer",
+ expires_at: Date.now() + 120_000,
+ };
+ mfs.existsSync.mockReturnValue(true);
+ mfs.readFileSync.mockReturnValue(JSON.stringify(tokens));
+ expect(await getValidAccessToken()).toBe("valid-tok");
+ });
+
+ test("returns null when expired and no refresh_token", async () => {
+ const tokens: TokenData = {
+ access_token: "expired-tok",
+ token_type: "bearer",
+ expires_at: Date.now() - 1000,
+ };
+ mfs.existsSync.mockReturnValue(true);
+ mfs.readFileSync.mockReturnValue(JSON.stringify(tokens));
+ expect(await getValidAccessToken()).toBeNull();
+ });
+
+ test("refreshes token when expired and refresh_token exists", async () => {
+ const tokens: TokenData = {
+ access_token: "expired-tok",
+ token_type: "bearer",
+ expires_at: Date.now() - 1000,
+ refresh_token: "refresh-tok",
+ };
+ const newTokens: TokenData = {
+ access_token: "new-tok",
+ token_type: "bearer",
+ expires_in: 3600,
+ };
+
+ mfs.existsSync.mockReturnValue(true);
+ mfs.readFileSync.mockReturnValue(JSON.stringify(tokens));
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({
+ ok: true,
+ json: () => Promise.resolve(newTokens),
+ })
+ );
+
+ const result = await getValidAccessToken();
+ expect(result).toBe("new-tok");
+
+ expect(fetch).toHaveBeenCalledWith(
+ "https://test.context7.com/api/oauth/token",
+ expect.objectContaining({
+ method: "POST",
+ body: expect.stringContaining("grant_type=refresh_token"),
+ })
+ );
+
+ expect(mfs.writeFileSync).toHaveBeenCalled();
+ });
+
+ test("returns null when refresh fails", async () => {
+ const tokens: TokenData = {
+ access_token: "expired-tok",
+ token_type: "bearer",
+ expires_at: Date.now() - 1000,
+ refresh_token: "refresh-tok",
+ };
+
+ mfs.existsSync.mockReturnValue(true);
+ mfs.readFileSync.mockReturnValue(JSON.stringify(tokens));
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({
+ ok: false,
+ json: () => Promise.resolve({ error: "invalid_grant" }),
+ })
+ );
+
+ expect(await getValidAccessToken()).toBeNull();
+ });
+});
+
+describe("exchangeCodeForTokens", () => {
+ test("POSTs correct parameters and returns TokenData on success", async () => {
+ const tokenResponse: TokenData = { access_token: "new-tok", token_type: "bearer" };
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({
+ ok: true,
+ json: () => Promise.resolve(tokenResponse),
+ })
+ );
+
+ const result = await exchangeCodeForTokens(
+ "https://example.com",
+ "auth-code",
+ "verifier",
+ "http://localhost:52417/callback",
+ "client-id"
+ );
+
+ expect(result).toEqual(tokenResponse);
+ expect(fetch).toHaveBeenCalledWith(
+ "https://example.com/api/oauth/token",
+ expect.objectContaining({
+ method: "POST",
+ body: expect.stringContaining("grant_type=authorization_code"),
+ })
+ );
+ const body = vi.mocked(fetch).mock.calls[0][1]!.body as string;
+ const params = new URLSearchParams(body);
+ expect(params.get("client_id")).toBe("client-id");
+ expect(params.get("code")).toBe("auth-code");
+ expect(params.get("code_verifier")).toBe("verifier");
+ expect(params.get("redirect_uri")).toBe("http://localhost:52417/callback");
+ });
+
+ test("throws with error_description on failure", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({
+ ok: false,
+ json: () => Promise.resolve({ error_description: "bad code" }),
+ })
+ );
+
+ await expect(
+ exchangeCodeForTokens("https://example.com", "code", "verifier", "redirect", "client")
+ ).rejects.toThrow("bad code");
+ });
+
+ test("throws generic message when response has no JSON", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({
+ ok: false,
+ json: () => Promise.reject(new Error("no json")),
+ })
+ );
+
+ await expect(
+ exchangeCodeForTokens("https://example.com", "code", "verifier", "redirect", "client")
+ ).rejects.toThrow("Failed to exchange code for tokens");
+ });
+});
+
+describe("buildAuthorizationUrl", () => {
+ test("constructs URL with all required parameters", () => {
+ const result = buildAuthorizationUrl(
+ "https://example.com",
+ "client-id",
+ "http://localhost:52417/callback",
+ "challenge",
+ "state-value"
+ );
+
+ const url = new URL(result);
+ expect(url.origin).toBe("https://example.com");
+ expect(url.pathname).toBe("/api/oauth/authorize");
+ expect(url.searchParams.get("client_id")).toBe("client-id");
+ expect(url.searchParams.get("redirect_uri")).toBe("http://localhost:52417/callback");
+ expect(url.searchParams.get("code_challenge")).toBe("challenge");
+ expect(url.searchParams.get("code_challenge_method")).toBe("S256");
+ expect(url.searchParams.get("state")).toBe("state-value");
+ expect(url.searchParams.get("scope")).toBe("profile email");
+ expect(url.searchParams.get("response_type")).toBe("code");
+ });
+});
+
+describe("createCallbackServer", () => {
+ async function httpGet(url: string): Promise<void> {
+ const http = await import("http");
+ return new Promise((resolve, reject) => {
+ http
+ .get(url, (res) => {
+ res.resume();
+ res.on("end", resolve);
+ })
+ .on("error", reject);
+ });
+ }
+
+ function closeAndWait(closeFn: () => void): Promise<void> {
+ return new Promise((resolve) => {
+ closeFn();
+ setTimeout(resolve, 100);
+ });
+ }
+
+ test("resolves with code and state on valid callback", async () => {
+ const server = createCallbackServer("expected-state");
+ const port = await server.port;
+ await httpGet(`http://127.0.0.1:${port}/callback?code=auth-code&state=expected-state`);
+ const result = await server.result;
+ expect(result).toEqual({ code: "auth-code", state: "expected-state" });
+ await closeAndWait(server.close);
+ });
+
+ test("rejects on state mismatch", async () => {
+ const server = createCallbackServer("expected-state");
+ const resultPromise = server.result.catch((e: Error) => e);
+ const port = await server.port;
+ await httpGet(`http://127.0.0.1:${port}/callback?code=auth-code&state=wrong-state`);
+ const err = await resultPromise;
+ expect(err).toBeInstanceOf(Error);
+ expect((err as Error).message).toBe("State mismatch");
+ await closeAndWait(server.close);
+ });
+
+ test("rejects on missing code", async () => {
+ const server = createCallbackServer("expected-state");
+ const resultPromise = server.result.catch((e: Error) => e);
+ const port = await server.port;
+ await httpGet(`http://127.0.0.1:${port}/callback?state=expected-state`);
+ const err = await resultPromise;
+ expect(err).toBeInstanceOf(Error);
+ expect((err as Error).message).toBe("Missing authorization code or state");
+ await closeAndWait(server.close);
+ });
+
+ test("rejects on error parameter", async () => {
+ const server = createCallbackServer("expected-state");
+ const resultPromise = server.result.catch((e: Error) => e);
+ const port = await server.port;
+ await httpGet(
+ `http://127.0.0.1:${port}/callback?error=access_denied&error_description=User+cancelled`
+ );
+ const err = await resultPromise;
+ expect(err).toBeInstanceOf(Error);
+ expect((err as Error).message).toBe("User cancelled");
+ await closeAndWait(server.close);
+ });
+});
diff --git a/packages/cli/src/commands/auth.ts b/packages/cli/src/commands/auth.ts
index d2981ad7..ab787b67 100644
--- a/packages/cli/src/commands/auth.ts
+++ b/packages/cli/src/commands/auth.ts
@@ -8,17 +8,15 @@ import {
createCallbackServer,
exchangeCodeForTokens,
saveTokens,
- loadTokens,
clearTokens,
buildAuthorizationUrl,
- isTokenExpired,
+ getValidAccessToken,
} from "../utils/auth.js";
import { trackEvent } from "../utils/tracking.js";
+import { CLI_CLIENT_ID } from "../constants.js";
import { getBaseUrl } from "../utils/api.js";
-const CLI_CLIENT_ID = "2veBSofhicRBguUT";
-
let baseUrl = "https://context7.com";
export function setAuthBaseUrl(url: string): void {
@@ -118,18 +116,13 @@ export async function performLogin(openBrowser = true): Promise<string | null> {
async function loginCommand(options: { browser: boolean }): Promise<void> {
trackEvent("command", { name: "login" });
- const existingTokens = loadTokens();
- if (existingTokens) {
- const expired = isTokenExpired(existingTokens);
- if (!expired || existingTokens.refresh_token) {
- console.log(pc.yellow("You are already logged in."));
- console.log(
- pc.dim("Run 'ctx7 logout' first if you want to log in with a different account.")
- );
- return;
- }
- clearTokens();
+ const existingToken = await getValidAccessToken();
+ if (existingToken) {
+ console.log(pc.yellow("You are already logged in."));
+ console.log(pc.dim("Run 'ctx7 logout' first if you want to log in with a different account."));
+ return;
}
+ clearTokens();
const token = await performLogin(options.browser);
if (!token) {
@@ -150,9 +143,9 @@ function logoutCommand(): void {
async function whoamiCommand(): Promise<void> {
trackEvent("command", { name: "whoami" });
- const tokens = loadTokens();
+ const accessToken = await getValidAccessToken();
- if (!tokens) {
+ if (!accessToken) {
console.log(pc.yellow("Not logged in."));
console.log(pc.dim("Run 'ctx7 login' to authenticate."));
return;
@@ -161,7 +154,7 @@ async function whoamiCommand(): Promise<void> {
console.log(pc.green("Logged in"));
try {
- const whoami = await fetchWhoami(tokens.access_token);
+ const whoami = await fetchWhoami(accessToken);
if (whoami.name) {
console.log(`${pc.dim("Name:".padEnd(13))}${whoami.name}`);
}
@@ -172,9 +165,7 @@ async function whoamiCommand(): Promise<void> {
console.log(`${pc.dim("Teamspace:".padEnd(13))}${whoami.teamspace.name}`);
}
} catch {
- if (isTokenExpired(tokens) && !tokens.refresh_token) {
- console.log(pc.dim("(Session may be expired - run 'ctx7 login' to refresh)"));
- }
+ console.log(pc.dim("(Session may be expired - run 'ctx7 login' to refresh)"));
}
}
diff --git a/packages/cli/src/commands/setup.ts b/packages/cli/src/commands/setup.ts
index 05f1248b..45d0e3e4 100644
--- a/packages/cli/src/commands/setup.ts
+++ b/packages/cli/src/commands/setup.ts
@@ -13,7 +13,7 @@ import { getBaseUrl, downloadSkill } from "../utils/api.js";
import { installSkillFiles } from "../utils/installer.js";
import { promptForInstallTargets, getTargetDirs } from "../utils/ide.js";
import { performLogin } from "./auth.js";
-import { loadTokens, isTokenExpired, saveTokens } from "../utils/auth.js";
+import { saveTokens, getValidAccessToken } from "../utils/auth.js";
import {
type SetupAgent,
type AuthOptions,
@@ -84,11 +84,7 @@ export function registerSetupCommand(program: Command): void {
}
async function authenticateAndGenerateKey(): Promise<string | null> {
- const existingTokens = loadTokens();
- const accessToken =
- existingTokens && !isTokenExpired(existingTokens)
- ? existingTokens.access_token
- : await performLogin();
+ const accessToken = (await getValidAccessToken()) ?? (await performLogin());
if (!accessToken) return null;
@@ -163,8 +159,8 @@ async function resolveCliAuth(apiKey?: string): Promise<void> {
return;
}
- const existingTokens = loadTokens();
- if (existingTokens && !isTokenExpired(existingTokens)) {
+ const validToken = await getValidAccessToken();
+ if (validToken) {
log.blank();
log.plain(`${pc.green("✔")} Authenticated`);
return;
diff --git a/packages/cli/src/constants.ts b/packages/cli/src/constants.ts
index 87cd5285..4aa356e1 100644
--- a/packages/cli/src/constants.ts
+++ b/packages/cli/src/constants.ts
@@ -7,3 +7,4 @@ const pkg = JSON.parse(readFileSync(join(__dirname, "../package.json"), "utf-8")
export const VERSION: string = pkg.version;
export const NAME: string = pkg.name;
+export const CLI_CLIENT_ID = "2veBSofhicRBguUT";
diff --git a/packages/cli/src/utils/auth.ts b/packages/cli/src/utils/auth.ts
index 9db23255..8302f636 100644
--- a/packages/cli/src/utils/auth.ts
+++ b/packages/cli/src/utils/auth.ts
@@ -3,6 +3,8 @@ import * as http from "http";
import * as fs from "fs";
import * as path from "path";
import * as os from "os";
+import { CLI_CLIENT_ID } from "../constants.js";
+import { getBaseUrl } from "./api.js";
const CONFIG_DIR = path.join(os.homedir(), ".context7");
const CREDENTIALS_FILE = path.join(CONFIG_DIR, "credentials.json");
@@ -74,6 +76,50 @@ export function isTokenExpired(tokens: TokenData): boolean {
return Date.now() > tokens.expires_at - 60000;
}
+async function refreshAccessToken(refreshToken: string): Promise<TokenData> {
+ const response = await fetch(`${getBaseUrl()}/api/oauth/token`, {
+ method: "POST",
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
+ body: new URLSearchParams({
+ grant_type: "refresh_token",
+ client_id: CLI_CLIENT_ID,
+ refresh_token: refreshToken,
+ }).toString(),
+ });
+
+ if (!response.ok) {
+ const err = (await response.json().catch(() => ({}))) as TokenErrorResponse;
+ throw new Error(err.error_description || err.error || "Failed to refresh token");
+ }
+
+ return (await response.json()) as TokenData;
+}
+
+/**
+ * Returns a valid access token, refreshing if expired.
+ * Returns null if no tokens exist or refresh fails.
+ */
+export async function getValidAccessToken(): Promise<string | null> {
+ const tokens = loadTokens();
+ if (!tokens) return null;
+
+ if (!isTokenExpired(tokens)) {
+ return tokens.access_token;
+ }
+
+ if (!tokens.refresh_token) {
+ return null;
+ }
+
+ try {
+ const newTokens = await refreshAccessToken(tokens.refresh_token);
+ saveTokens(newTokens);
+ return newTokens.access_token;
+ } catch {
+ return null;
+ }
+}
+
export interface CallbackResult {
code: string;
state: string;
diff --git a/packages/cli/vitest.config.ts b/packages/cli/vitest.config.ts
new file mode 100644
index 00000000..0f78dc01
--- /dev/null
+++ b/packages/cli/vitest.config.ts
@@ -0,0 +1,9 @@
+import { defineConfig } from "vitest/config";
+
+export default defineConfig({
+ test: {
+ globals: true,
+ environment: "node",
+ include: ["src/**/*.test.ts"],
+ },
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index f8645a24..2c525b84 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -97,6 +97,9 @@ importers:
typescript-eslint:
specifier: ^8.28.0
+ vitest:
+ specifier: ^4.0.13
+ version: 4.0.14(@opentelemetry/[email protected])(@types/[email protected])
packages/mcp:
dependencies:
@@ -3413,6 +3416,14 @@ snapshots:
chai: 6.2.1
tinyrainbow: 3.0.3
+ dependencies:
+ '@vitest/spy': 4.0.14
+ estree-walker: 3.0.3
+ magic-string: 0.30.21
+ optionalDependencies:
+ vite: 7.2.4(@types/[email protected])
+
dependencies:
'@vitest/spy': 4.0.14
@@ -4668,6 +4679,18 @@ snapshots:
+ dependencies:
+ esbuild: 0.25.12
+ fdir: 6.5.0([email protected])
+ picomatch: 4.0.3
+ postcss: 8.5.6
+ rollup: 4.53.3
+ tinyglobby: 0.2.15
+ optionalDependencies:
+ '@types/node': 22.19.7
+ fsevents: 2.3.3
+
dependencies:
esbuild: 0.25.12
@@ -4680,6 +4703,44 @@ snapshots:
'@types/node': 25.0.3
fsevents: 2.3.3
+ dependencies:
+ '@vitest/expect': 4.0.14
+ '@vitest/mocker': 4.0.14([email protected](@types/[email protected]))
+ '@vitest/pretty-format': 4.0.14
+ '@vitest/runner': 4.0.14
+ '@vitest/snapshot': 4.0.14
+ '@vitest/spy': 4.0.14
+ '@vitest/utils': 4.0.14
+ es-module-lexer: 1.7.0
+ expect-type: 1.2.2
+ magic-string: 0.30.21
+ obug: 2.1.1
+ pathe: 2.0.3
+ picomatch: 4.0.3
+ std-env: 3.10.0
+ tinybench: 2.9.0
+ tinyexec: 0.3.2
+ tinyglobby: 0.2.15
+ tinyrainbow: 3.0.3
+ vite: 7.2.4(@types/[email protected])
+ why-is-node-running: 2.3.0
+ optionalDependencies:
+ '@opentelemetry/api': 1.9.0
+ '@types/node': 22.19.7
+ transitivePeerDependencies:
+ - jiti
+ - less
+ - lightningcss
+ - msw
+ - sass
+ - sass-embedded
+ - stylus
+ - sugarss
+ - terser
+ - tsx
+ - yaml
+
dependencies:
'@vitest/expect': 4.0.14