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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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 <url>` 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 <taskId>` 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.
Expand Down
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
138 changes: 138 additions & 0 deletions src/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 ?? "m0ujmjk3mmIuuNjX";

const SUCCESS_HTML = `<!doctype html>
<html>
Expand Down Expand Up @@ -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 = {
Expand Down Expand Up @@ -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<void>;
};

const defaultSleep = (ms: number) =>
new Promise<void>((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<OAuthConfig> {
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 <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<DeviceAuthorizationResponse>(
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<OAuthConfig> {
if (!oauth.refreshToken) {
throw new Error("OAuth access expired and no refresh token is available. Run `s1 login` again.");
Expand Down
70 changes: 55 additions & 15 deletions src/commands/login.ts
Original file line number Diff line number Diff line change
@@ -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);
Expand All @@ -18,12 +18,42 @@ export function registerLoginCommand(program: Command): void {
.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)"
)
.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,
Expand All @@ -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<void> {
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."
)
);
}
}
104 changes: 104 additions & 0 deletions tests/device-login.test.mjs
Original file line number Diff line number Diff line change
@@ -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/);
}
});