From c72467bb30581dc5f911683ce2eb5963a2fb7582 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 03:43:32 +0000 Subject: [PATCH] s1 login: wait for browser callback and device code together Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DuYf7wb1EAoffTQ9poskFK --- CHANGELOG.md | 2 +- README.md | 13 +++-- src/auth.ts | 37 ++++++++++++-- src/commands/login.ts | 96 ++++++++++++++++++++++++++----------- tests/device-login.test.mjs | 18 +++++++ 5 files changed, 126 insertions(+), 40 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2620258..0ac361f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased -Adds `s1 login --device` for signing in when the browser is on another device (SSH, servers, containers). The CLI shows a URL and a short code; approve it in a browser on any device and the CLI receives the tokens (OAuth 2.0 Device Authorization Grant). Plain `s1 login` in an SSH session now suggests `--device`. +`s1 login` now works when the browser is on another device (SSH, servers, containers). It opens your browser as before and also prints a URL and short code; approve the code in a browser on any device and the CLI receives the tokens (OAuth 2.0 Device Authorization Grant). Whichever finishes first is used. `s1 login --device` uses only the short-code flow. ## 2.3.0 - 2026-11-05 diff --git a/README.md b/README.md index 7e05e96..10db668 100644 --- a/README.md +++ b/README.md @@ -318,18 +318,17 @@ Do not include credentials or private data in the message. ### login -Authorize in your browser with OAuth 2.1 and PKCE. +Sign in with OAuth. `s1 login` opens your browser and, at the same time, +prints a URL and short code for signing in from another device. Whichever you +finish first is used, so the same command works on your laptop and over SSH, +on servers and in containers. ```bash s1 login -s1 login --no-browser -s1 login --device +s1 login --no-browser # don't open a browser; print both URLs +s1 login --device # only the short-code flow ``` -`--device` is for SSH sessions, servers and containers where the browser is on -another device. The CLI prints a URL and a short code; open the URL on any -phone or computer, sign in, confirm the code, and the CLI saves the tokens. - ### config Manage CLI configuration. diff --git a/src/auth.ts b/src/auth.ts index 68fb404..2c14f71 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -378,6 +378,7 @@ export interface BrowserLoginOptions { port?: number; timeoutMs?: number; onReady?: (details: BrowserLoginStart) => void; + signal?: AbortSignal; } export interface BrowserLoginResult { @@ -477,6 +478,18 @@ export async function loginWithBrowser( } }); + if (options.signal) { + if (options.signal.aborted) { + queueMicrotask(() => finish(new Error("Browser login cancelled."))); + } else { + options.signal.addEventListener( + "abort", + () => finish(new Error("Browser login cancelled.")), + { once: true } + ); + } + } + server.on("error", (error) => { finish( error instanceof Error @@ -576,10 +589,21 @@ export type DeviceLoginOptions = { clientId?: string; onPrompt?: (prompt: DeviceLoginPrompt) => void; sleep?: (ms: number) => Promise; + signal?: AbortSignal; }; -const defaultSleep = (ms: number) => - new Promise((resolve) => setTimeout(resolve, ms)); +const defaultSleep = (ms: number, signal?: AbortSignal) => + new Promise((resolve) => { + const timer = setTimeout(resolve, ms); + signal?.addEventListener( + "abort", + () => { + clearTimeout(timer); + resolve(); + }, + { once: true } + ); + }); /** * OAuth 2.0 Device Authorization Grant (RFC 8628): show a short code, let the @@ -594,8 +618,13 @@ export async function loginWithDeviceCode( "Device login is not configured yet. Use `s1 login` or `s1 config set-key `." ); } - const sleep = options.sleep ?? defaultSleep; + const signal = options.signal; + const sleep = options.sleep ?? ((ms: number) => defaultSleep(ms, signal)); + const throwIfCancelled = () => { + if (signal?.aborted) throw new Error("Device login cancelled."); + }; const metadata = await discoverAuthorizationServer(); + throwIfCancelled(); if (!metadata.device_authorization_endpoint) { throw new Error("The authorization server does not support device login."); } @@ -611,6 +640,7 @@ export async function loginWithDeviceCode( }), "Device authorization" ); + throwIfCancelled(); if (!(device.device_code && device.user_code && device.verification_uri)) { throw new Error("Device authorization response is missing required fields."); } @@ -633,6 +663,7 @@ export async function loginWithDeviceCode( while (Date.now() < deadline) { await sleep(intervalMs); + throwIfCancelled(); let response: Response; try { response = await fetch(metadata.token_endpoint, { diff --git a/src/commands/login.ts b/src/commands/login.ts index f025b81..e87aa16 100644 --- a/src/commands/login.ts +++ b/src/commands/login.ts @@ -14,13 +14,13 @@ function parseInteger(value: string, label: string): number { export function registerLoginCommand(program: Command): void { program .command("login") - .description("Authorize with OAuth 2.1 in your browser") + .description("Sign in with your browser, on this machine or any other device") .option("--no-browser", "print the authorization URL instead of opening a browser") .option("--timeout ", "wait timeout in seconds", "300") .option("--port ", "callback port (default: random)") .option( "--device", - "sign in with a short code from any device (for SSH, servers, and containers)" + "only use the short-code flow (no local callback or browser)" ) .action(async (opts) => { const timeoutSeconds = parseInteger(opts.timeout, "timeout"); @@ -46,39 +46,77 @@ export function registerLoginCommand(program: Command): void { return; } - if (isRemoteSession()) { - console.log( - chalk.yellow( - "Looks like an SSH session. If the browser is on another device, use `s1 login --device`." - ) - ); - } - - const result = await loginWithBrowser({ - openBrowser: opts.browser, - port, - timeoutMs: timeoutSeconds * 1000, - onReady: ({ authUrl, callbackUrl, browserOpened }) => { - console.log(`${chalk.dim("Callback:")} ${callbackUrl}`); - if (browserOpened) { - console.log(chalk.green("Opened your browser. Complete sign-in to continue.")); - } else { - console.log(chalk.yellow("Open this URL to continue sign-in:")); - console.log(authUrl); - } - }, + // Wait for whichever finishes first: the browser callback on this + // machine, or approval of the device code from any other device. + // The device hint prints after the browser line so the output reads in order. + let markBrowserReady: () => void = () => {}; + const browserReady = new Promise((resolve) => { + markBrowserReady = resolve; }); - - await finishLogin(result.oauth); + const oauth = await firstSuccessful([ + (signal) => + loginWithBrowser({ + openBrowser: opts.browser, + port, + timeoutMs: timeoutSeconds * 1000, + signal, + onReady: ({ authUrl, browserOpened }) => { + if (browserOpened) { + console.log(chalk.green("Opened your browser. Complete sign-in to continue.")); + } else { + console.log("Open this URL in a browser on this machine:"); + console.log(` ${chalk.cyan(authUrl)}`); + } + markBrowserReady(); + }, + }) + .then((result) => result.oauth) + .finally(() => markBrowserReady()), + (signal) => + loginWithDeviceCode({ + timeoutMs: timeoutSeconds * 1000, + signal, + onPrompt: ({ userCode, verificationUri, verificationUriComplete }) => { + void browserReady.then(() => { + console.log( + `${chalk.yellow("Browser on another device?")} Open this URL there and sign in:` + ); + console.log(` ${chalk.cyan(verificationUriComplete ?? verificationUri)}`); + console.log(`Confirm this code: ${chalk.bold(userCode)}`); + }); + }, + }), + ]); + await finishLogin(oauth); }); } -function isRemoteSession(): boolean { - return Boolean( - process.env.SSH_CONNECTION || process.env.SSH_CLIENT || process.env.SSH_TTY - ); +/** + * Runs the login methods side by side and resolves with the first one that + * succeeds, cancelling the rest. Rejects only when every method fails. + */ +async function firstSuccessful( + tasks: Array<(signal: AbortSignal) => Promise> +): Promise { + const controller = new AbortController(); + const errors: Error[] = []; + try { + return await new Promise((resolve, reject) => { + let pending = tasks.length; + for (const task of tasks) { + task(controller.signal).then(resolve, (error: unknown) => { + errors.push(error instanceof Error ? error : new Error(String(error))); + pending -= 1; + if (pending === 0) reject(errors[0]); + }); + } + }); + } finally { + controller.abort(); + } } + async function finishLogin(oauth: OAuthConfig): Promise { console.log(chalk.dim("Validating OAuth access token...")); await validateCredential(oauth.accessToken); diff --git a/tests/device-login.test.mjs b/tests/device-login.test.mjs index 87d3563..4ed990d 100644 --- a/tests/device-login.test.mjs +++ b/tests/device-login.test.mjs @@ -102,3 +102,21 @@ test("device login explains when no client id is configured", async () => { await assert.rejects(loginWithDeviceCode({ clientId: "" }), /not configured/); } }); + +test("device login stops polling when cancelled", async () => { + state.script = [[400, { error: "authorization_pending" }]]; + const controller = new AbortController(); + let polls = 0; + await assert.rejects( + loginWithDeviceCode({ + clientId: "public-client", + signal: controller.signal, + sleep: async () => { + polls += 1; + if (polls === 2) controller.abort(); + }, + }), + /cancelled/ + ); + assert.equal(calls.token.length, 1); +});