diff --git a/CLAUDE.md b/CLAUDE.md index 2fb3b87..60cdefb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -6,11 +6,13 @@ in to Proof and stores the tokens; everything x401 comes from `@proof.com/x401-a ## Rules 1. **No x401 logic here.** The CLI maps x401-agent calls to commands, files and exit codes. -2. **OAuth through `oauth4webapi` only.** Authorization code with PKCE S256 and a loopback redirect; - public client `cag5xwbbz`, no secret. +2. **OAuth through `oauth4webapi` only.** Two login modes, one public client per environment (`caynxy5ad` sandbox, `caynqpyde` production), no secret: + authorization code with PKCE S256 and a loopback redirect (default), and the device + authorization grant, RFC 8628 (`login --device`), which polls at the server's `interval`. 3. **Output is a contract.** stdout carries only the endpoint's body, one JSON object (`--json`), the token (`token`) or the `PROOF-RESPONSE` (`present`). stderr carries one `x401-cli: ` - line per event. Exit codes live in `src/output.ts`. Never print a token anywhere else. + line per event; the one exception is the `login --device` prompt, a plain multi-line block with + the URL and the user code. Exit codes live in `src/output.ts`. Never print a token anywhere else. 4. **Refresh under the credentials-file lock**, and store the new pair before using it: Proof revokes the grant when a rotated refresh token is reused. 5. **Never follow redirects.** diff --git a/README.md b/README.md index b357d09..8d58921 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,30 @@ x401-cli resume ot7gzqj4p x401-cli cancel ot7gzqj4p ``` +### Sign in with a code + +`--device` signs in with a code instead of a local redirect, for example on a remote host or in a +container. The CLI opens the sign-in page in your browser when it can, and always prints the URL and +the code so that you can sign in from any device. Check that the page shows the same code, then +approve. The CLI waits for the approval. + +```sh +x401-cli login --device +``` + +``` +Opening Proof in your browser to sign in. +If nothing opened, or to sign in from another device, go to: + +https://api.proof.com/oauth/v2/device + +and enter this code: + +WDJB-MJHT + +x401-cli: logged_in production (~/.config/proof/x401-cli/credentials.json) +``` + ### Get the access token `token` prints the access token. @@ -105,6 +129,7 @@ export PROOF_ACCESS_TOKEN=$(x401-cli token --sandbox) | `--timeout ` | `login`, `token`, `fetch`, `resume`, `present` | How long to wait for the sign-in or the approval, e.g. `9m` (default 15m) | | `--no-wait` | `fetch`, `present` | Exits with code 5 while the approval is pending | | `--no-browser` | `login`, `token` | Prints the sign-in URL instead of opening the browser | +| `--device` | `login`, `token` | Signs in with a code, without a local redirect; the sign-in page can open on any device | | `-X`, `-H`, `-d` | `fetch` | Method, header, body, as in curl; `-d @file` and `-d @-` read the body from a file or stdin | | `-o ` | `fetch` | Writes the body to a file | | `--proof-request ` | `present` | The `PROOF-REQUEST` value, `-` for stdin, `@file` | diff --git a/src/cli.ts b/src/cli.ts index 3ca1cc4..3cafcf7 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -1,5 +1,6 @@ #!/usr/bin/env node import { spawn } from "node:child_process"; +import { setTimeout as sleep } from "node:timers/promises"; import { parseArgs } from "node:util"; import { realpathSync } from "node:fs"; import { pathToFileURL } from "node:url"; @@ -38,6 +39,7 @@ Options --timeout How long to wait for the user's approval, e.g. 9m (default: 15m) --no-wait Return as soon as the approval is pending (exit 5), resume later --no-browser login: print the sign-in URL instead of opening the browser + --device login: sign in with a code instead of a local redirect -X, --method fetch: HTTP method -H, --header fetch: header "Name: value", repeatable -d, --data fetch: body; @file or @- for stdin @@ -75,6 +77,7 @@ function parse(argv: string[]): { timeout: { type: "string", default: DEFAULT_TIMEOUT }, "no-wait": { type: "boolean", default: false }, "no-browser": { type: "boolean", default: false }, + device: { type: "boolean", default: false }, method: { type: "string", short: "X" }, header: { type: "string", short: "H", multiple: true, default: [] }, data: { type: "string", short: "d" }, @@ -96,6 +99,7 @@ function parse(argv: string[]): { timeoutMs: parseDuration(values.timeout), noWait: values["no-wait"], noBrowser: values["no-browser"], + device: values.device, ...(values.method !== undefined && { method: values.method.toUpperCase(), }), @@ -193,6 +197,13 @@ export async function run(argv: string[], deps: Deps): Promise { } function openBrowser(url: string): Promise { + if ( + process.platform === "linux" && + !process.env.DISPLAY && + !process.env.WAYLAND_DISPLAY + ) { + return Promise.reject(new Error("no display")); + } const [command, ...args] = process.platform === "darwin" ? ["open", url] @@ -202,10 +213,11 @@ function openBrowser(url: string): Promise { return new Promise((resolve, reject) => { const child = spawn(command!, args, { stdio: "ignore", detached: true }); child.once("error", reject); - child.once("spawn", () => { - child.unref(); - resolve(); - }); + child.once("exit", (code) => + code === 0 + ? resolve() + : reject(new Error(`${command} exited with ${String(code)}`)), + ); }); } @@ -227,6 +239,7 @@ if ( fetch: globalThis.fetch, openBrowser, now: () => Math.floor(Date.now() / 1000), + sleep, readStdin, }); process.exitCode = code; diff --git a/src/commands/auth.ts b/src/commands/auth.ts index 7fffb79..051b72a 100644 --- a/src/commands/auth.ts +++ b/src/commands/auth.ts @@ -11,8 +11,8 @@ import { writeCredentials, type Tokens, } from "../credentials.ts"; -import { CLIENT_ID, ENVIRONMENTS } from "../environment.ts"; -import { login, revoke } from "../oauth.ts"; +import { CLIENT_IDS, ENVIRONMENTS } from "../environment.ts"; +import { deviceLogin, login, revoke } from "../oauth.ts"; import { CliError, EXIT, event, failureJson } from "../output.ts"; const environments = (ctx: Context): Environment[] => @@ -22,12 +22,16 @@ const environmentOf = (ctx: Context): Environment => ctx.options.sandbox ? "sandbox" : "production"; async function signIn(ctx: Context, environment: Environment): Promise { - const tokens = await login(oauthDeps(ctx, environment), { + const deps = oauthDeps(ctx, environment); + const options = { io: ctx.io, openBrowser: ctx.openBrowser, noBrowser: ctx.options.noBrowser, timeoutMs: ctx.options.timeoutMs, - }); + }; + const tokens = ctx.options.device + ? await deviceLogin(deps, { ...options, sleep: ctx.sleep }) + : await login(deps, options); const path = ctx.options.auth; await withLock(path, async () => { const credentials = await readCredentials(path); @@ -102,6 +106,7 @@ export async function logoutCommand(ctx: Context): Promise { type Status = { environment: Environment; issuer: string; + client_id: string; expires_at: number | null; refreshable: boolean; }; @@ -118,6 +123,7 @@ export async function statusCommand(ctx: Context): Promise { { environment, issuer: loginIssuer(environment, tokens), + client_id: CLIENT_IDS[environment], expires_at: tokens.expires_at ?? null, refreshable: tokens.refresh_token !== undefined, }, @@ -129,7 +135,6 @@ export async function statusCommand(ctx: Context): Promise { `no login; run \`x401-cli login${ctx.options.sandbox ? " --sandbox" : ""}\``, ); const summary = { - client_id: CLIENT_ID, credentials_file: path, token_source: fromEnv ? "env" : "file", logins: entries, @@ -140,11 +145,10 @@ export async function statusCommand(ctx: Context): Promise { } else { ctx.io.stdout.write( [ - `client_id: ${CLIENT_ID}`, `credentials: ${path}${fromEnv ? " (overridden by PROOF_ACCESS_TOKEN)" : ""}`, ...entries.map( (entry) => - `${entry.environment} (${entry.issuer}): expires ${ + `${entry.environment} (${entry.issuer}, client ${entry.client_id}): expires ${ entry.expires_at === null ? "never" : new Date(entry.expires_at * 1000).toISOString() diff --git a/src/context.ts b/src/context.ts index 3b7a004..d5eb17e 100644 --- a/src/context.ts +++ b/src/context.ts @@ -6,7 +6,7 @@ import { writeCredentials, type Tokens, } from "./credentials.ts"; -import { issuerOf, type Issuers } from "./environment.ts"; +import { CLIENT_IDS, issuerOf, type Issuers } from "./environment.ts"; import { refresh, type OAuthDeps } from "./oauth.ts"; import { CliError, type Io } from "./output.ts"; @@ -16,6 +16,7 @@ export type Deps = { fetch: typeof globalThis.fetch; openBrowser: (url: string) => Promise; now: () => number; + sleep: (ms: number) => Promise; readStdin: () => Promise; issuers?: Issuers; }; @@ -27,6 +28,7 @@ export type Options = { timeoutMs: number; noWait: boolean; noBrowser: boolean; + device: boolean; method?: string; headers: string[]; data?: string; @@ -45,6 +47,7 @@ export const loginCommand = (environment: Environment): string => export function oauthDeps(ctx: Context, environment: Environment): OAuthDeps { return { issuer: issuerOf(environment, ctx.issuers), + clientId: CLIENT_IDS[environment], fetch: ctx.fetch, now: ctx.now, }; diff --git a/src/environment.ts b/src/environment.ts index 39a2432..8f80424 100644 --- a/src/environment.ts +++ b/src/environment.ts @@ -6,7 +6,10 @@ import { import type { DcApiRequest } from "@proof.com/x401-agent"; export const ENVIRONMENTS: readonly Environment[] = ["production", "sandbox"]; -export const CLIENT_ID = "cag5xwbbz"; +export const CLIENT_IDS: Readonly> = { + production: "caynqpyde", + sandbox: "caynxy5ad", +}; export const SCOPE = "agentic"; export type Issuers = Partial>; diff --git a/src/oauth.ts b/src/oauth.ts index beec7cb..958bc38 100644 --- a/src/oauth.ts +++ b/src/oauth.ts @@ -2,17 +2,16 @@ import { createServer } from "node:http"; import type { AddressInfo } from "node:net"; import * as oauth from "oauth4webapi"; import type { Tokens } from "./credentials.ts"; -import { CLIENT_ID, SCOPE } from "./environment.ts"; +import { SCOPE } from "./environment.ts"; import { CliError, event, type Io } from "./output.ts"; export type OAuthDeps = { issuer: string; + clientId: string; fetch: typeof globalThis.fetch; now: () => number; }; -const CLIENT: oauth.Client = { client_id: CLIENT_ID }; - const CALLBACK_PAGE = "x401-cli

Signed in. You can close this window.

"; @@ -103,22 +102,44 @@ function listen(): Promise<{ }); } +export type SignInOptions = { + io: Io; + openBrowser: (url: string) => Promise; + noBrowser: boolean; + timeoutMs: number; +}; + +const openedBrowser = async ( + options: SignInOptions, + url: string, +): Promise => + !options.noBrowser && + (await options.openBrowser(url).then( + () => true, + () => false, + )); + +async function showSignIn( + options: SignInOptions, + url: string, + messages: { opened: string; manual: string }, +): Promise { + const opened = await openedBrowser(options, url); + event(options.io, "login", opened ? messages.opened : messages.manual); +} + export async function login( deps: OAuthDeps, - options: { - io: Io; - openBrowser: (url: string) => Promise; - noBrowser: boolean; - timeoutMs: number; - }, + options: SignInOptions, ): Promise { const as = await server(deps); + const client: oauth.Client = { client_id: deps.clientId }; const codeVerifier = oauth.generateRandomCodeVerifier(); const state = oauth.generateRandomState(); const { redirectUri, callback, close } = await listen(); try { const url = new URL(as.authorization_endpoint!); - url.searchParams.set("client_id", CLIENT_ID); + url.searchParams.set("client_id", deps.clientId); url.searchParams.set("redirect_uri", redirectUri); url.searchParams.set("response_type", "code"); url.searchParams.set("scope", SCOPE); @@ -128,12 +149,10 @@ export async function login( ); url.searchParams.set("code_challenge_method", "S256"); url.searchParams.set("state", state); - if (options.noBrowser) { - event(options.io, "login", `open this URL to sign in: ${url.href}`); - } else { - event(options.io, "login", "opening your browser to sign in to Proof"); - await options.openBrowser(url.href); - } + await showSignIn(options, url.href, { + opened: "opened your browser to sign in to Proof", + manual: `open this URL to sign in: ${url.href}`, + }); const timeout = new Promise((_resolve, reject) => { setTimeout( () => @@ -146,14 +165,14 @@ export async function login( const callbackUrl = await Promise.race([callback, timeout]); const parameters = oauth.validateAuthResponse( as, - CLIENT, + client, callbackUrl, state, ); const response = await reach("exchange the sign-in code", () => oauth.authorizationCodeGrantRequest( as, - CLIENT, + client, oauth.None(), parameters, redirectUri, @@ -163,13 +182,130 @@ export async function login( ); return tokens( deps, - await oauth.processAuthorizationCodeResponse(as, CLIENT, response), + await oauth.processAuthorizationCodeResponse(as, client, response), ); } finally { close(); } } +const DEFAULT_INTERVAL_SECONDS = 5; +const SLOW_DOWN_SECONDS = 5; + +const oauthErrorOf = (error: unknown): string | undefined => + error instanceof oauth.ResponseBodyError ? error.error : undefined; + +function deviceRefusal(error: unknown): CliError { + const code = oauthErrorOf(error); + const reason = + code !== undefined + ? ` (${code})` + : error instanceof Error + ? `: ${error.message}` + : ""; + return new CliError( + "unauthorized", + `Proof refused the device sign-in${reason}`, + ); +} + +export async function deviceLogin( + deps: OAuthDeps, + options: SignInOptions & { sleep: (ms: number) => Promise }, +): Promise { + const as = await server(deps); + const client: oauth.Client = { client_id: deps.clientId }; + if (as.device_authorization_endpoint === undefined) { + throw new CliError( + "usage", + `${deps.issuer} does not offer device sign-in; run login without --device`, + ); + } + const started = await reach("start the device sign-in", () => + oauth.deviceAuthorizationRequest( + as, + client, + oauth.None(), + { scope: SCOPE }, + requestOptions(deps), + ), + ); + let device: oauth.DeviceAuthorizationResponse; + try { + device = await oauth.processDeviceAuthorizationResponse( + as, + client, + started, + ); + } catch (error) { + throw deviceRefusal(error); + } + const opened = await openedBrowser( + options, + device.verification_uri_complete ?? device.verification_uri, + ); + options.io.stderr.write( + [ + ...(opened + ? [ + "Opening Proof in your browser to sign in.", + "If nothing opened, or to sign in from another device, go to:", + ] + : ["To sign in, go to:"]), + "", + device.verification_uri, + "", + "and enter this code:", + "", + device.user_code, + "", + "", + ].join("\n"), + ); + const limitMs = Math.min(options.timeoutMs, device.expires_in * 1000); + let intervalMs = (device.interval ?? DEFAULT_INTERVAL_SECONDS) * 1000; + let waitedMs = 0; + for (;;) { + if (waitedMs + intervalMs > limitMs) { + throw new CliError("unauthorized", "sign-in did not complete in time"); + } + await options.sleep(intervalMs); + waitedMs += intervalMs; + const response = await reach("check the device sign-in", () => + oauth.deviceCodeGrantRequest( + as, + client, + oauth.None(), + device.device_code, + requestOptions(deps), + ), + ); + try { + return tokens( + deps, + await oauth.processDeviceCodeResponse(as, client, response), + ); + } catch (error) { + switch (oauthErrorOf(error)) { + case "authorization_pending": + break; + case "slow_down": + intervalMs += SLOW_DOWN_SECONDS * 1000; + break; + case "access_denied": + throw new CliError("cancelled", "the sign-in was denied"); + case "expired_token": + throw new CliError( + "expired", + "the sign-in code expired; run login again", + ); + default: + throw deviceRefusal(error); + } + } + } +} + export async function refresh( deps: OAuthDeps, current: Tokens, @@ -182,10 +318,11 @@ export async function refresh( ); } const as = await server(deps); + const client: oauth.Client = { client_id: deps.clientId }; const response = await reach("refresh the token", () => oauth.refreshTokenGrantRequest( as, - CLIENT, + client, oauth.None(), refreshToken, requestOptions(deps), @@ -194,7 +331,7 @@ export async function refresh( try { return tokens( deps, - await oauth.processRefreshTokenResponse(as, CLIENT, response), + await oauth.processRefreshTokenResponse(as, client, response), ); } catch { throw new CliError( @@ -206,13 +343,14 @@ export async function refresh( export async function revoke(deps: OAuthDeps, current: Tokens): Promise { const as = await server(deps); + const client: oauth.Client = { client_id: deps.clientId }; if (as.revocation_endpoint === undefined) { return; } const response = await reach("revoke the token", () => oauth.revocationRequest( as, - CLIENT, + client, oauth.None(), current.refresh_token ?? current.access_token, { diff --git a/tests/cli.test.ts b/tests/cli.test.ts index ab70f35..82b585b 100644 --- a/tests/cli.test.ts +++ b/tests/cli.test.ts @@ -13,7 +13,11 @@ import { environmentOf } from "../src/environment.ts"; import { parseDuration } from "../src/output.ts"; import { cli, + DEVICE_AUTHORIZATION, + deviceRoute, + SANDBOX, NOW, + oauthError, PENDING, proofRequestFor, proofRoute, @@ -311,7 +315,7 @@ test("an expired access token is refreshed under the lock and the new pair is st const form = new URLSearchParams(await refresh.text()); assert.equal(form.get("grant_type"), "refresh_token"); assert.equal(form.get("refresh_token"), "ref"); - assert.equal(form.get("client_id"), "cag5xwbbz"); + assert.equal(form.get("client_id"), "caynxy5ad"); const proof = calls.find((call) => call.url.endsWith("/dc-api/requests"))!; assert.equal(proof.headers.get("authorization"), "Bearer fresh-access"); const stored = await readJson(auth); @@ -520,7 +524,7 @@ test("login signs in through the loopback redirect with PKCE and stores the toke assert.equal(result.code, 0, result.stderr); assert.equal(authorizeUrl!.origin, "https://api.fairfax.proof.com"); - assert.equal(authorizeUrl!.searchParams.get("client_id"), "cag5xwbbz"); + assert.equal(authorizeUrl!.searchParams.get("client_id"), "caynxy5ad"); assert.equal(authorizeUrl!.searchParams.get("scope"), "agentic"); assert.equal(authorizeUrl!.searchParams.get("code_challenge_method"), "S256"); assert.match( @@ -593,11 +597,11 @@ test("status reports the logins and exits unauthorized when there are none", asy { environment: "sandbox", issuer: "https://api.fairfax.proof.com", + client_id: "caynxy5ad", expires_at: NOW + 3600, refreshable: true, }, ]); - assert.equal(some.json().client_id, "cag5xwbbz"); }); test("logout revokes the refresh token and forgets the login", async () => { @@ -612,3 +616,219 @@ test("logout revokes the refresh token and forgets the login", async () => { assert.equal(form.get("token"), "ref"); assert.deepEqual(await readJson(auth), {}); }); + +const DEVICE_PROMPT = [ + "", + DEVICE_AUTHORIZATION.verification_uri, + "", + "and enter this code:", + "", + "WDJB-MJHT", + "", +].join("\n"); + +test("login --device opens the URL with the code, polls until approved and stores the tokens", async () => { + const { auth } = await workspace(); + const { fetch, calls } = stubFetch( + deviceRoute([ + () => oauthError("authorization_pending"), + () => oauthError("authorization_pending"), + ]), + ); + const waits: number[] = []; + const opened: string[] = []; + + const result = await cli( + ["login", "--device", "--sandbox", "--json", "--auth", auth], + { + fetch, + sleep: async (ms) => { + waits.push(ms); + }, + openBrowser: async (url) => { + opened.push(url); + }, + }, + ); + + assert.equal(result.code, 0, result.stderr); + assert.deepEqual(opened, [DEVICE_AUTHORIZATION.verification_uri_complete]); + assert.deepEqual(waits, [5000, 5000, 5000]); + assert.equal( + result.stderr, + [ + "Opening Proof in your browser to sign in.", + "If nothing opened, or to sign in from another device, go to:", + DEVICE_PROMPT, + `x401-cli: logged_in sandbox (${auth})`, + "", + ].join("\n"), + ); + assert.deepEqual(result.json(), { + environment: "sandbox", + expires_at: NOW + 7200, + }); + const start = calls.find((call) => + call.url.endsWith("/oauth/v2/device_authorization"), + )!; + const startForm = new URLSearchParams(await start.text()); + assert.equal(startForm.get("client_id"), "caynxy5ad"); + assert.equal(startForm.get("scope"), "agentic"); + const polls = calls.filter((call) => call.url.endsWith("/oauth/v2/token")); + assert.equal(polls.length, 3); + const pollForm = new URLSearchParams(await polls[0]!.text()); + assert.equal( + pollForm.get("grant_type"), + "urn:ietf:params:oauth:grant-type:device_code", + ); + assert.equal(pollForm.get("device_code"), "the-device-code"); + assert.equal(pollForm.get("client_id"), "caynxy5ad"); + assert.equal(pollForm.has("client_secret"), false); + assert.deepEqual(await readJson(auth), { + sandbox: { + issuer: "https://api.fairfax.proof.com", + access_token: "fresh-access", + refresh_token: "fresh-refresh", + expires_at: NOW + 7200, + scope: "agentic", + }, + }); + assert.equal(result.stdout.includes("fresh-"), false); + assert.equal(result.stderr.includes("fresh-"), false); + assert.equal(result.stderr.includes("the-device-code"), false); +}); + +test("production signs in with the production client", async () => { + const { auth } = await workspace(); + const { fetch, calls } = stubFetch(deviceRoute([])); + + const result = await cli( + ["login", "--device", "--no-browser", "--json", "--auth", auth], + { fetch, sleep: async () => undefined, env: { PROOF_ISSUER: SANDBOX } }, + ); + + assert.equal(result.code, 0, result.stderr); + const forms = await Promise.all( + calls + .filter((call) => call.method === "POST") + .map(async (call) => new URLSearchParams(await call.text())), + ); + assert.deepEqual( + forms.map((form) => form.get("client_id")), + ["caynqpyde", "caynqpyde"], + ); +}); + +test("login --device prints the URL and the code without the browser line when the browser cannot open or --no-browser is set", async () => { + for (const [flags, openBrowser] of [ + [ + [], + async () => { + throw new Error("no display"); + }, + ], + [["--no-browser"], async () => assert.fail("must not open the browser")], + ] as const) { + const { auth } = await workspace(); + const { fetch } = stubFetch(deviceRoute([])); + + const result = await cli( + ["login", "--device", "--sandbox", ...flags, "--auth", auth], + { fetch, openBrowser }, + ); + + assert.equal(result.code, 0, result.stderr); + assert.equal( + result.stderr, + `To sign in, go to:\n${DEVICE_PROMPT}\nx401-cli: logged_in sandbox (${auth})\n`, + ); + } +}); + +test("login --device waits longer after slow_down", async () => { + const { auth } = await workspace(); + const { fetch } = stubFetch(deviceRoute([() => oauthError("slow_down")])); + const waits: number[] = []; + + const result = await cli(["login", "--device", "--sandbox", "--auth", auth], { + fetch, + sleep: async (ms) => { + waits.push(ms); + }, + }); + + assert.equal(result.code, 0, result.stderr); + assert.deepEqual(waits, [5000, 10000]); +}); + +test("login --device exits cancelled when denied and expired when the code expires", async () => { + for (const [error, code, name] of [ + ["access_denied", 8, "cancelled"], + ["expired_token", 7, "expired"], + ] as const) { + const { auth } = await workspace(); + const { fetch } = stubFetch(deviceRoute([() => oauthError(error)])); + + const result = await cli( + ["login", "--device", "--sandbox", "--json", "--auth", auth], + { fetch }, + ); + + assert.equal(result.code, code, result.stderr); + assert.equal(result.json().error, name); + assert.deepEqual(await readJson(auth).catch(() => ({})), {}); + } +}); + +test("login --device exits unauthorized when --timeout runs out before the approval", async () => { + const { auth } = await workspace(); + const pending = () => oauthError("authorization_pending"); + const { fetch, calls } = stubFetch( + deviceRoute([pending, pending, pending, pending]), + ); + + const result = await cli( + ["login", "--device", "--sandbox", "--timeout", "12s", "--auth", auth], + { fetch }, + ); + + assert.equal(result.code, 3); + assert.match(result.stderr, /sign-in did not complete in time/); + assert.equal( + calls.filter((call) => call.url.endsWith("/oauth/v2/token")).length, + 2, + ); +}); + +test("login --device names the OAuth error when Proof refuses the client", async () => { + const { auth } = await workspace(); + const { fetch } = stubFetch( + (request, url) => + url.pathname === "/oauth/v2/device_authorization" + ? oauthError("invalid_client", 401) + : undefined, + deviceRoute([]), + ); + + const result = await cli(["login", "--device", "--sandbox", "--auth", auth], { + fetch, + }); + + assert.equal(result.code, 3); + assert.match( + result.stderr, + /x401-cli: unauthorized Proof refused the device sign-in \(invalid_client\)/, + ); +}); + +test("login --device is a usage error when Proof does not offer device sign-in", async () => { + const { auth } = await workspace(); + const { fetch } = stubFetch(proofRoute()); + + const result = await cli(["login", "--device", "--sandbox", "--auth", auth], { + fetch, + }); + + assert.equal(result.code, 1); + assert.match(result.stderr, /does not offer device sign-in/); +}); diff --git a/tests/helpers.ts b/tests/helpers.ts index 2e621a7..e866456 100644 --- a/tests/helpers.ts +++ b/tests/helpers.ts @@ -44,6 +44,47 @@ export const AS_METADATA = { token_endpoint_auth_methods_supported: ["none"], }; +export const DEVICE_METADATA = { + ...AS_METADATA, + device_authorization_endpoint: `${SANDBOX}/oauth/v2/device_authorization`, + grant_types_supported: [ + "authorization_code", + "refresh_token", + "urn:ietf:params:oauth:grant-type:device_code", + ], +}; + +export const DEVICE_AUTHORIZATION = { + device_code: "the-device-code", + user_code: "WDJB-MJHT", + verification_uri: `${SANDBOX}/oauth/device`, + verification_uri_complete: `${SANDBOX}/oauth/device?user_code=WDJB-MJHT`, + expires_in: 600, + interval: 5, +}; + +export const oauthError = (error: string, status = 400) => + Response.json({ error }, { status }); + +export const deviceRoute = + (polls: (() => Response)[]): Route => + (request, url) => { + if (url.origin !== SANDBOX) { + return undefined; + } + const key = `${request.method} ${url.pathname}`; + if (key === "GET /.well-known/oauth-authorization-server") { + return Response.json(DEVICE_METADATA); + } + if (key === "POST /oauth/v2/device_authorization") { + return Response.json(DEVICE_AUTHORIZATION); + } + if (key === "POST /oauth/v2/token") { + return (polls.shift() ?? (() => Response.json(TOKENS)))(); + } + return undefined; + }; + export const PENDING = { id: "ot1", status: "pending", @@ -179,6 +220,7 @@ export async function cli( }, openBrowser: async () => undefined, now: () => NOW, + sleep: async () => undefined, readStdin: async () => Buffer.alloc(0), ...deps, });