Skip to content

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

CTX7-1839: Surface the real error when a CLI OAuth request fails (#2915)

Fahreddin Özcane1b47937db6a
diff --git a/.changeset/surface-cli-auth-errors.md b/.changeset/surface-cli-auth-errors.md
new file mode 100644
index 00000000..dabce34e
--- /dev/null
+++ b/.changeset/surface-cli-auth-errors.md
@@ -0,0 +1,5 @@
+---
+"ctx7": patch
+---
+
+Surface the underlying network error when an OAuth request fails. Connection failures now report the cause (TLS interception, DNS, firewall, timeout) with a hint, and non-JSON error responses report the HTTP status and body excerpt instead of a generic message.
diff --git a/packages/cli/src/__tests__/auth-utils.test.ts b/packages/cli/src/__tests__/auth-utils.test.ts
index 65140847..84276029 100644
--- a/packages/cli/src/__tests__/auth-utils.test.ts
+++ b/packages/cli/src/__tests__/auth-utils.test.ts
@@ -299,12 +299,38 @@ describe("getValidAccessToken", () => {
"fetch",
vi.fn().mockResolvedValue({
ok: false,
- json: () => Promise.resolve({ error: "invalid_grant" }),
+ status: 400,
+ url: "https://test.context7.com/api/oauth/token",
+ text: () => Promise.resolve(JSON.stringify({ error: "invalid_grant" })),
})
);
expect(await getValidAccessToken()).toBeNull();
});
+
+ // 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 null 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",
+ };
+
+ 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" } })
+ )
+ );
+
+ expect(await getValidAccessToken()).toBeNull();
+ });
});
describe("startDeviceAuthorization", () => {
@@ -354,12 +380,45 @@ describe("startDeviceAuthorization", () => {
"fetch",
vi.fn().mockResolvedValue({
ok: false,
- json: () =>
- Promise.resolve({ error: "invalid_request", error_description: "bad client_id" }),
+ status: 400,
+ url: "https://t/api/oauth/device/code",
+ text: () =>
+ Promise.resolve(
+ JSON.stringify({ error: "invalid_request", error_description: "bad client_id" })
+ ),
})
);
await expect(startDeviceAuthorization("https://t", "bogus")).rejects.toThrow("bad client_id");
});
+
+ test("reports status and body excerpt when the response is not JSON", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({
+ ok: false,
+ status: 403,
+ url: "https://t/api/oauth/device/code",
+ text: () => Promise.resolve("<html><body>Blocked by proxy</body></html>"),
+ })
+ );
+ await expect(startDeviceAuthorization("https://t", "c")).rejects.toThrow(
+ /HTTP 403.*Blocked by proxy/s
+ );
+ });
+
+ test("surfaces the underlying cause when the connection fails", async () => {
+ const failure = Object.assign(new TypeError("fetch failed"), {
+ cause: {
+ code: "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
+ message: "unable to verify leaf signature",
+ },
+ });
+ vi.stubGlobal("fetch", vi.fn().mockRejectedValue(failure));
+
+ await expect(startDeviceAuthorization("https://t", "c")).rejects.toThrow(
+ /UNABLE_TO_VERIFY_LEAF_SIGNATURE.*NODE_EXTRA_CA_CERTS/s
+ );
+ });
});
describe("pollDeviceToken", () => {
@@ -412,7 +471,7 @@ describe("pollDeviceToken", () => {
vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("ECONNREFUSED")));
const result = await pollDeviceToken("https://t", "c", "dc");
expect(result.status).toBe("transient");
- expect(result.errorMessage).toBe("ECONNREFUSED");
+ expect(result.errorMessage).toContain("ECONNREFUSED");
});
test("throws on unknown 4xx error code", async () => {
diff --git a/packages/cli/src/utils/auth.ts b/packages/cli/src/utils/auth.ts
index fecd1b20..99769399 100644
--- a/packages/cli/src/utils/auth.ts
+++ b/packages/cli/src/utils/auth.ts
@@ -85,22 +85,15 @@ export function isTokenExpired(tokens: TokenData): boolean {
}
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({
+ return oauthRequest<TokenData>(
+ `${getBaseUrl()}/api/oauth/token`,
+ 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;
+ }),
+ "Failed to refresh token"
+ );
}
/**
@@ -147,6 +140,86 @@ export interface DeviceAuthorizationResponse {
const DEVICE_CODE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
+async function describeErrorResponse(response: Response, fallback: string): Promise<string> {
+ const body = await response.text().catch(() => "");
+
+ try {
+ const err = JSON.parse(body) as TokenErrorResponse;
+ const message = err.error_description || err.error;
+ if (message) return message;
+ } catch {
+ // An interceptor's HTML, not an OAuth error object.
+ }
+
+ const excerpt = body.replace(/\s+/g, " ").trim().slice(0, 200);
+ const detail = `HTTP ${response.status} from ${response.url}`;
+ return excerpt ? `${fallback} (${detail}): ${excerpt}` : `${fallback} (${detail})`;
+}
+
+const TLS_HINT =
+ "The TLS certificate could not be verified, which usually means a proxy is inspecting HTTPS traffic. Point NODE_EXTRA_CA_CERTS at your organization's root CA.";
+const DNS_HINT = "DNS lookup failed. Check your network or VPN connection.";
+const BLOCKED_HINT =
+ "The connection was refused or reset, which usually means a firewall or proxy is blocking it.";
+const TIMEOUT_HINT = "The connection timed out. A proxy or firewall may be dropping the request.";
+const DEFAULT_HINT =
+ "If you are behind a corporate proxy, note that Node does not use HTTPS_PROXY automatically.";
+
+const CONNECTION_HINTS: Record<string, string> = {
+ UNABLE_TO_VERIFY_LEAF_SIGNATURE: TLS_HINT,
+ SELF_SIGNED_CERT_IN_CHAIN: TLS_HINT,
+ DEPTH_ZERO_SELF_SIGNED_CERT: TLS_HINT,
+ CERT_HAS_EXPIRED: TLS_HINT,
+ ENOTFOUND: DNS_HINT,
+ EAI_AGAIN: DNS_HINT,
+ ECONNREFUSED: BLOCKED_HINT,
+ ECONNRESET: BLOCKED_HINT,
+ EHOSTUNREACH: BLOCKED_HINT,
+ ENETUNREACH: BLOCKED_HINT,
+ UND_ERR_CONNECT_TIMEOUT: TIMEOUT_HINT,
+ ETIMEDOUT: TIMEOUT_HINT,
+};
+
+function getErrorCause(error: unknown): { code?: string; message?: string } {
+ if (typeof error !== "object" || error === null || !("cause" in error)) return {};
+ const cause = (error as { cause: unknown }).cause;
+ if (typeof cause !== "object" || cause === null) return {};
+
+ const { code, message } = cause as { code?: unknown; message?: unknown };
+ return {
+ code: typeof code === "string" ? code : undefined,
+ message: typeof message === "string" ? message : undefined,
+ };
+}
+
+function describeConnectionError(error: unknown, url: string): string {
+ const { code, message } = getErrorCause(error);
+ const detail = message || (error instanceof Error ? error.message : String(error));
+ const hint = (code && CONNECTION_HINTS[code]) || DEFAULT_HINT;
+
+ return `Could not reach ${url}: ${detail}${code ? ` (${code})` : ""}\n${hint}`;
+}
+
+async function postForm(url: string, params: URLSearchParams): Promise<Response> {
+ try {
+ return await fetch(url, {
+ method: "POST",
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
+ body: params.toString(),
+ });
+ } catch (error) {
+ throw new Error(describeConnectionError(error, url));
+ }
+}
+
+async function oauthRequest<T>(url: string, params: URLSearchParams, fallback: string): Promise<T> {
+ const response = await postForm(url, params);
+ if (!response.ok) {
+ throw new Error(await describeErrorResponse(response, fallback));
+ }
+ return (await response.json()) as T;
+}
+
/** RFC 8628 §3.2 default poll interval when the server omits `interval`. */
export const DEFAULT_DEVICE_POLL_INTERVAL_SECONDS = 5;
@@ -165,18 +238,11 @@ export async function startDeviceAuthorization(
// ignore
}
- const response = await fetch(`${baseUrl}/api/oauth/device/code`, {
- method: "POST",
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
- body: params.toString(),
- });
-
- if (!response.ok) {
- const err = (await response.json().catch(() => ({}))) as TokenErrorResponse;
- throw new Error(err.error_description || err.error || "Failed to start device authorization");
- }
-
- return (await response.json()) as DeviceAuthorizationResponse;
+ return oauthRequest<DeviceAuthorizationResponse>(
+ `${baseUrl}/api/oauth/device/code`,
+ params,
+ "Failed to start device authorization"
+ );
}
export interface PollDeviceTokenResult {
@@ -192,15 +258,14 @@ export async function pollDeviceToken(
): Promise<PollDeviceTokenResult> {
let response: Response;
try {
- response = await fetch(`${baseUrl}/api/oauth/device/token`, {
- method: "POST",
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
- body: new URLSearchParams({
+ response = await postForm(
+ `${baseUrl}/api/oauth/device/token`,
+ new URLSearchParams({
grant_type: DEVICE_CODE_GRANT,
device_code: deviceCode,
client_id: clientId,
- }).toString(),
- });
+ })
+ );
} catch (error) {
// Network blip — keep polling.
return {
diff --git a/packages/sdk/vitest.config.ts b/packages/sdk/vitest.config.ts
index 18a0a187..a79e8829 100644
--- a/packages/sdk/vitest.config.ts
+++ b/packages/sdk/vitest.config.ts
@@ -10,6 +10,8 @@ export default defineConfig({
environment: "node",
include: ["src/**/*.test.ts"],
env: process.env,
+ // These tests call the live API, so the 5s default fails on latency alone.
+ testTimeout: 30_000,
},
resolve: {
alias: {