From a08b92d38b068acea8690c209eb5610954a360c2 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 03:40:27 +0000 Subject: [PATCH 1/2] Add s1 login --device (OAuth device authorization grant) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DuYf7wb1EAoffTQ9poskFK --- src/auth.ts | 138 ++++++++++++++++++++++++++++++++++++ src/commands/login.ts | 70 ++++++++++++++---- tests/device-login.test.mjs | 104 +++++++++++++++++++++++++++ 3 files changed, 297 insertions(+), 15 deletions(-) create mode 100644 tests/device-login.test.mjs diff --git a/src/auth.ts b/src/auth.ts index 45e26db..f872bd3 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -18,6 +18,12 @@ const OAUTH_SCOPES = "openid profile email offline_access"; // Names the CLI as the source of sign-ups that start from `s1 login`. const OAUTH_SOURCE = "search1api-cli"; const EXPIRY_SKEW_MS = 60_000; +const DEVICE_CODE_GRANT = "urn:ietf:params:oauth:grant-type:device_code"; +// Public OAuth application (no secret) with Device Authorization Grant enabled. +// Dynamically registered clients cannot use the device grant, so this one is +// created once in the Clerk Dashboard and ships with the CLI. +export const DEVICE_CLIENT_ID = + process.env.SEARCH1API_OAUTH_DEVICE_CLIENT_ID ?? ""; const SUCCESS_HTML = ` @@ -51,6 +57,7 @@ type AuthorizationServerMetadata = { registration_endpoint?: string | null; code_challenge_methods_supported?: string[]; grant_types_supported?: string[]; + device_authorization_endpoint?: string | null; }; type ClientRegistrationResponse = { @@ -541,6 +548,137 @@ export async function loginWithBrowser( }); } +type DeviceAuthorizationResponse = { + device_code: string; + user_code: string; + verification_uri: string; + verification_uri_complete?: string; + expires_in: number; + interval?: number; +}; + +type OAuthErrorResponse = { + error?: string; + error_description?: string; +}; + +export type DeviceLoginPrompt = { + userCode: string; + verificationUri: string; + verificationUriComplete?: string; + expiresInSeconds: number; + browserOpened: boolean; +}; + +export type DeviceLoginOptions = { + openBrowser?: boolean; + timeoutMs?: number; + clientId?: string; + onPrompt?: (prompt: DeviceLoginPrompt) => void; + sleep?: (ms: number) => Promise; +}; + +const defaultSleep = (ms: number) => + new Promise((resolve) => setTimeout(resolve, ms)); + +/** + * OAuth 2.0 Device Authorization Grant (RFC 8628): show a short code, let the + * user approve it in a browser on any device, and poll for tokens. + */ +export async function loginWithDeviceCode( + options: DeviceLoginOptions = {} +): Promise { + const clientId = options.clientId ?? DEVICE_CLIENT_ID; + if (!clientId) { + throw new Error( + "Device login is not configured yet. Use `s1 login` or `s1 config set-key `." + ); + } + const sleep = options.sleep ?? defaultSleep; + const metadata = await discoverAuthorizationServer(); + if (!metadata.device_authorization_endpoint) { + throw new Error("The authorization server does not support device login."); + } + + const device = await readJson( + await fetch(metadata.device_authorization_endpoint, { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ + client_id: clientId, + scope: OAUTH_SCOPES, + }), + }), + "Device authorization" + ); + if (!(device.device_code && device.user_code && device.verification_uri)) { + throw new Error("Device authorization response is missing required fields."); + } + + const browserUrl = device.verification_uri_complete ?? device.verification_uri; + const browserOpened = + options.openBrowser === true ? openBrowser(browserUrl) : false; + options.onPrompt?.({ + userCode: device.user_code, + verificationUri: device.verification_uri, + verificationUriComplete: device.verification_uri_complete, + expiresInSeconds: device.expires_in, + browserOpened, + }); + + const expiresMs = (device.expires_in ?? 600) * 1000; + const deadline = + Date.now() + Math.min(expiresMs, options.timeoutMs ?? expiresMs); + let intervalMs = Math.max(1, device.interval ?? 5) * 1000; + + while (Date.now() < deadline) { + await sleep(intervalMs); + let response: Response; + try { + response = await fetch(metadata.token_endpoint, { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ + grant_type: DEVICE_CODE_GRANT, + device_code: device.device_code, + client_id: clientId, + }), + }); + } catch { + // Network blips: keep polling while the code is still valid. + continue; + } + if (response.ok) { + const token = (await response.json()) as TokenResponse; + return oauthConfigFromToken(token, metadata, clientId); + } + + const text = await response.text(); + let body: OAuthErrorResponse = {}; + try { + body = JSON.parse(text) as OAuthErrorResponse; + } catch { + // Non-JSON error bodies fall through to the generic error below. + } + switch (body.error) { + case "authorization_pending": + continue; + case "slow_down": + intervalMs += 5000; + continue; + case "access_denied": + throw new Error("Login was denied in the browser."); + case "expired_token": + throw new Error("The login code expired. Run `s1 login --device` again."); + default: + throw new Error( + `Device login failed (${response.status}): ${body.error_description ?? body.error ?? text}` + ); + } + } + throw new Error("Timed out waiting for device login. Run `s1 login --device` again."); +} + export async function refreshOAuthConfig(oauth: OAuthConfig): Promise { if (!oauth.refreshToken) { throw new Error("OAuth access expired and no refresh token is available. Run `s1 login` again."); diff --git a/src/commands/login.ts b/src/commands/login.ts index b678698..f025b81 100644 --- a/src/commands/login.ts +++ b/src/commands/login.ts @@ -1,7 +1,7 @@ import chalk from "chalk"; import { Command } from "commander"; -import { loginWithBrowser, validateCredential } from "../auth.js"; -import { getConfigFilePath, saveOAuthConfig } from "../config.js"; +import { loginWithBrowser, loginWithDeviceCode, validateCredential } from "../auth.js"; +import { getConfigFilePath, saveOAuthConfig, type OAuthConfig } from "../config.js"; function parseInteger(value: string, label: string): number { const parsed = Number.parseInt(value, 10); @@ -18,12 +18,42 @@ export function registerLoginCommand(program: Command): void { .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)" + ) .action(async (opts) => { const timeoutSeconds = parseInteger(opts.timeout, "timeout"); const port = opts.port ? parseInteger(opts.port, "port") : undefined; console.log(chalk.bold.blue("Search1API Login")); + if (opts.device) { + const oauth = await loginWithDeviceCode({ + openBrowser: false, + timeoutMs: timeoutSeconds * 1000, + onPrompt: ({ userCode, verificationUri, verificationUriComplete }) => { + console.log("Open this URL on any device and sign in:"); + console.log(` ${chalk.cyan(verificationUriComplete ?? verificationUri)}`); + console.log(`Confirm this code: ${chalk.bold(userCode)}`); + if (verificationUriComplete) { + console.log(chalk.dim(`Or go to ${verificationUri} and enter the code.`)); + } + console.log(chalk.dim("Waiting for approval...")); + }, + }); + await finishLogin(oauth); + 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, @@ -39,19 +69,29 @@ export function registerLoginCommand(program: Command): void { }, }); - console.log(chalk.dim("Validating OAuth access token...")); - await validateCredential(result.oauth.accessToken); - saveOAuthConfig(result.oauth); + await finishLogin(result.oauth); + }); +} + +function isRemoteSession(): boolean { + return Boolean( + process.env.SSH_CONNECTION || process.env.SSH_CLIENT || process.env.SSH_TTY + ); +} - console.log(chalk.green("Authorization complete. OAuth tokens saved.")); - console.log(`${chalk.dim("Config file:")} ${getConfigFilePath()}`); +async function finishLogin(oauth: OAuthConfig): Promise { + console.log(chalk.dim("Validating OAuth access token...")); + await validateCredential(oauth.accessToken); + saveOAuthConfig(oauth); - if (process.env.SEARCH1API_KEY) { - console.log( - chalk.yellow( - "Note: SEARCH1API_KEY is set in your environment and will override the saved key." - ) - ); - } - }); + console.log(chalk.green("Authorization complete. OAuth tokens saved.")); + console.log(`${chalk.dim("Config file:")} ${getConfigFilePath()}`); + + if (process.env.SEARCH1API_KEY) { + console.log( + chalk.yellow( + "Note: SEARCH1API_KEY is set in your environment and will override the saved key." + ) + ); + } } diff --git a/tests/device-login.test.mjs b/tests/device-login.test.mjs new file mode 100644 index 0000000..87d3563 --- /dev/null +++ b/tests/device-login.test.mjs @@ -0,0 +1,104 @@ +import assert from "node:assert/strict"; +import { createServer } from "node:http"; +import test from "node:test"; + +const state = { script: [] }; + +function startMockAuthServer() { + const calls = { device: [], token: [] }; + const server = createServer(async (req, res) => { + let body = ""; + for await (const chunk of req) body += chunk; + const base = `http://127.0.0.1:${server.address().port}`; + const send = (status, json) => { + res.writeHead(status, { "Content-Type": "application/json" }); + res.end(JSON.stringify(json)); + }; + if (req.url === "/.well-known/oauth-protected-resource") { + return send(200, { resource: base, authorization_servers: [base] }); + } + if (req.url === "/.well-known/oauth-authorization-server") { + return send(200, { + issuer: base, + authorization_endpoint: `${base}/oauth/authorize`, + token_endpoint: `${base}/oauth/token`, + device_authorization_endpoint: `${base}/oauth/device_authorization`, + }); + } + if (req.url === "/oauth/device_authorization") { + calls.device.push(new URLSearchParams(body)); + return send(200, { + device_code: "secret-device-code", + user_code: "BCDF-GHJK", + verification_uri: `${base}/device`, + verification_uri_complete: `${base}/device?user_code=BCDF-GHJK`, + expires_in: 600, + interval: 1, + }); + } + if (req.url === "/oauth/token") { + calls.token.push(new URLSearchParams(body)); + const script = state.script; + const [status, json] = script[Math.min(calls.token.length - 1, script.length - 1)]; + return send(status, json); + } + send(404, {}); + }); + return new Promise((resolve) => + server.listen(0, "127.0.0.1", () => resolve({ server, calls })) + ); +} + +// config.js reads the metadata URL once, so all tests share one mock server. +const { server, calls } = await startMockAuthServer(); +process.env.SEARCH1API_OAUTH_RESOURCE_METADATA = `http://127.0.0.1:${server.address().port}/.well-known/oauth-protected-resource`; +const { loginWithDeviceCode } = await import("../dist/auth.js"); +test.after(() => server.close()); +test.beforeEach(() => { + calls.device.length = 0; + calls.token.length = 0; +}); + +test("device login polls through pending and slow_down, then returns tokens", async () => { + state.script = [ + [400, { error: "authorization_pending" }], + [400, { error: "slow_down" }], + [200, { access_token: "at", refresh_token: "rt", expires_in: 3600, token_type: "Bearer" }], + ]; + { + const sleeps = []; + let prompt; + const oauth = await loginWithDeviceCode({ + clientId: "public-client", + sleep: async (ms) => { sleeps.push(ms); }, + onPrompt: (p) => { prompt = p; }, + }); + assert.equal(prompt.userCode, "BCDF-GHJK"); + assert.equal(oauth.accessToken, "at"); + assert.equal(oauth.refreshToken, "rt"); + assert.equal(oauth.clientId, "public-client"); + assert.deepEqual(sleeps, [1000, 1000, 6000]); + assert.equal(calls.device[0].get("client_id"), "public-client"); + assert.match(calls.device[0].get("scope"), /offline_access/); + const tokenCall = calls.token[0]; + assert.equal(tokenCall.get("grant_type"), "urn:ietf:params:oauth:grant-type:device_code"); + assert.equal(tokenCall.get("device_code"), "secret-device-code"); + } +}); + +test("device login stops when the user denies access", async () => { + state.script = [[400, { error: "access_denied" }]]; + { + await assert.rejects( + loginWithDeviceCode({ clientId: "public-client", sleep: async () => {} }), + /denied/ + ); + } +}); + +test("device login explains when no client id is configured", async () => { + state.script = []; + { + await assert.rejects(loginWithDeviceCode({ clientId: "" }), /not configured/); + } +}); From 544d20a020793d3d8aa51c4eb89ed3dc8912014f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 03:08:34 +0000 Subject: [PATCH 2/2] Ship device login client id, docs and changelog Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DuYf7wb1EAoffTQ9poskFK --- CHANGELOG.md | 4 ++++ README.md | 5 +++++ src/auth.ts | 2 +- 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e6aa15e..2620258 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## 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`. + ## 2.3.0 - 2026-11-05 Adds `s1 deepcrawl ` and `deepcrawl()` / `deepcrawlStatus()` SDK helpers for `POST /deepcrawl` and `GET /deepcrawl/status/{taskId}`: crawl a whole site or section in one task and get every page as Markdown. The command starts the task, waits for it (`--timeout`, default 300 s, polling every 2 s), then prints the stats, one line per page, failed URLs and the result URL. Options: `--type sitemap|all`, `-n/--max-pages` (1-1000), repeatable `--include`/`--exclude` path rules (up to 20 each), `--format json|zip` (the CLI defaults to `json`), `-o/--output` (pages JSON or the ZIP), `--no-wait`, `--json`. `s1 deepcrawl status ` checks a task for free. 20 credits per task, any page count. Options after a subcommand now belong to that subcommand, so a global `-V` must come before it. The agent skill routes "crawl this whole site" requests to it. diff --git a/README.md b/README.md index 3d8e1df..7e05e96 100644 --- a/README.md +++ b/README.md @@ -323,8 +323,13 @@ Authorize in your browser with OAuth 2.1 and PKCE. ```bash s1 login s1 login --no-browser +s1 login --device ``` +`--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 f872bd3..68fb404 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -23,7 +23,7 @@ const DEVICE_CODE_GRANT = "urn:ietf:params:oauth:grant-type:device_code"; // Dynamically registered clients cannot use the device grant, so this one is // created once in the Clerk Dashboard and ships with the CLI. export const DEVICE_CLIENT_ID = - process.env.SEARCH1API_OAUTH_DEVICE_CLIENT_ID ?? ""; + process.env.SEARCH1API_OAUTH_DEVICE_CLIENT_ID ?? "m0ujmjk3mmIuuNjX"; const SUCCESS_HTML = `