Context7 Platform -- Up-to-date docs for AI agents
CTX7-3201: fix(cli): prompt to sign in again when the refresh token is rejected (#3429)
Ramazan Onur Acarf54b37204a26
diff --git a/.changeset/cli-expired-session-prompt.md b/.changeset/cli-expired-session-prompt.mdnew file mode 100644index 00000000..179719fb--- /dev/null+++ b/.changeset/cli-expired-session-prompt.md@@ -0,0 +1,5 @@+---+"ctx7": minor+---++Tell users when their Context7 session has expired instead of silently continuing without an account. If the server rejects the stored refresh token, the CLI clears the dead credentials. In a terminal it asks "Your Context7 session has expired. Sign in again now? (Y/n)" and, on yes, signs you in and continues the command. In scripts, agents, CI or with `--json` it never prompts; it prints a one-line notice to stderr and continues anonymously. Network errors, rate limits and server errors keep the credentials so the next command retries.diff --git a/packages/cli/src/__tests__/auth-commands.test.ts b/packages/cli/src/__tests__/auth-commands.test.tsindex bd1a57fc..070ea7c4 100644--- a/packages/cli/src/__tests__/auth-commands.test.ts+++ b/packages/cli/src/__tests__/auth-commands.test.ts@@ -95,6 +95,13 @@ describe("login command", () => {await runCommand("login").catch(() => {});expect(process.exit).toHaveBeenCalledWith(1);});++ // login runs its own sign-in flow; the expired-session prompt would ask twice.+ test("does not offer the expired-session prompt", async () => {+ mockGetValidAccessToken.mockResolvedValue("existing-token");+ await runCommand("login");+ expect(mockGetValidAccessToken).toHaveBeenCalledWith({ recoverExpiredSession: false });+ });});describe("logout command", () => {@@ -120,6 +127,12 @@ describe("whoami command", () => {expect(trackEvent).toHaveBeenCalledWith("command", { name: "whoami" });});+ test("does not offer the expired-session prompt", async () => {+ mockGetValidAccessToken.mockResolvedValue(undefined);+ await runCommand("whoami");+ expect(mockGetValidAccessToken).toHaveBeenCalledWith({ recoverExpiredSession: false });+ });+test("fetches and displays user info when logged in", async () => {mockGetValidAccessToken.mockResolvedValue("valid-token");vi.stubGlobal(diff --git a/packages/cli/src/__tests__/auth-utils.test.ts b/packages/cli/src/__tests__/auth-utils.test.tsindex cbb0fd99..b9b60756 100644--- a/packages/cli/src/__tests__/auth-utils.test.ts+++ b/packages/cli/src/__tests__/auth-utils.test.ts@@ -16,6 +16,14 @@ vi.mock("fs", () => {vi.mock("../constants.js", () => ({ CLI_CLIENT_ID: "test-client-id" }));vi.mock("../utils/api.js", () => ({ getBaseUrl: () => "https://test.context7.com" }));+const mockConfirm = vi.fn();+vi.mock("@inquirer/prompts", () => ({ confirm: (...args: unknown[]) => mockConfirm(...args) }));++const mockPerformLogin = vi.fn();+vi.mock("../commands/auth.js", () => ({+ performLogin: (...args: unknown[]) => mockPerformLogin(...args),+}));+import * as fs from "fs";import {saveTokens,@@ -42,6 +50,8 @@ beforeEach(() => {vi.stubEnv("XDG_CONFIG_HOME", undefined);vi.stubEnv("XDG_STATE_HOME", undefined);vi.stubEnv("XDG_CACHE_HOME", undefined);+ // A developer's own key would suppress the expired-session prompt.+ vi.stubEnv("CONTEXT7_API_KEY", undefined);vi.stubGlobal("fetch",vi.fn(() => {@@ -177,6 +187,13 @@ describe("clearTokens", () => {expect(mfs.unlinkSync).toHaveBeenCalledWith(CREDENTIALS_PATH);});+ test("also deletes the legacy ~/.context7 credentials file", () => {+ mfs.existsSync.mockReturnValue(true);+ expect(clearTokens()).toBe(true);+ expect(mfs.unlinkSync).toHaveBeenCalledWith(CREDENTIALS_PATH);+ expect(mfs.unlinkSync).toHaveBeenCalledWith(LEGACY_CREDENTIALS_PATH);+ });+test("returns false when file does not exist", () => {mfs.existsSync.mockReturnValue(false);expect(clearTokens()).toBe(false);@@ -326,52 +343,273 @@ describe("getValidAccessToken", () => {const written = JSON.parse(mfs.writeFileSync.mock.calls[0][1] as string);expect(written.refresh_token).toBe("rotated-tok");});+});- test("returns undefined when refresh fails", async () => {- const tokens: TokenData = {- access_token: "expired-tok",- token_type: "bearer",- expires_at: Date.now() - 1000,- refresh_token: "refresh-tok",- };+describe("getValidAccessToken when the refresh token is rejected", () => {+ const EXPIRED: TokenData = {+ access_token: "expired-tok",+ token_type: "bearer",+ // A fixed past instant: earlier tests leave Date.now mocked.+ expires_at: 1,+ refresh_token: "refresh-tok",+ };- mfs.existsSync.mockReturnValue(true);- mfs.readFileSync.mockReturnValue(JSON.stringify(tokens));+ let files: Map<string, string>;+ let stdinTTY: PropertyDescriptor | undefined;+ let stdoutTTY: PropertyDescriptor | undefined;++ function setTTY(value: boolean): void {+ Object.defineProperty(process.stdin, "isTTY", { value, configurable: true });+ Object.defineProperty(process.stdout, "isTTY", { value, configurable: true });+ }++ function restoreTTY(target: NodeJS.ReadStream | NodeJS.WriteStream, d?: PropertyDescriptor) {+ if (d) Object.defineProperty(target, "isTTY", d);+ else delete (target as { isTTY?: boolean }).isTTY;+ }++ function stubRefreshResponse(status: number, body: unknown): void {vi.stubGlobal("fetch",vi.fn().mockResolvedValue({- ok: false,- status: 400,+ ok: status < 400,+ status,url: "https://test.context7.com/api/oauth/token",- text: () => Promise.resolve(JSON.stringify({ error: "invalid_grant" })),+ json: () => Promise.resolve(body),+ text: () => Promise.resolve(JSON.stringify(body)),}));+ }- expect(await getValidAccessToken()).toBeUndefined();+ function stubInvalidGrant(): void {+ stubRefreshResponse(400, {+ error: "invalid_grant",+ error_description: "The refresh token is malformed or not valid",+ });+ }++ let logSpy: ReturnType<typeof vi.spyOn>;+ let errorSpy: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ // In-memory credentials so clearing them is visible to the next command.+ files = new Map([[CREDENTIALS_PATH, JSON.stringify(EXPIRED)]]);+ mfs.existsSync.mockImplementation((p) => files.has(String(p)) || p === CONFIG_DIR_PATH);+ mfs.readFileSync.mockImplementation((p) => files.get(String(p)) ?? "");+ mfs.writeFileSync.mockImplementation((p, data) => void files.set(String(p), String(data)));+ mfs.unlinkSync.mockImplementation((p) => void files.delete(String(p)));++ stdinTTY = Object.getOwnPropertyDescriptor(process.stdin, "isTTY");+ stdoutTTY = Object.getOwnPropertyDescriptor(process.stdout, "isTTY");+ logSpy = vi.spyOn(console, "log").mockImplementation(() => {});+ errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ });++ afterEach(() => {+ restoreTTY(process.stdin, stdinTTY);+ restoreTTY(process.stdout, stdoutTTY);+ vi.restoreAllMocks();+ });++ describe("in an interactive terminal", () => {+ beforeEach(() => setTTY(true));++ test("prompts once and returns the new token when the user signs in", async () => {+ stubInvalidGrant();+ mockConfirm.mockResolvedValue(true);+ mockPerformLogin.mockImplementation(async () => {+ files.set(CREDENTIALS_PATH, JSON.stringify({ access_token: "ctx7sk-new" }));+ return "ctx7sk-new";+ });++ expect(await getValidAccessToken()).toBe("ctx7sk-new");+ expect(mockConfirm).toHaveBeenCalledTimes(1);+ expect(mockConfirm).toHaveBeenCalledWith(+ expect.objectContaining({+ message: "Your Context7 session has expired. Sign in again now?",+ default: true,+ })+ );+ expect(mockPerformLogin).toHaveBeenCalledTimes(1);++ // The next command uses the new credentials without refreshing.+ expect(await getValidAccessToken()).toBe("ctx7sk-new");+ expect(mockConfirm).toHaveBeenCalledTimes(1);+ expect(fetch).toHaveBeenCalledTimes(1);+ });++ test("continues anonymously on No and does not prompt on the next command", async () => {+ stubInvalidGrant();+ mockConfirm.mockResolvedValue(false);++ expect(await getValidAccessToken()).toBeUndefined();+ expect(mockPerformLogin).not.toHaveBeenCalled();+ expect(files.has(CREDENTIALS_PATH)).toBe(false);+ expect(logSpy).toHaveBeenCalledWith(+ expect.stringContaining("Continuing without an account. Run ctx7 login to sign in later.")+ );++ expect(await getValidAccessToken()).toBeUndefined();+ expect(mockConfirm).toHaveBeenCalledTimes(1);+ expect(fetch).toHaveBeenCalledTimes(1);+ });++ test("continues anonymously when the login fails", async () => {+ stubInvalidGrant();+ mockConfirm.mockResolvedValue(true);+ mockPerformLogin.mockResolvedValue(null);++ expect(await getValidAccessToken()).toBeUndefined();+ expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("Continuing without an account"));+ });++ test("exits on Ctrl-C instead of continuing anonymously", async () => {+ stubInvalidGrant();+ mockConfirm.mockRejectedValue(+ Object.assign(new Error("User force closed the prompt"), { name: "ExitPromptError" })+ );+ vi.spyOn(process.stdout, "write").mockImplementation(() => true);+ const exit = vi.spyOn(process, "exit").mockImplementation((() => {+ throw new Error("process.exit");+ }) as never);++ await expect(getValidAccessToken()).rejects.toThrow("process.exit");+ expect(exit).toHaveBeenCalledWith(130);+ expect(mockPerformLogin).not.toHaveBeenCalled();+ expect(files.has(CREDENTIALS_PATH)).toBe(false);+ });++ // getAuthHeaders sends CONTEXT7_API_KEY ahead of any stored token, so the+ // user is still authenticated: no prompt, no "continuing without an account".+ test("clears silently without prompting when CONTEXT7_API_KEY is set", async () => {+ vi.stubEnv("CONTEXT7_API_KEY", "ctx7sk-envkey");+ stubInvalidGrant();++ expect(await getValidAccessToken()).toBeUndefined();+ expect(files.has(CREDENTIALS_PATH)).toBe(false);+ expect(mockConfirm).not.toHaveBeenCalled();+ expect(logSpy).not.toHaveBeenCalled();+ expect(errorSpy).not.toHaveBeenCalled();+ });++ test("does not prompt when --json is passed", async () => {+ const argv = process.argv;+ process.argv = [...argv, "--json"];+ try {+ stubInvalidGrant();+ expect(await getValidAccessToken()).toBeUndefined();+ } finally {+ process.argv = argv;+ }+ expect(mockConfirm).not.toHaveBeenCalled();+ expect(errorSpy).toHaveBeenCalledTimes(1);+ });++ test("clears silently without prompting when recovery is disabled", async () => {+ stubInvalidGrant();++ expect(await getValidAccessToken({ recoverExpiredSession: false })).toBeUndefined();+ expect(mockConfirm).not.toHaveBeenCalled();+ expect(files.has(CREDENTIALS_PATH)).toBe(false);+ expect(logSpy).not.toHaveBeenCalled();+ expect(errorSpy).not.toHaveBeenCalled();+ });++ // Parallel commands (common with agents) race on a rotating refresh token:+ // the loser's "already used" rejection must not delete the winner's tokens.+ test("keeps credentials another process rotated in the meantime", async () => {+ const rotated = {+ access_token: "rotated-access",+ token_type: "bearer",+ refresh_token: "rotated-refresh",+ expires_at: 8_000_000_000_000,+ };+ vi.stubGlobal(+ "fetch",+ vi.fn().mockImplementation(async () => {+ files.set(CREDENTIALS_PATH, JSON.stringify(rotated));+ return {+ ok: false,+ status: 400,+ url: "https://test.context7.com/api/oauth/token",+ text: () => Promise.resolve(JSON.stringify({ error: "invalid_grant" })),+ };+ })+ );++ expect(await getValidAccessToken()).toBe("rotated-access");+ expect(files.get(CREDENTIALS_PATH)).toBe(JSON.stringify(rotated));+ expect(mockConfirm).not.toHaveBeenCalled();+ });++ test("treats invalid_client as a definitive rejection", async () => {+ stubRefreshResponse(401, { error: "invalid_client" });+ mockConfirm.mockResolvedValue(false);++ expect(await getValidAccessToken()).toBeUndefined();+ expect(mockConfirm).toHaveBeenCalledTimes(1);+ expect(files.has(CREDENTIALS_PATH)).toBe(false);+ });});- // An expired refresh token is indistinguishable from being logged out, so the- // caller reports "not logged in" rather than surfacing a network error here.- test("returns undefined when the refresh connection fails", async () => {- const tokens: TokenData = {- access_token: "expired-tok",- token_type: "bearer",- expires_at: Date.now() - 1000,- refresh_token: "refresh-tok",- };+ describe("without a TTY", () => {+ beforeEach(() => setTTY(false));- mfs.existsSync.mockReturnValue(true);- mfs.readFileSync.mockReturnValue(JSON.stringify(tokens));- vi.stubGlobal(- "fetch",- vi- .fn()- .mockRejectedValue(- Object.assign(new TypeError("fetch failed"), { cause: { code: "ENOTFOUND" } })- )- );+ test("never prompts, clears the credentials and writes to stderr only", async () => {+ files.set(LEGACY_CREDENTIALS_PATH, JSON.stringify(EXPIRED));+ stubInvalidGrant();+ const stdoutWrite = vi.spyOn(process.stdout, "write").mockImplementation(() => true);- expect(await getValidAccessToken()).toBeUndefined();+ expect(await getValidAccessToken()).toBeUndefined();++ expect(mockConfirm).not.toHaveBeenCalled();+ expect(mockPerformLogin).not.toHaveBeenCalled();+ expect(files.has(CREDENTIALS_PATH)).toBe(false);+ expect(files.has(LEGACY_CREDENTIALS_PATH)).toBe(false);+ expect(errorSpy).toHaveBeenCalledTimes(1);+ expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("Run ctx7 login"));+ expect(logSpy).not.toHaveBeenCalled();+ expect(stdoutWrite).not.toHaveBeenCalled();++ // Credentials are gone, so the next command neither refreshes nor warns.+ expect(await getValidAccessToken()).toBeUndefined();+ expect(errorSpy).toHaveBeenCalledTimes(1);+ expect(fetch).toHaveBeenCalledTimes(1);+ });+ });++ describe("transient failures keep the credentials and never prompt", () => {+ beforeEach(() => setTTY(true));++ test.each([+ [503, { error: "server_error" }],+ [429, { error: "invalid_grant" }],+ [400, "<html>Bad gateway</html>"],+ ])("HTTP %s", async (status, body) => {+ stubRefreshResponse(status, body);++ expect(await getValidAccessToken()).toBeUndefined();+ expect(files.get(CREDENTIALS_PATH)).toBe(JSON.stringify(EXPIRED));+ expect(mfs.unlinkSync).not.toHaveBeenCalled();+ expect(mockConfirm).not.toHaveBeenCalled();+ expect(errorSpy).not.toHaveBeenCalled();+ });++ test("network error", async () => {+ vi.stubGlobal(+ "fetch",+ vi+ .fn()+ .mockRejectedValue(+ Object.assign(new TypeError("fetch failed"), { cause: { code: "ENOTFOUND" } })+ )+ );++ expect(await getValidAccessToken()).toBeUndefined();+ expect(files.get(CREDENTIALS_PATH)).toBe(JSON.stringify(EXPIRED));+ expect(mockConfirm).not.toHaveBeenCalled();+ expect(errorSpy).not.toHaveBeenCalled();+ });});});diff --git a/packages/cli/src/commands/auth.ts b/packages/cli/src/commands/auth.tsindex 948cadd1..e1c2887d 100644--- a/packages/cli/src/commands/auth.ts+++ b/packages/cli/src/commands/auth.ts@@ -189,7 +189,7 @@ export async function performLogin(openBrowser = true): Promise<string | null> {async function loginCommand(options: { browser: boolean }): Promise<void> {trackEvent("command", { name: "login" });- const existingToken = await getValidAccessToken();+ const existingToken = await getValidAccessToken({ recoverExpiredSession: false });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."));@@ -216,7 +216,7 @@ function logoutCommand(): void {async function whoamiCommand(): Promise<void> {trackEvent("command", { name: "whoami" });- const accessToken = await getValidAccessToken();+ const accessToken = await getValidAccessToken({ recoverExpiredSession: false });if (!accessToken) {console.log(pc.yellow("Not logged in."));diff --git a/packages/cli/src/commands/docs.ts b/packages/cli/src/commands/docs.tsindex 2565b34c..aac97c0c 100644--- a/packages/cli/src/commands/docs.ts+++ b/packages/cli/src/commands/docs.ts@@ -50,8 +50,9 @@ async function resolveCommand(): Promise<void> {trackEvent("command", { name: "library" });- const spinner = isTTY ? ora(`Searching for "${library}"...`).start() : null;+ // Resolve the token before the spinner starts: an expired session may prompt.const accessToken = await getValidAccessToken();+ const spinner = isTTY ? ora(`Searching for "${library}"...`).start() : null;let data;try {@@ -131,8 +132,9 @@ async function queryCommand(return;}- const spinner = isTTY ? ora(`Fetching docs for "${libraryId}"...`).start() : null;+ // Resolve the token before the spinner starts: an expired session may prompt.const accessToken = await getValidAccessToken();+ const spinner = isTTY ? ora(`Fetching docs for "${libraryId}"...`).start() : null;const outputType = options.json ? "json" : "txt";let result;diff --git a/packages/cli/src/commands/generate.ts b/packages/cli/src/commands/generate.tsindex 7f81c66a..9e60f0a5 100644--- a/packages/cli/src/commands/generate.ts+++ b/packages/cli/src/commands/generate.ts@@ -60,7 +60,7 @@ async function generateCommand(options: GenerateOptions): Promise<void> {trackEvent("command", { name: "generate" });log.blank();- let accessToken = await getValidAccessToken();+ let accessToken = await getValidAccessToken({ recoverExpiredSession: false });if (!accessToken) {log.info("Authentication required. Logging in...");log.blank();diff --git a/packages/cli/src/commands/setup.ts b/packages/cli/src/commands/setup.tsindex 0f8da581..e3436ae5 100644--- a/packages/cli/src/commands/setup.ts+++ b/packages/cli/src/commands/setup.ts@@ -215,7 +215,7 @@ async function resolveCliAuth(apiKey?: string): Promise<void> {return;}- const validToken = await getValidAccessToken();+ const validToken = await getValidAccessToken({ recoverExpiredSession: false });if (validToken) {log.blank();log.plain(`${pc.green("✔")} Authenticated`);diff --git a/packages/cli/src/commands/skill.ts b/packages/cli/src/commands/skill.tsindex 6b33267d..66526eb6 100644--- a/packages/cli/src/commands/skill.ts+++ b/packages/cli/src/commands/skill.ts@@ -841,9 +841,9 @@ async function suggestCommand(options: SuggestOptions): Promise<void> {scanSpinner.succeed(`Found ${deps.length} dependencies`);// Step 2: Single API call to backend- const searchSpinner = ora("Finding matching skills...").start();-+ // Resolve the token before the spinner starts: an expired session may prompt.const accessToken = await getValidAccessToken();+ const searchSpinner = ora("Finding matching skills...").start();let data;try {diff --git a/packages/cli/src/setup/auth.ts b/packages/cli/src/setup/auth.tsindex 0cd70ab2..59232607 100644--- a/packages/cli/src/setup/auth.ts+++ b/packages/cli/src/setup/auth.ts@@ -7,7 +7,8 @@ import { getValidAccessToken, isContext7ApiKey } from "../utils/auth.js";import { log } from "../utils/logger.js";export async function resolveSetupApiKey(): Promise<string | null> {- const accessToken = (await getValidAccessToken()) ?? (await performLogin());+ const accessToken =+ (await getValidAccessToken({ recoverExpiredSession: false })) ?? (await performLogin());if (!accessToken) return null;if (isContext7ApiKey(accessToken)) return accessToken;diff --git a/packages/cli/src/utils/auth.ts b/packages/cli/src/utils/auth.tsindex 2cb01143..d6cbf50b 100644--- a/packages/cli/src/utils/auth.ts+++ b/packages/cli/src/utils/auth.ts@@ -1,5 +1,7 @@import * as fs from "fs";import * as os from "os";+import pc from "picocolors";+import { confirm } from "@inquirer/prompts";import { CLI_CLIENT_ID } from "../constants.js";import { getBaseUrl } from "./api.js";import {@@ -91,16 +93,106 @@ export function isTokenExpired(tokens: TokenData): boolean {return Date.now() > tokens.expires_at - 60000;}+/**+ * The authorization server definitively rejected the stored refresh token+ * (RFC 6749 §5.2 `invalid_grant` / `invalid_client`). Retrying cannot succeed;+ * only a new login can.+ */+class RefreshTokenRejectedError extends Error {}++const DEFINITIVE_REFRESH_ERRORS = new Set(["invalid_grant", "invalid_client"]);+async function refreshAccessToken(refreshToken: string): Promise<TokenData> {- return oauthRequest<TokenData>(+ const response = await postForm(`${getBaseUrl()}/api/oauth/token`,new URLSearchParams({grant_type: "refresh_token",client_id: CLI_CLIENT_ID,refresh_token: refreshToken,- }),- "Failed to refresh token"+ }));+ if (response.ok) {+ return (await response.json()) as TokenData;+ }++ const body = await response.text().catch(() => "");+ // 429 and 5xx are transient even if a proxy dresses them up as an OAuth error.+ if (response.status < 500 && response.status !== 429) {+ try {+ const err = JSON.parse(body) as TokenErrorResponse;+ if (err.error && DEFINITIVE_REFRESH_ERRORS.has(err.error)) {+ throw new RefreshTokenRejectedError(err.error_description || err.error);+ }+ } catch (error) {+ if (error instanceof RefreshTokenRejectedError) throw error;+ // Not an OAuth error object; treat as transient below.+ }+ }+ throw new Error(`Failed to refresh token (HTTP ${response.status})`);+}++const SESSION_EXPIRED_NOTICE =+ "Your Context7 session has expired. Run ctx7 login to sign in again. Continuing without an account.";++/**+ * True when we may prompt: both stdin and stdout are terminals and no+ * machine-readable output was requested.+ */+function isInteractiveSession(): boolean {+ if (!process.stdin.isTTY || !process.stdout.isTTY) return false;+ return !process.argv.includes("--json");+}++/**+ * The stored session was rejected and its credentials cleared. In a terminal,+ * offer to sign in again; otherwise tell the user on stderr so stdout stays+ * parseable. Returns the new access token if the user signed in.+ */+async function recoverExpiredSession(): Promise<string | undefined> {+ if (!isInteractiveSession()) {+ console.error(SESSION_EXPIRED_NOTICE);+ return undefined;+ }++ let signIn: boolean;+ try {+ signIn = await confirm({+ message: "Your Context7 session has expired. Sign in again now?",+ default: true,+ });+ } catch (error) {+ // Ctrl-C aborts the command, as it does at every other ctx7 prompt and at+ // performLogin's "Press Enter" one step later. Only "No" continues.+ if (error instanceof Error && error.name === "ExitPromptError") {+ process.stdout.write("\n");+ process.exit(130);+ }+ signIn = false;+ }++ if (signIn) {+ // Imported lazily: commands/auth.ts depends on this module.+ const { performLogin } = await import("../commands/auth.js");+ const token = await performLogin();+ if (token) {+ console.log("");+ return token;+ }+ }++ console.log(pc.dim("Continuing without an account. Run ctx7 login to sign in later."));+ console.log("");+ return undefined;+}++interface GetValidAccessTokenOptions {+ /**+ * When the stored refresh token is rejected, offer to sign in again (or+ * print a notice when non-interactive). Commands that run their own login+ * flow (login, whoami, setup, generate) turn this off so the user is not+ * asked twice; the dead credentials are still cleared.+ */+ recoverExpiredSession?: boolean;}/**@@ -108,8 +200,14 @@ async function refreshAccessToken(refreshToken: string): Promise<TokenData> {* tokens are stored or refresh fails. Pre-0.5 installs may have OAuth tokens* with a `refresh_token`; new installs hold long-lived API keys that never* expire and skip the refresh path entirely.+ *+ * A transient refresh failure (network, 429, 5xx) keeps the credentials so the+ * next command retries. A definitive rejection clears them, so the user is+ * told at most once per expired session.*/-export async function getValidAccessToken(): Promise<string | undefined> {+export async function getValidAccessToken(+ options: GetValidAccessTokenOptions = {}+): Promise<string | undefined> {const tokens = loadTokens();if (!tokens) return undefined;@@ -128,8 +226,21 @@ export async function getValidAccessToken(): Promise<string | undefined> {// drop it and log the user out at the next expiry.saveTokens({ refresh_token: tokens.refresh_token, ...newTokens });return newTokens.access_token;- } catch {- return undefined;+ } catch (error) {+ if (!(error instanceof RefreshTokenRejectedError)) return undefined;+ // A concurrent ctx7 process may have refreshed first, rotating the token we+ // sent. Its credentials are valid; clearing them would log the user out.+ const current = loadTokens();+ if (current && current.refresh_token !== tokens.refresh_token) {+ return isTokenExpired(current) ? undefined : current.access_token;+ }+ clearTokens();+ // CONTEXT7_API_KEY takes precedence over stored tokens in every request+ // (getAuthHeaders), so the user is still signed in; don't claim otherwise.+ if (options.recoverExpiredSession === false || process.env.CONTEXT7_API_KEY) {+ return undefined;+ }+ return recoverExpiredSession();}}