Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
13 changes: 6 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
37 changes: 34 additions & 3 deletions src/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,7 @@ export interface BrowserLoginOptions {
port?: number;
timeoutMs?: number;
onReady?: (details: BrowserLoginStart) => void;
signal?: AbortSignal;
}

export interface BrowserLoginResult {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -576,10 +589,21 @@ export type DeviceLoginOptions = {
clientId?: string;
onPrompt?: (prompt: DeviceLoginPrompt) => void;
sleep?: (ms: number) => Promise<void>;
signal?: AbortSignal;
};

const defaultSleep = (ms: number) =>
new Promise<void>((resolve) => setTimeout(resolve, ms));
const defaultSleep = (ms: number, signal?: AbortSignal) =>
new Promise<void>((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
Expand All @@ -594,8 +618,13 @@ export async function loginWithDeviceCode(
"Device login is not configured yet. Use `s1 login` or `s1 config set-key <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.");
}
Expand All @@ -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.");
}
Expand All @@ -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, {
Expand Down
96 changes: 67 additions & 29 deletions src/commands/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 <seconds>", "wait timeout in seconds", "300")
.option("--port <number>", "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");
Expand All @@ -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<void>((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<T>(
tasks: Array<(signal: AbortSignal) => Promise<T>>
): Promise<T> {
const controller = new AbortController();
const errors: Error[] = [];
try {
return await new Promise<T>((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<void> {
console.log(chalk.dim("Validating OAuth access token..."));
await validateCredential(oauth.accessToken);
Expand Down
18 changes: 18 additions & 0 deletions tests/device-login.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});