Skip to content

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

feat(cli): OAuth 2.0 device authorization flow (#2714)

Fahreddin Özcan5a180d5b80c1
diff --git a/.changeset/cli-device-oauth.md b/.changeset/cli-device-oauth.md
new file mode 100644
index 00000000..141ee9a7
--- /dev/null
+++ b/.changeset/cli-device-oauth.md
@@ -0,0 +1,7 @@
+---
+"ctx7": minor
+---
+
+Add OAuth 2.0 device authorization flow (RFC 8628) for `ctx7 login` and `ctx7 setup`. Required for headless / remote hosts (SSH, Codespaces, Docker, CI) where the existing localhost-callback flow can't work — the browser was opening on the user's laptop while the callback listener ran on the remote host.
+
+The new flow prints a verification URL and short code, then polls a token endpoint. The user visits the URL on any device, signs in, and approves; the CLI receives the same `ctx7sk-…` API key it would have gotten from the legacy flow. Device flow is selected automatically when `SSH_CONNECTION` is set or `$DISPLAY` is missing on Linux, and can be forced with `ctx7 login --device`. Polling tolerates transient network errors and 5xx responses without ending the session.
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 04b6464e..30a6f4dd 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -24,6 +24,7 @@
"dependencies": {
"@inquirer/core": "^11.1.1",
"@inquirer/prompts": "^8.2.0",
+ "boxen": "^8.0.1",
"commander": "^13.1.0",
"figlet": "^1.9.4",
"open": "^10.1.0",
diff --git a/packages/cli/src/__tests__/auth-commands.test.ts b/packages/cli/src/__tests__/auth-commands.test.ts
index 0358eca7..e124e4a0 100644
--- a/packages/cli/src/__tests__/auth-commands.test.ts
+++ b/packages/cli/src/__tests__/auth-commands.test.ts
@@ -9,6 +9,9 @@ const mockGenerateState = vi.fn();
const mockCreateCallbackServer = vi.fn();
const mockExchangeCodeForTokens = vi.fn();
const mockBuildAuthorizationUrl = vi.fn();
+const mockShouldUseDeviceFlow = vi.fn((..._args: unknown[]) => false);
+const mockStartDeviceAuthorization = vi.fn();
+const mockPollDeviceToken = vi.fn();
vi.mock("../utils/auth.js", () => ({
getValidAccessToken: (...args: unknown[]) => mockGetValidAccessToken(...args),
@@ -19,6 +22,10 @@ vi.mock("../utils/auth.js", () => ({
createCallbackServer: (...args: unknown[]) => mockCreateCallbackServer(...args),
exchangeCodeForTokens: (...args: unknown[]) => mockExchangeCodeForTokens(...args),
buildAuthorizationUrl: (...args: unknown[]) => mockBuildAuthorizationUrl(...args),
+ shouldUseDeviceFlow: (...args: unknown[]) => mockShouldUseDeviceFlow(...args),
+ startDeviceAuthorization: (...args: unknown[]) => mockStartDeviceAuthorization(...args),
+ pollDeviceToken: (...args: unknown[]) => mockPollDeviceToken(...args),
+ DEFAULT_DEVICE_POLL_INTERVAL_SECONDS: 5,
}));
vi.mock("../utils/tracking.js", () => ({
@@ -40,7 +47,7 @@ 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 { registerAuthCommands, performLogin, performDeviceLogin } from "../commands/auth.js";
import { trackEvent } from "../utils/tracking.js";
let logOutput: string[];
@@ -255,4 +262,201 @@ describe("performLogin", () => {
expect(result).toBeNull();
expect(mockClose).toHaveBeenCalled();
});
+
+ test("uses device flow when forceDevice=true", async () => {
+ mockStartDeviceAuthorization.mockResolvedValue({
+ device_code: "dc",
+ user_code: "ABCD-EFGH",
+ verification_uri: "https://t/oauth/device",
+ verification_uri_complete: "https://t/oauth/device?user_code=ABCD-EFGH",
+ expires_in: 600,
+ interval: 0,
+ });
+ mockPollDeviceToken.mockResolvedValue({
+ status: "approved",
+ tokens: { access_token: "ctx7sk-x", token_type: "bearer" },
+ });
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({ ok: false, json: () => Promise.resolve({}) })
+ );
+
+ const result = await performLogin(false, true);
+ expect(result).toBe("ctx7sk-x");
+ expect(mockCreateCallbackServer).not.toHaveBeenCalled();
+ });
+
+ test("uses device flow when shouldUseDeviceFlow returns true", async () => {
+ mockShouldUseDeviceFlow.mockReturnValueOnce(true);
+ mockStartDeviceAuthorization.mockResolvedValue({
+ device_code: "dc",
+ user_code: "X",
+ verification_uri: "https://t",
+ verification_uri_complete: undefined,
+ expires_in: 600,
+ interval: 0,
+ });
+ mockPollDeviceToken.mockResolvedValue({
+ status: "approved",
+ tokens: { access_token: "tok", token_type: "bearer" },
+ });
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({ ok: false, json: () => Promise.resolve({}) })
+ );
+
+ const result = await performLogin(false);
+ expect(result).toBe("tok");
+ expect(mockStartDeviceAuthorization).toHaveBeenCalled();
+ });
+});
+
+describe("performDeviceLogin", () => {
+ const authorization = {
+ device_code: "dc",
+ user_code: "ABCD-EFGH",
+ verification_uri: "https://t.example/oauth/device",
+ verification_uri_complete: "https://t.example/oauth/device?user_code=ABCD-EFGH",
+ expires_in: 600,
+ interval: 0, // 0ms poll cadence so tests don't need fake timers
+ };
+
+ beforeEach(() => {
+ // Quiet whoami so announceIdentity falls back without polluting stdout.
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({ ok: false, json: () => Promise.resolve({}) })
+ );
+ });
+
+ test("returns access_token on approved", async () => {
+ mockStartDeviceAuthorization.mockResolvedValue(authorization);
+ mockPollDeviceToken.mockResolvedValue({
+ status: "approved",
+ tokens: { access_token: "ctx7sk-x", token_type: "bearer" },
+ });
+
+ const result = await performDeviceLogin(false);
+ expect(result).toBe("ctx7sk-x");
+ expect(mockSaveTokens).toHaveBeenCalledWith({
+ access_token: "ctx7sk-x",
+ token_type: "bearer",
+ });
+ });
+
+ test("returns null on denied", async () => {
+ mockStartDeviceAuthorization.mockResolvedValue(authorization);
+ mockPollDeviceToken.mockResolvedValue({ status: "denied" });
+
+ expect(await performDeviceLogin(false)).toBeNull();
+ expect(mockSaveTokens).not.toHaveBeenCalled();
+ });
+
+ test("returns null on expired", async () => {
+ mockStartDeviceAuthorization.mockResolvedValue(authorization);
+ mockPollDeviceToken.mockResolvedValue({ status: "expired" });
+
+ expect(await performDeviceLogin(false)).toBeNull();
+ expect(mockSaveTokens).not.toHaveBeenCalled();
+ });
+
+ test("keeps polling on transient errors and applies backoff (RFC 8628 §3.5)", async () => {
+ vi.useFakeTimers();
+ try {
+ mockStartDeviceAuthorization.mockResolvedValue(authorization);
+ mockPollDeviceToken
+ .mockResolvedValueOnce({ status: "transient", errorMessage: "ECONN" })
+ .mockResolvedValueOnce({ status: "pending" })
+ .mockResolvedValueOnce({
+ status: "approved",
+ tokens: { access_token: "t", token_type: "bearer" },
+ });
+
+ const pending = performDeviceLogin(false);
+ // transient bumps the interval by 5s (mirroring slow_down), so the
+ // 2nd and 3rd polls each need a 5s wait. Advance enough to cover both.
+ await vi.advanceTimersByTimeAsync(11_000);
+ const result = await pending;
+ expect(result).toBe("t");
+ expect(mockPollDeviceToken).toHaveBeenCalledTimes(3);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ test("backs off polling cadence when slow_down is returned", async () => {
+ vi.useFakeTimers();
+ try {
+ mockStartDeviceAuthorization.mockResolvedValue(authorization);
+ mockPollDeviceToken.mockResolvedValueOnce({ status: "slow_down" }).mockResolvedValueOnce({
+ status: "approved",
+ tokens: { access_token: "t", token_type: "bearer" },
+ });
+
+ const pending = performDeviceLogin(false);
+ // First poll fires after the initial 0ms interval; slow_down then
+ // bumps the interval by 5000ms before the second poll.
+ await vi.advanceTimersByTimeAsync(5500);
+ const result = await pending;
+ expect(result).toBe("t");
+ expect(mockPollDeviceToken).toHaveBeenCalledTimes(2);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ test("returns null when start request throws", async () => {
+ mockStartDeviceAuthorization.mockRejectedValue(new Error("network down"));
+
+ expect(await performDeviceLogin(false)).toBeNull();
+ expect(mockPollDeviceToken).not.toHaveBeenCalled();
+ });
+
+ test("opens verification_uri_complete when openBrowser=true and stdin is non-TTY", async () => {
+ const originalIsTTY = process.stdin.isTTY;
+ Object.defineProperty(process.stdin, "isTTY", { value: false, configurable: true });
+ try {
+ mockStartDeviceAuthorization.mockResolvedValue(authorization);
+ mockPollDeviceToken.mockResolvedValue({
+ status: "approved",
+ tokens: { access_token: "t", token_type: "bearer" },
+ });
+
+ await performDeviceLogin(true);
+ expect(mockOpen).toHaveBeenCalledWith(authorization.verification_uri_complete);
+ } finally {
+ Object.defineProperty(process.stdin, "isTTY", { value: originalIsTTY, configurable: true });
+ }
+ });
+
+ test("skips opening a browser when openBrowser=false", async () => {
+ mockStartDeviceAuthorization.mockResolvedValue(authorization);
+ mockPollDeviceToken.mockResolvedValue({
+ status: "approved",
+ tokens: { access_token: "t", token_type: "bearer" },
+ });
+
+ await performDeviceLogin(false);
+ expect(mockOpen).not.toHaveBeenCalled();
+ });
+
+ test("defaults poll interval to 5s when server omits it (RFC 8628 §3.2)", async () => {
+ vi.useFakeTimers();
+ try {
+ mockStartDeviceAuthorization.mockResolvedValue({ ...authorization, interval: undefined });
+ mockPollDeviceToken.mockResolvedValueOnce({ status: "pending" }).mockResolvedValueOnce({
+ status: "approved",
+ tokens: { access_token: "t", token_type: "bearer" },
+ });
+
+ const pending = performDeviceLogin(false);
+ // Two 5s polls.
+ await vi.advanceTimersByTimeAsync(11_000);
+ const result = await pending;
+ expect(result).toBe("t");
+ expect(mockPollDeviceToken).toHaveBeenCalledTimes(2);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
});
diff --git a/packages/cli/src/__tests__/auth-utils.test.ts b/packages/cli/src/__tests__/auth-utils.test.ts
index f48f541b..5681ea35 100644
--- a/packages/cli/src/__tests__/auth-utils.test.ts
+++ b/packages/cli/src/__tests__/auth-utils.test.ts
@@ -29,6 +29,9 @@ import {
exchangeCodeForTokens,
buildAuthorizationUrl,
createCallbackServer,
+ shouldUseDeviceFlow,
+ startDeviceAuthorization,
+ pollDeviceToken,
type TokenData,
} from "../utils/auth.js";
@@ -421,3 +424,172 @@ describe("createCallbackServer", () => {
await closeAndWait(server.close);
});
});
+
+describe("shouldUseDeviceFlow", () => {
+ const originalEnv = { ...process.env };
+ const originalPlatform = Object.getOwnPropertyDescriptor(process, "platform")!;
+
+ beforeEach(() => {
+ delete process.env.SSH_CONNECTION;
+ delete process.env.SSH_CLIENT;
+ delete process.env.SSH_TTY;
+ delete process.env.DISPLAY;
+ delete process.env.WAYLAND_DISPLAY;
+ });
+
+ afterEach(() => {
+ process.env = { ...originalEnv };
+ Object.defineProperty(process, "platform", originalPlatform);
+ });
+
+ test("false on macOS with no SSH env", () => {
+ Object.defineProperty(process, "platform", { value: "darwin", configurable: true });
+ expect(shouldUseDeviceFlow()).toBe(false);
+ });
+
+ test.each(["SSH_CONNECTION", "SSH_CLIENT", "SSH_TTY"])("true when %s is set", (key) => {
+ Object.defineProperty(process, "platform", { value: "darwin", configurable: true });
+ process.env[key] = "anything";
+ expect(shouldUseDeviceFlow()).toBe(true);
+ });
+
+ test("true on Linux without DISPLAY / WAYLAND_DISPLAY", () => {
+ Object.defineProperty(process, "platform", { value: "linux", configurable: true });
+ expect(shouldUseDeviceFlow()).toBe(true);
+ });
+
+ test("false on Linux with DISPLAY set", () => {
+ Object.defineProperty(process, "platform", { value: "linux", configurable: true });
+ process.env.DISPLAY = ":0";
+ expect(shouldUseDeviceFlow()).toBe(false);
+ });
+
+ test("false on Linux with WAYLAND_DISPLAY set", () => {
+ Object.defineProperty(process, "platform", { value: "linux", configurable: true });
+ process.env.WAYLAND_DISPLAY = "wayland-0";
+ expect(shouldUseDeviceFlow()).toBe(false);
+ });
+});
+
+describe("startDeviceAuthorization", () => {
+ test("returns parsed response on 200", async () => {
+ const payload = {
+ device_code: "dc",
+ user_code: "ABCD-EFGH",
+ verification_uri: "https://t.example/oauth/device",
+ verification_uri_complete: "https://t.example/oauth/device?user_code=ABCD-EFGH",
+ expires_in: 600,
+ interval: 5,
+ };
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({ ok: true, json: () => Promise.resolve(payload) })
+ );
+ await expect(startDeviceAuthorization("https://t.example", "test-client")).resolves.toEqual(
+ payload
+ );
+ });
+
+ test("POSTs client_id as form-encoded body", async () => {
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: true,
+ json: () =>
+ Promise.resolve({
+ device_code: "",
+ user_code: "",
+ verification_uri: "",
+ expires_in: 0,
+ interval: 5,
+ }),
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ await startDeviceAuthorization("https://t.example", "test-client");
+ expect(fetchMock).toHaveBeenCalledWith(
+ "https://t.example/api/oauth/device/code",
+ expect.objectContaining({
+ method: "POST",
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
+ body: "client_id=test-client",
+ })
+ );
+ });
+
+ test("throws with the server-provided error_description", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({
+ ok: false,
+ json: () =>
+ Promise.resolve({ error: "invalid_request", error_description: "bad client_id" }),
+ })
+ );
+ await expect(startDeviceAuthorization("https://t", "bogus")).rejects.toThrow("bad client_id");
+ });
+});
+
+describe("pollDeviceToken", () => {
+ test("approved on 200 returns tokens", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({ access_token: "ctx7sk-x", token_type: "bearer" }),
+ })
+ );
+ const result = await pollDeviceToken("https://t", "c", "dc");
+ expect(result.status).toBe("approved");
+ expect(result.tokens?.access_token).toBe("ctx7sk-x");
+ });
+
+ test.each([
+ ["authorization_pending", "pending"],
+ ["slow_down", "slow_down"],
+ ["access_denied", "denied"],
+ ["expired_token", "expired"],
+ ] as const)("maps %s -> %s", async (serverError, expected) => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({
+ ok: false,
+ status: 400,
+ json: () => Promise.resolve({ error: serverError }),
+ })
+ );
+ expect((await pollDeviceToken("https://t", "c", "dc")).status).toBe(expected);
+ });
+
+ test("returns transient on a 5xx response", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({
+ ok: false,
+ status: 503,
+ json: () => Promise.resolve({ error: "server_error" }),
+ })
+ );
+ const result = await pollDeviceToken("https://t", "c", "dc");
+ expect(result.status).toBe("transient");
+ expect(result.errorMessage).toBeTruthy();
+ });
+
+ test("returns transient on a fetch network failure", async () => {
+ 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");
+ });
+
+ test("throws on unknown 4xx error code", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({
+ ok: false,
+ status: 400,
+ json: () =>
+ Promise.resolve({ error: "invalid_grant", error_description: "device_code malformed" }),
+ })
+ );
+ await expect(pollDeviceToken("https://t", "c", "dc")).rejects.toThrow("device_code malformed");
+ });
+});
diff --git a/packages/cli/src/commands/auth.ts b/packages/cli/src/commands/auth.ts
index ab787b67..951ab5a2 100644
--- a/packages/cli/src/commands/auth.ts
+++ b/packages/cli/src/commands/auth.ts
@@ -2,6 +2,7 @@ import { Command } from "commander";
import pc from "picocolors";
import ora from "ora";
import open from "open";
+import boxen from "boxen";
import {
generatePKCE,
generateState,
@@ -11,6 +12,10 @@ import {
clearTokens,
buildAuthorizationUrl,
getValidAccessToken,
+ shouldUseDeviceFlow,
+ startDeviceAuthorization,
+ pollDeviceToken,
+ DEFAULT_DEVICE_POLL_INTERVAL_SECONDS,
} from "../utils/auth.js";
import { trackEvent } from "../utils/tracking.js";
@@ -28,6 +33,7 @@ export function registerAuthCommands(program: Command): void {
.command("login")
.description("Log in to Context7")
.option("--no-browser", "Don't open browser automatically")
+ .option("--device", "Force device-code flow (use on SSH / headless hosts)")
.action(async (options) => {
await loginCommand(options);
});
@@ -47,7 +53,157 @@ export function registerAuthCommands(program: Command): void {
});
}
-export async function performLogin(openBrowser = true): Promise<string | null> {
+function renderDeviceCodeBox(
+ userCode: string,
+ verificationUri: string,
+ verificationUriComplete: string | undefined
+): string {
+ const codeLine = `${pc.dim("Your one-time code:")}\n\n ${pc.green(pc.bold(userCode))}`;
+ // Per RFC 8628 §3.3, even when verification_uri_complete is available we
+ // still show the bare verification_uri so users on screen readers / paper
+ // can type it manually.
+ const linkLine = verificationUriComplete
+ ? `${pc.dim("Open this link to approve:")}\n${pc.cyan(verificationUriComplete)}\n\n${pc.dim("Or visit")} ${pc.cyan(verificationUri)} ${pc.dim("and enter the code above.")}`
+ : `${pc.dim("Visit:")} ${pc.cyan(verificationUri)}`;
+ return boxen(`${codeLine}\n\n${linkLine}`, {
+ title: "Sign in to Context7",
+ titleAlignment: "left",
+ padding: 1,
+ margin: { top: 1, bottom: 1, left: 2, right: 2 },
+ borderStyle: "round",
+ borderColor: "gray",
+ });
+}
+
+/** Prints a prompt and resolves on the next keypress. No-op when stdin isn't a TTY. */
+function waitForEnter(prompt: string): Promise<void> {
+ if (!process.stdin.isTTY) return Promise.resolve();
+ return new Promise<void>((resolve) => {
+ process.stdout.write(` ${pc.dim(prompt)} `);
+ const onData = (chunk: Buffer) => {
+ // Ctrl-C
+ if (chunk[0] === 0x03) {
+ process.stdin.removeListener("data", onData);
+ process.stdin.setRawMode?.(false);
+ process.stdin.pause();
+ process.stdout.write("\n");
+ process.exit(130);
+ }
+ process.stdin.removeListener("data", onData);
+ process.stdin.setRawMode?.(false);
+ process.stdin.pause();
+ process.stdout.write("\n");
+ resolve();
+ };
+ process.stdin.setRawMode?.(true);
+ process.stdin.resume();
+ process.stdin.on("data", onData);
+ });
+}
+
+async function announceIdentity(accessToken: string): Promise<string> {
+ try {
+ const whoami = await fetchWhoami(accessToken);
+ const name = whoami.email || whoami.name;
+ if (!name) return "Login successful!";
+ const team = whoami.teamspace?.name;
+ return team
+ ? `Logged in as ${pc.bold(name)} ${pc.dim(`(${team})`)}`
+ : `Logged in as ${pc.bold(name)}`;
+ } catch {
+ return "Login successful!";
+ }
+}
+
+export async function performDeviceLogin(openBrowser = true): Promise<string | null> {
+ const spinner = ora("Preparing login...").start();
+
+ let authorization;
+ try {
+ authorization = await startDeviceAuthorization(baseUrl, CLI_CLIENT_ID);
+ } catch (error) {
+ spinner.fail(pc.red("Login failed"));
+ if (error instanceof Error) console.error(pc.red(error.message));
+ return null;
+ }
+
+ spinner.stop();
+
+ console.log(
+ renderDeviceCodeBox(
+ authorization.user_code,
+ authorization.verification_uri,
+ authorization.verification_uri_complete
+ )
+ );
+
+ const target = authorization.verification_uri_complete ?? authorization.verification_uri;
+ if (openBrowser) {
+ await waitForEnter("Press Enter to open the browser, or Ctrl-C to quit...");
+ try {
+ await open(target);
+ } catch {
+ console.log(pc.dim(` Couldn't open a browser — visit the link above manually.`));
+ }
+ } else {
+ console.log(pc.dim(" Open the link above in any browser to continue."));
+ console.log("");
+ }
+
+ const waitingSpinner = ora({ text: "Waiting for authorization...", indent: 2 }).start();
+
+ const deadline = Date.now() + authorization.expires_in * 1000;
+ let intervalMs = (authorization.interval ?? DEFAULT_DEVICE_POLL_INTERVAL_SECONDS) * 1000;
+
+ while (Date.now() < deadline) {
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
+ try {
+ const result = await pollDeviceToken(baseUrl, CLI_CLIENT_ID, authorization.device_code);
+ if (result.status === "approved" && result.tokens) {
+ saveTokens(result.tokens);
+ const successText = await announceIdentity(result.tokens.access_token);
+ waitingSpinner.succeed(pc.green(successText));
+ return result.tokens.access_token;
+ }
+ if (result.status === "slow_down") {
+ intervalMs += 5000;
+ continue;
+ }
+ if (result.status === "denied") {
+ waitingSpinner.fail(pc.red("Authorization denied."));
+ return null;
+ }
+ if (result.status === "expired") {
+ waitingSpinner.fail(pc.red("Code expired. Run login again."));
+ return null;
+ }
+ if (result.status === "transient") {
+ // RFC 8628 §3.5: client MUST unilaterally reduce polling frequency on
+ // connection timeout. Apply +5s like slow_down so a flaky network or
+ // 5xx burst doesn't keep hitting at the original cadence.
+ intervalMs += 5000;
+ continue;
+ }
+ // pending — keep polling at the current cadence.
+ } catch (error) {
+ waitingSpinner.fail(pc.red("Login failed"));
+ if (error instanceof Error) console.error(pc.red(error.message));
+ return null;
+ }
+ }
+
+ waitingSpinner.fail(pc.red("Code expired without approval."));
+ return null;
+}
+
+export async function performLogin(
+ openBrowser = true,
+ forceDevice = false
+): Promise<string | null> {
+ if (forceDevice || shouldUseDeviceFlow()) {
+ return performDeviceLogin(openBrowser);
+ }
+
const spinner = ora("Preparing login...").start();
try {
@@ -114,7 +270,7 @@ export async function performLogin(openBrowser = true): Promise<string | null> {
}
}
-async function loginCommand(options: { browser: boolean }): Promise<void> {
+async function loginCommand(options: { browser: boolean; device?: boolean }): Promise<void> {
trackEvent("command", { name: "login" });
const existingToken = await getValidAccessToken();
if (existingToken) {
@@ -124,7 +280,7 @@ async function loginCommand(options: { browser: boolean }): Promise<void> {
}
clearTokens();
- const token = await performLogin(options.browser);
+ const token = await performLogin(options.browser, options.device ?? false);
if (!token) {
process.exit(1);
}
diff --git a/packages/cli/src/utils/auth.ts b/packages/cli/src/utils/auth.ts
index 8302f636..02abf1f5 100644
--- a/packages/cli/src/utils/auth.ts
+++ b/packages/cli/src/utils/auth.ts
@@ -312,3 +312,115 @@ export function buildAuthorizationUrl(
url.searchParams.set("response_type", "code");
return url.toString();
}
+
+export interface DeviceAuthorizationResponse {
+ device_code: string;
+ user_code: string;
+ verification_uri: string;
+ verification_uri_complete?: string;
+ expires_in: number;
+ /** Optional per RFC 8628 §3.2; clients MUST default to 5s when absent. */
+ interval?: number;
+}
+
+const DEVICE_CODE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
+
+/** RFC 8628 §3.2 default poll interval when the server omits `interval`. */
+export const DEFAULT_DEVICE_POLL_INTERVAL_SECONDS = 5;
+
+/** Heuristic: prefer device flow on SSH and headless Linux. False positives are fine — device flow works locally too. */
+export function shouldUseDeviceFlow(): boolean {
+ if (process.env.SSH_CONNECTION || process.env.SSH_CLIENT || process.env.SSH_TTY) return true;
+ if (process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) {
+ return true;
+ }
+ return false;
+}
+
+export async function startDeviceAuthorization(
+ baseUrl: string,
+ clientId: string
+): Promise<DeviceAuthorizationResponse> {
+ // Hostname is shown on the server's verification page so the user can confirm
+ // that the device they're authorizing matches the one running the CLI
+ // (RFC 8628 §5.4 phishing resistance). Best-effort; falls back to "unknown".
+ const params = new URLSearchParams({ client_id: clientId });
+ try {
+ const hostname = os.hostname();
+ if (hostname) params.set("hostname", hostname);
+ } catch {
+ // 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;
+}
+
+export interface PollDeviceTokenResult {
+ status: "approved" | "pending" | "slow_down" | "denied" | "expired" | "transient";
+ tokens?: TokenData;
+ errorMessage?: string;
+}
+
+export async function pollDeviceToken(
+ baseUrl: string,
+ clientId: string,
+ deviceCode: string
+): 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({
+ grant_type: DEVICE_CODE_GRANT,
+ device_code: deviceCode,
+ client_id: clientId,
+ }).toString(),
+ });
+ } catch (error) {
+ // Network blip — keep polling.
+ return {
+ status: "transient",
+ errorMessage: error instanceof Error ? error.message : "network error",
+ };
+ }
+
+ if (response.ok) {
+ const tokens = (await response.json()) as TokenData;
+ return { status: "approved", tokens };
+ }
+
+ // Treat any 5xx as transient so a flaky backend doesn't end the user's session.
+ if (response.status >= 500) {
+ const err = (await response.json().catch(() => ({}))) as TokenErrorResponse;
+ return {
+ status: "transient",
+ errorMessage: err.error_description || err.error || `HTTP ${response.status}`,
+ };
+ }
+
+ const err = (await response.json().catch(() => ({}))) as TokenErrorResponse;
+ switch (err.error) {
+ case "authorization_pending":
+ return { status: "pending" };
+ case "slow_down":
+ return { status: "slow_down" };
+ case "access_denied":
+ return { status: "denied" };
+ case "expired_token":
+ return { status: "expired" };
+ default:
+ throw new Error(err.error_description || err.error || "Device token poll failed");
+ }
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 304b5133..f6bd39ee 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -54,6 +54,9 @@ importers:
'@inquirer/prompts':
specifier: ^8.2.0
version: 8.2.0(@types/[email protected])
+ boxen:
+ specifier: ^8.0.1
+ version: 8.0.1
commander:
specifier: ^13.1.0
version: 13.1.0
@@ -996,30 +999,35 @@ packages:
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@mariozechner/[email protected]':
resolution: {integrity: sha512-JlVjxxw0GbGC0djXYWRIqyteO3J1KZ/QG3udlEFaOD5TLOM1FnmXXAPDQBqr+aBVr720ef9K00dirYnJ0LDCtw==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@mariozechner/[email protected]':
resolution: {integrity: sha512-4t8BUi5zZ+L77otFQVnVSlaTyAX4TVk9EqQm4syMrEQp96trFEHEwwNHcNEBGzYv5+K7mxay50TthYkz47OWzQ==}
engines: {node: '>= 10'}
cpu: [riscv64]
os: [linux]
+ libc: [glibc]
'@mariozechner/[email protected]':
resolution: {integrity: sha512-trtPwcNLW37irwQCJLtCxLw757jjJZk3TSnY/MU9bhtWtA3K9b/eLW0e4RGhUXDoFRds9opNWWaUDuFLa8dm0w==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@mariozechner/[email protected]':
resolution: {integrity: sha512-WfnzIvOCCWQiN0MmltCEo6cLceUDbYe+I7xyFZjaps5A+2Op/M2CY7Rey+C4ucQhrvmpoHmTSFgY9ODWk7snoA==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
+ libc: [musl]
'@mariozechner/[email protected]':
resolution: {integrity: sha512-+8+1aHYsBPUjmW3otmWlg+Hijt0iJvoBBs5e0mxFeUd4gDaKMB8Bn6x7c6KVtscg7E5j5NFXnwQqNSIAO4p8zQ==}
@@ -1137,56 +1145,67 @@ packages:
resolution: {integrity: sha512-k9oD15soC/Ln6d2Wv/JOFPzZXIAIFLp6B+i14KhxAfnq76ajt0EhYc5YPeX6W1xJkAdItcVT+JhKl1QZh44/qw==}
cpu: [arm]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-vTNlKq+N6CK/8UktsrFuc+/7NlEYVxgaEgRXVUVK258Z5ymho29skzW1sutgYjqNnquGwVUObAaxae8rZ6YMhg==}
cpu: [arm]
os: [linux]
+ libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-RGrFLWgMhSxRs/EWJMIFM1O5Mzuz3Xy3/mnxJp/5cVhZ2XoCAxJnmNsEyeMJtpK+wu0FJFWz+QF4mjCA7AUQ3w==}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-kASyvfBEWYPEwe0Qv4nfu6pNkITLTb32p4yTgzFCocHnJLAHs+9LjUu9ONIhvfT/5lv4YS5muBHyuV84epBo/A==}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-JiuKcp2teLJwQ7vkJ95EwESWkNRFJD7TQgYmCnrPtlu50b4XvT5MOmurWNrCj3IFdyjBQ5p9vnrX4JM6I8OE7g==}
cpu: [loong64]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-EoGSa8nd6d3T7zLuqdojxC20oBfNT8nexBbB/rkxgKj5T5vhpAQKKnD+h3UkoMuTyXkP5jTjK/ccNRmQrPNDuw==}
cpu: [ppc64]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-4s+Wped2IHXHPnAEbIB0YWBv7SDohqxobiiPA1FIWZpX+w9o2i4LezzH/NkFUl8LRci/8udci6cLq+jJQlh+0g==}
cpu: [riscv64]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-68k2g7+0vs2u9CxDt5ktXTngsxOQkSEV/xBbwlqYcUrAVh6P9EgMZvFsnHy4SEiUl46Xf0IObWVbMvPrr2gw8A==}
cpu: [riscv64]
os: [linux]
+ libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-VYsFMpULAz87ZW6BVYw3I6sWesGpsP9OPcyKe8ofdg9LHxSbRMd7zrVrr5xi/3kMZtpWL/wC+UIJWJYVX5uTKg==}
cpu: [s390x]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-3EhFi1FU6YL8HTUJZ51imGJWEX//ajQPfqWLI3BQq4TlvHy4X0MOr5q3D2Zof/ka0d5FNdPwZXm3Yyib/UEd+w==}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-eoROhjcc6HbZCJr+tvVT8X4fW3/5g/WkGvvmwz/88sDtSJzO7r/blvoBDgISDiCjDRZmHpwud7h+6Q9JxFwq1Q==}
cpu: [x64]
os: [linux]
+ libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-OueLAWgrNSPGAdUdIjSWXw+u/02BRTcnfw9PN41D2vq/JSEPnJnVuBgw18VkN8wcd4fjUs+jFHVM4t9+kBSNLw==}
@@ -1475,6 +1494,9 @@ packages:
resolution: {integrity: sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==}
+ resolution: {integrity: sha512-IOfwwBF5iczOjp/WeY4YxyjqAFMQoZufdQWDd19SEExbVLNXqvpzSJ/M7Za4/sCPmQ0+GRquoA7bGcINcxew6w==}
+
resolution: {integrity: sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw==}
engines: {node: '>=6'}
@@ -1539,6 +1561,10 @@ packages:
resolution: {integrity: sha512-tzPjzCxygAKWFOJP011oxFHs57HzIhOEracIgAePE4pqB3LikALKnSzUyU4MGs9/iCEUuHlAJTjTc5M+u7YEGg==}
+ resolution: {integrity: sha512-F3PH5k5juxom4xktynS7MoFY+NUWH5LC4CnH11YB8NPew+HLpmBLCybSAEyb2F+4pRXhuhWqFesoQd6DAyc2hw==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==}
@@ -1586,6 +1612,10 @@ packages:
resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==}
engines: {node: '>=6'}
+ resolution: {integrity: sha512-8WB3Jcas3swSvjIeA2yvCJ+Miyz5l1ZmB6HFb9R1317dt9LCQoswg/BGrmAmkWVEszSrrg4RwmO46qIm2OEnSA==}
+ engines: {node: '>=16'}
+
resolution: {integrity: sha512-p4Z49OGG5W/WBCPSS/dH3jQ73kD6tiMmUM+bckNK6Jr5JHMG3k9bg/BvKR8lKmtVBKmOiuVaV2ws8s9oSbwysg==}
engines: {node: '>=18'}
@@ -1609,6 +1639,10 @@ packages:
resolution: {integrity: sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-/lzGpEWL/8PfI0BmBOPRwp0c/wFNX1RdUML3jK/RcSBA9T8mZDdQpqYBKtCFTOfQbwPqWEOpjqW+Fnayc0969g==}
+ engines: {node: '>=10'}
+
resolution: {integrity: sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw==}
engines: {node: '>=18'}
@@ -1735,6 +1769,9 @@ packages:
resolution: {integrity: sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==}
+ resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==}
+
resolution: {integrity: sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==}
engines: {node: '>= 0.8'}
@@ -2130,6 +2167,10 @@ packages:
resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==}
engines: {node: '>=0.10.0'}
+ resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==}
+ engines: {node: '>=8'}
+
resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==}
engines: {node: '>=0.10.0'}
@@ -2729,6 +2770,10 @@ packages:
resolution: {integrity: sha512-UhDfHmA92YAlNnCfhmq0VeNL5bDbiZGg7sZ2IvPsXubGkiNa9EC+tUTsjBRsYUAz87btI6/1wf4XoVvQ3uRnmQ==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==}
+ engines: {node: '>=8'}
+
resolution: {integrity: sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==}
engines: {node: '>=18'}
@@ -2849,6 +2894,10 @@ packages:
resolution: {integrity: sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==}
engines: {node: '>= 0.8.0'}
+ resolution: {integrity: sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA==}
+ engines: {node: '>=16'}
+
resolution: {integrity: sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==}
engines: {node: '>= 0.6'}
@@ -2994,6 +3043,10 @@ packages:
engines: {node: '>=8'}
hasBin: true
+ resolution: {integrity: sha512-c9bZp7b5YtRj2wOe6dlj32MK+Bx/M/d+9VB2SHM1OtsUHR0aV0tdP6DWh/iMt0kWi1t5g1Iudu6hQRNd1A4PVA==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==}
engines: {node: '>=0.10.0'}
@@ -4464,6 +4517,10 @@ snapshots:
json-schema-traverse: 1.0.0
require-from-string: 2.0.2
+ dependencies:
+ string-width: 4.2.3
+
@@ -4518,6 +4575,17 @@ snapshots:
+ dependencies:
+ ansi-align: 3.0.1
+ camelcase: 8.0.0
+ chalk: 5.6.2
+ cli-boxes: 3.0.0
+ string-width: 7.2.0
+ type-fest: 4.41.0
+ widest-line: 5.0.0
+ wrap-ansi: 9.0.2
+
dependencies:
balanced-match: 1.0.2
@@ -4562,6 +4630,8 @@ snapshots:
+
@@ -4579,6 +4649,8 @@ snapshots:
+
dependencies:
restore-cursor: 5.1.0
@@ -4667,6 +4739,8 @@ snapshots:
+
@@ -5155,6 +5229,8 @@ snapshots:
+
dependencies:
is-extglob: 2.1.1
@@ -5715,10 +5791,16 @@ snapshots:
+ dependencies:
+ emoji-regex: 8.0.0
+ is-fullwidth-code-point: 3.0.0
+ strip-ansi: 6.0.1
+
dependencies:
emoji-regex: 10.6.0
- get-east-asian-width: 1.4.0
+ get-east-asian-width: 1.6.0
strip-ansi: 7.1.2
@@ -5837,6 +5919,8 @@ snapshots:
dependencies:
prelude-ls: 1.2.1
+
dependencies:
content-type: 1.0.5
@@ -6052,6 +6136,10 @@ snapshots:
siginfo: 2.0.0
stackback: 0.0.2
+ dependencies:
+ string-width: 7.2.0
+