From f418a994527a89c698bb849e3ea9adf6661a337d Mon Sep 17 00:00:00 2001 From: Jeremie Charrier Date: Fri, 6 Nov 2026 13:22:12 -0500 Subject: [PATCH 1/5] Add device authorization grant login (login --device) Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 5 +- README.md | 15 ++++ src/cli.ts | 5 ++ src/commands/auth.ts | 19 +++-- src/context.ts | 2 + src/oauth.ts | 119 ++++++++++++++++++++++++++++ tests/cli.test.ts | 184 +++++++++++++++++++++++++++++++++++++++++++ tests/helpers.ts | 45 +++++++++++ 8 files changed, 385 insertions(+), 9 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 2fb3b87..e2f4d25 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -6,8 +6,9 @@ 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 `cag5xwbbz`, 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. diff --git a/README.md b/README.md index b357d09..e4d15e4 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,20 @@ x401-cli resume ot7gzqj4p x401-cli cancel ot7gzqj4p ``` +### Sign in without a local browser + +On a remote host or in a container, `--device` prints a URL and a code. Open the URL on any device, +sign in to Proof and enter the code. The CLI waits for the approval. + +```sh +x401-cli login --device +``` + +``` +x401-cli: login to sign in, open https://api.proof.com/oauth/v2/device and enter the code WDJB-MJHT +x401-cli: login or open this URL: https://api.proof.com/oauth/v2/device?user_code=WDJB-MJHT +``` + ### Get the access token `token` prints the access token. @@ -105,6 +119,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 that you enter on any device, for hosts with no local browser | | `-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..fc33c96 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 on any device, without a local browser -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(), }), @@ -227,6 +231,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..93b53a3 100644 --- a/src/commands/auth.ts +++ b/src/commands/auth.ts @@ -12,7 +12,7 @@ import { type Tokens, } from "../credentials.ts"; import { CLIENT_ID, ENVIRONMENTS } from "../environment.ts"; -import { login, revoke } from "../oauth.ts"; +import { deviceLogin, login, revoke } from "../oauth.ts"; import { CliError, EXIT, event, failureJson } from "../output.ts"; const environments = (ctx: Context): Environment[] => @@ -22,12 +22,17 @@ 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), { - io: ctx.io, - openBrowser: ctx.openBrowser, - noBrowser: ctx.options.noBrowser, - timeoutMs: ctx.options.timeoutMs, - }); + const deps = oauthDeps(ctx, environment); + const { io } = ctx; + const { timeoutMs } = ctx.options; + const tokens = ctx.options.device + ? await deviceLogin(deps, { io, timeoutMs, sleep: ctx.sleep }) + : await login(deps, { + io, + openBrowser: ctx.openBrowser, + noBrowser: ctx.options.noBrowser, + timeoutMs, + }); const path = ctx.options.auth; await withLock(path, async () => { const credentials = await readCredentials(path); diff --git a/src/context.ts b/src/context.ts index 3b7a004..65706bf 100644 --- a/src/context.ts +++ b/src/context.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; diff --git a/src/oauth.ts b/src/oauth.ts index beec7cb..e9a27c2 100644 --- a/src/oauth.ts +++ b/src/oauth.ts @@ -170,6 +170,125 @@ export async function login( } } +const DEFAULT_INTERVAL_SECONDS = 5; +const SLOW_DOWN_SECONDS = 5; + +function oauthErrorOf(error: unknown): string | undefined { + if (error instanceof oauth.ResponseBodyError) { + return error.error; + } + if (error instanceof oauth.WWWAuthenticateChallengeError) { + return error.cause.find( + (challenge) => challenge.parameters.error !== undefined, + )?.parameters.error; + } + return 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: { + io: Io; + timeoutMs: number; + sleep: (ms: number) => Promise; + }, +): Promise { + const as = await server(deps); + 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); + } + event( + options.io, + "login", + `to sign in, open ${device.verification_uri} and enter the code ${device.user_code}`, + ); + if (device.verification_uri_complete !== undefined) { + event( + options.io, + "login", + `or open this URL: ${device.verification_uri_complete}`, + ); + } + 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, diff --git a/tests/cli.test.ts b/tests/cli.test.ts index ab70f35..5c58de9 100644 --- a/tests/cli.test.ts +++ b/tests/cli.test.ts @@ -13,7 +13,10 @@ import { environmentOf } from "../src/environment.ts"; import { parseDuration } from "../src/output.ts"; import { cli, + DEVICE_AUTHORIZATION, + deviceRoute, NOW, + oauthError, PENDING, proofRequestFor, proofRoute, @@ -612,3 +615,184 @@ test("logout revokes the refresh token and forgets the login", async () => { assert.equal(form.get("token"), "ref"); assert.deepEqual(await readJson(auth), {}); }); + +test("login --device shows the user code on stderr, 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[] = []; + let opened = false; + + const result = await cli( + ["login", "--device", "--sandbox", "--json", "--auth", auth], + { + fetch, + sleep: async (ms) => { + waits.push(ms); + }, + openBrowser: async () => { + opened = true; + }, + }, + ); + + assert.equal(result.code, 0, result.stderr); + assert.equal(opened, false); + assert.deepEqual(waits, [5000, 5000, 5000]); + assert.equal( + result.stderr, + [ + `x401-cli: login to sign in, open ${DEVICE_AUTHORIZATION.verification_uri} and enter the code WDJB-MJHT`, + `x401-cli: login or open this URL: ${DEVICE_AUTHORIZATION.verification_uri_complete}`, + `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"), "cag5xwbbz"); + 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"), "cag5xwbbz"); + 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("login --device reads the OAuth error from a WWW-Authenticate challenge, as Doorkeeper sends it", async () => { + const { auth } = await workspace(); + const challenged = (error: string) => () => + oauthError(error, 400, { + "WWW-Authenticate": `Bearer realm="Doorkeeper", error="${error}"`, + }); + const pending = await workspace(); + const { fetch } = stubFetch( + deviceRoute([challenged("authorization_pending")]), + ); + const approved = await cli( + ["login", "--device", "--sandbox", "--auth", pending.auth], + { fetch }, + ); + assert.equal(approved.code, 0, approved.stderr); + + const denied = stubFetch(deviceRoute([challenged("access_denied")])); + const result = await cli(["login", "--device", "--sandbox", "--auth", auth], { + fetch: denied.fetch, + }); + assert.equal(result.code, 8, result.stderr); +}); + +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..5b57e26 100644 --- a/tests/helpers.ts +++ b/tests/helpers.ts @@ -44,6 +44,50 @@ 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, + headers: Record = {}, +) => Response.json({ error }, { status, headers }); + +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 +223,7 @@ export async function cli( }, openBrowser: async () => undefined, now: () => NOW, + sleep: async () => undefined, readStdin: async () => Buffer.alloc(0), ...deps, }); From b0810113f66c9af29bd96147a9e857e2afb8a615 Mon Sep 17 00:00:00 2001 From: Jeremie Charrier Date: Fri, 6 Nov 2026 14:16:00 -0500 Subject: [PATCH 2/5] Open the browser for device login and show the code Co-Authored-By: Claude Opus 5.5 --- README.md | 13 ++++---- src/cli.ts | 18 +++++++--- src/commands/auth.ts | 17 +++++----- src/oauth.ts | 78 +++++++++++++++++++++----------------------- tests/cli.test.ts | 55 ++++++++++++++++--------------- tests/helpers.ts | 7 ++-- 6 files changed, 96 insertions(+), 92 deletions(-) diff --git a/README.md b/README.md index e4d15e4..be4e674 100644 --- a/README.md +++ b/README.md @@ -66,18 +66,19 @@ x401-cli resume ot7gzqj4p x401-cli cancel ot7gzqj4p ``` -### Sign in without a local browser +### Sign in with a code -On a remote host or in a container, `--device` prints a URL and a code. Open the URL on any device, -sign in to Proof and enter the code. The CLI waits for the approval. +`--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; otherwise it prints the URL +for you to open on any device. Check that the page shows the same code, then approve. The CLI waits +for the approval. ```sh x401-cli login --device ``` ``` -x401-cli: login to sign in, open https://api.proof.com/oauth/v2/device and enter the code WDJB-MJHT -x401-cli: login or open this URL: https://api.proof.com/oauth/v2/device?user_code=WDJB-MJHT +x401-cli: login open https://api.proof.com/oauth/v2/device?user_code=WDJB-MJHT to sign in; check that it shows the code WDJB-MJHT ``` ### Get the access token @@ -119,7 +120,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 that you enter on any device, for hosts with no local 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 fc33c96..3cafcf7 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -39,7 +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 on any device, without a local 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 @@ -197,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] @@ -206,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)}`)), + ); }); } diff --git a/src/commands/auth.ts b/src/commands/auth.ts index 93b53a3..4c20ed3 100644 --- a/src/commands/auth.ts +++ b/src/commands/auth.ts @@ -23,16 +23,15 @@ const environmentOf = (ctx: Context): Environment => async function signIn(ctx: Context, environment: Environment): Promise { const deps = oauthDeps(ctx, environment); - const { io } = ctx; - const { timeoutMs } = ctx.options; + const options = { + io: ctx.io, + openBrowser: ctx.openBrowser, + noBrowser: ctx.options.noBrowser, + timeoutMs: ctx.options.timeoutMs, + }; const tokens = ctx.options.device - ? await deviceLogin(deps, { io, timeoutMs, sleep: ctx.sleep }) - : await login(deps, { - io, - openBrowser: ctx.openBrowser, - noBrowser: ctx.options.noBrowser, - timeoutMs, - }); + ? 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); diff --git a/src/oauth.ts b/src/oauth.ts index e9a27c2..6804593 100644 --- a/src/oauth.ts +++ b/src/oauth.ts @@ -103,14 +103,30 @@ function listen(): Promise<{ }); } +export type SignInOptions = { + io: Io; + openBrowser: (url: string) => Promise; + noBrowser: boolean; + timeoutMs: number; +}; + +async function showSignIn( + options: SignInOptions, + url: string, + messages: { opened: string; manual: string }, +): Promise { + const opened = + !options.noBrowser && + (await options.openBrowser(url).then( + () => true, + () => false, + )); + 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 codeVerifier = oauth.generateRandomCodeVerifier(); @@ -128,12 +144,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( () => @@ -173,17 +187,8 @@ export async function login( const DEFAULT_INTERVAL_SECONDS = 5; const SLOW_DOWN_SECONDS = 5; -function oauthErrorOf(error: unknown): string | undefined { - if (error instanceof oauth.ResponseBodyError) { - return error.error; - } - if (error instanceof oauth.WWWAuthenticateChallengeError) { - return error.cause.find( - (challenge) => challenge.parameters.error !== undefined, - )?.parameters.error; - } - return undefined; -} +const oauthErrorOf = (error: unknown): string | undefined => + error instanceof oauth.ResponseBodyError ? error.error : undefined; function deviceRefusal(error: unknown): CliError { const code = oauthErrorOf(error); @@ -201,11 +206,7 @@ function deviceRefusal(error: unknown): CliError { export async function deviceLogin( deps: OAuthDeps, - options: { - io: Io; - timeoutMs: number; - sleep: (ms: number) => Promise; - }, + options: SignInOptions & { sleep: (ms: number) => Promise }, ): Promise { const as = await server(deps); if (as.device_authorization_endpoint === undefined) { @@ -233,18 +234,15 @@ export async function deviceLogin( } catch (error) { throw deviceRefusal(error); } - event( - options.io, - "login", - `to sign in, open ${device.verification_uri} and enter the code ${device.user_code}`, - ); - if (device.verification_uri_complete !== undefined) { - event( - options.io, - "login", - `or open this URL: ${device.verification_uri_complete}`, - ); - } + const url = device.verification_uri_complete ?? device.verification_uri; + const check = + device.verification_uri_complete === undefined + ? `enter the code ${device.user_code}` + : `check that it shows the code ${device.user_code}`; + await showSignIn(options, url, { + opened: `opened ${url} in your browser; ${check}`, + manual: `open ${url} to sign in; ${check}`, + }); const limitMs = Math.min(options.timeoutMs, device.expires_in * 1000); let intervalMs = (device.interval ?? DEFAULT_INTERVAL_SECONDS) * 1000; let waitedMs = 0; diff --git a/tests/cli.test.ts b/tests/cli.test.ts index 5c58de9..95905fc 100644 --- a/tests/cli.test.ts +++ b/tests/cli.test.ts @@ -616,7 +616,7 @@ test("logout revokes the refresh token and forgets the login", async () => { assert.deepEqual(await readJson(auth), {}); }); -test("login --device shows the user code on stderr, polls until approved and stores the tokens", async () => { +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([ @@ -625,7 +625,7 @@ test("login --device shows the user code on stderr, polls until approved and sto ]), ); const waits: number[] = []; - let opened = false; + const opened: string[] = []; const result = await cli( ["login", "--device", "--sandbox", "--json", "--auth", auth], @@ -634,20 +634,19 @@ test("login --device shows the user code on stderr, polls until approved and sto sleep: async (ms) => { waits.push(ms); }, - openBrowser: async () => { - opened = true; + openBrowser: async (url) => { + opened.push(url); }, }, ); assert.equal(result.code, 0, result.stderr); - assert.equal(opened, false); + assert.deepEqual(opened, [DEVICE_AUTHORIZATION.verification_uri_complete]); assert.deepEqual(waits, [5000, 5000, 5000]); assert.equal( result.stderr, [ - `x401-cli: login to sign in, open ${DEVICE_AUTHORIZATION.verification_uri} and enter the code WDJB-MJHT`, - `x401-cli: login or open this URL: ${DEVICE_AUTHORIZATION.verification_uri_complete}`, + `x401-cli: login opened ${DEVICE_AUTHORIZATION.verification_uri_complete} in your browser; check that it shows the code WDJB-MJHT`, `x401-cli: logged_in sandbox (${auth})`, "", ].join("\n"), @@ -686,27 +685,29 @@ test("login --device shows the user code on stderr, polls until approved and sto assert.equal(result.stderr.includes("the-device-code"), false); }); -test("login --device reads the OAuth error from a WWW-Authenticate challenge, as Doorkeeper sends it", async () => { - const { auth } = await workspace(); - const challenged = (error: string) => () => - oauthError(error, 400, { - "WWW-Authenticate": `Bearer realm="Doorkeeper", error="${error}"`, - }); - const pending = await workspace(); - const { fetch } = stubFetch( - deviceRoute([challenged("authorization_pending")]), - ); - const approved = await cli( - ["login", "--device", "--sandbox", "--auth", pending.auth], - { fetch }, - ); - assert.equal(approved.code, 0, approved.stderr); +test("login --device prints the URL with the code when the browser cannot open or --no-browser is set", async () => { + const manual = `x401-cli: login open ${DEVICE_AUTHORIZATION.verification_uri_complete} to sign in; check that it shows the code WDJB-MJHT\n`; + 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 denied = stubFetch(deviceRoute([challenged("access_denied")])); - const result = await cli(["login", "--device", "--sandbox", "--auth", auth], { - fetch: denied.fetch, - }); - assert.equal(result.code, 8, result.stderr); + const result = await cli( + ["login", "--device", "--sandbox", ...flags, "--auth", auth], + { fetch, openBrowser }, + ); + + assert.equal(result.code, 0, result.stderr); + assert.equal(result.stderr.startsWith(manual), true, result.stderr); + assert.equal(result.stderr.split("\n").length, 3); + } }); test("login --device waits longer after slow_down", async () => { diff --git a/tests/helpers.ts b/tests/helpers.ts index 5b57e26..e866456 100644 --- a/tests/helpers.ts +++ b/tests/helpers.ts @@ -63,11 +63,8 @@ export const DEVICE_AUTHORIZATION = { interval: 5, }; -export const oauthError = ( - error: string, - status = 400, - headers: Record = {}, -) => Response.json({ error }, { status, headers }); +export const oauthError = (error: string, status = 400) => + Response.json({ error }, { status }); export const deviceRoute = (polls: (() => Response)[]): Route => From d0256ed581ce750b49190aca06d13f58307ec200 Mon Sep 17 00:00:00 2001 From: Jeremie Charrier Date: Fri, 6 Nov 2026 14:24:13 -0500 Subject: [PATCH 3/5] Show the device sign-in prompt as a URL and code block Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 3 ++- README.md | 17 +++++++++++++---- src/oauth.ts | 44 +++++++++++++++++++++++++++++--------------- tests/cli.test.ts | 23 ++++++++++++++++++----- 4 files changed, 62 insertions(+), 25 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index e2f4d25..4f0747d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,7 +11,8 @@ in to Proof and stores the tokens; everything x401 comes from `@proof.com/x401-a 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 be4e674..1aaad48 100644 --- a/README.md +++ b/README.md @@ -69,16 +69,25 @@ 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; otherwise it prints the URL -for you to open on any device. Check that the page shows the same code, then approve. The CLI waits -for the approval. +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 ``` ``` -x401-cli: login open https://api.proof.com/oauth/v2/device?user_code=WDJB-MJHT to sign in; check that it shows the code WDJB-MJHT +Attempting to open your default browser. +If the browser does not open or you wish to use a different device to authorize this request, open the following URL: + +https://api.proof.com/oauth/v2/device + +Then enter the code: + +WDJB-MJHT + +x401-cli: logged_in production (~/.config/proof/x401-cli/credentials.json) ``` ### Get the access token diff --git a/src/oauth.ts b/src/oauth.ts index 6804593..0bf72dd 100644 --- a/src/oauth.ts +++ b/src/oauth.ts @@ -110,17 +110,22 @@ export type SignInOptions = { 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 = - !options.noBrowser && - (await options.openBrowser(url).then( - () => true, - () => false, - )); + const opened = await openedBrowser(options, url); event(options.io, "login", opened ? messages.opened : messages.manual); } @@ -234,15 +239,24 @@ export async function deviceLogin( } catch (error) { throw deviceRefusal(error); } - const url = device.verification_uri_complete ?? device.verification_uri; - const check = - device.verification_uri_complete === undefined - ? `enter the code ${device.user_code}` - : `check that it shows the code ${device.user_code}`; - await showSignIn(options, url, { - opened: `opened ${url} in your browser; ${check}`, - manual: `open ${url} to sign in; ${check}`, - }); + const opened = await openedBrowser( + options, + device.verification_uri_complete ?? device.verification_uri, + ); + options.io.stderr.write( + [ + ...(opened ? ["Attempting to open your default browser."] : []), + "If the browser does not open or you wish to use a different device to authorize this request, open the following URL:", + "", + device.verification_uri, + "", + "Then enter the 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; diff --git a/tests/cli.test.ts b/tests/cli.test.ts index 95905fc..78bdfd5 100644 --- a/tests/cli.test.ts +++ b/tests/cli.test.ts @@ -616,6 +616,17 @@ test("logout revokes the refresh token and forgets the login", async () => { assert.deepEqual(await readJson(auth), {}); }); +const DEVICE_PROMPT = [ + "If the browser does not open or you wish to use a different device to authorize this request, open the following URL:", + "", + DEVICE_AUTHORIZATION.verification_uri, + "", + "Then enter the 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( @@ -646,7 +657,8 @@ test("login --device opens the URL with the code, polls until approved and store assert.equal( result.stderr, [ - `x401-cli: login opened ${DEVICE_AUTHORIZATION.verification_uri_complete} in your browser; check that it shows the code WDJB-MJHT`, + "Attempting to open your default browser.", + DEVICE_PROMPT, `x401-cli: logged_in sandbox (${auth})`, "", ].join("\n"), @@ -685,8 +697,7 @@ test("login --device opens the URL with the code, polls until approved and store assert.equal(result.stderr.includes("the-device-code"), false); }); -test("login --device prints the URL with the code when the browser cannot open or --no-browser is set", async () => { - const manual = `x401-cli: login open ${DEVICE_AUTHORIZATION.verification_uri_complete} to sign in; check that it shows the code WDJB-MJHT\n`; +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 [ [ [], @@ -705,8 +716,10 @@ test("login --device prints the URL with the code when the browser cannot open o ); assert.equal(result.code, 0, result.stderr); - assert.equal(result.stderr.startsWith(manual), true, result.stderr); - assert.equal(result.stderr.split("\n").length, 3); + assert.equal( + result.stderr, + `${DEVICE_PROMPT}\nx401-cli: logged_in sandbox (${auth})\n`, + ); } }); From bdae647b844feaf42755a57f91de9e3e8a1a832f Mon Sep 17 00:00:00 2001 From: Jeremie Charrier Date: Fri, 6 Nov 2026 14:26:45 -0500 Subject: [PATCH 4/5] Use Proof wording for the device sign-in prompt Co-Authored-By: Claude Opus 5.5 --- README.md | 6 +++--- src/oauth.ts | 10 +++++++--- tests/cli.test.ts | 8 ++++---- 3 files changed, 14 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 1aaad48..8d58921 100644 --- a/README.md +++ b/README.md @@ -78,12 +78,12 @@ x401-cli login --device ``` ``` -Attempting to open your default browser. -If the browser does not open or you wish to use a different device to authorize this request, open the following URL: +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 -Then enter the code: +and enter this code: WDJB-MJHT diff --git a/src/oauth.ts b/src/oauth.ts index 0bf72dd..cfda98a 100644 --- a/src/oauth.ts +++ b/src/oauth.ts @@ -245,12 +245,16 @@ export async function deviceLogin( ); options.io.stderr.write( [ - ...(opened ? ["Attempting to open your default browser."] : []), - "If the browser does not open or you wish to use a different device to authorize this request, open the following URL:", + ...(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, "", - "Then enter the code:", + "and enter this code:", "", device.user_code, "", diff --git a/tests/cli.test.ts b/tests/cli.test.ts index 78bdfd5..d1d7520 100644 --- a/tests/cli.test.ts +++ b/tests/cli.test.ts @@ -617,11 +617,10 @@ test("logout revokes the refresh token and forgets the login", async () => { }); const DEVICE_PROMPT = [ - "If the browser does not open or you wish to use a different device to authorize this request, open the following URL:", "", DEVICE_AUTHORIZATION.verification_uri, "", - "Then enter the code:", + "and enter this code:", "", "WDJB-MJHT", "", @@ -657,7 +656,8 @@ test("login --device opens the URL with the code, polls until approved and store assert.equal( result.stderr, [ - "Attempting to open your default browser.", + "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})`, "", @@ -718,7 +718,7 @@ test("login --device prints the URL and the code without the browser line when t assert.equal(result.code, 0, result.stderr); assert.equal( result.stderr, - `${DEVICE_PROMPT}\nx401-cli: logged_in sandbox (${auth})\n`, + `To sign in, go to:\n${DEVICE_PROMPT}\nx401-cli: logged_in sandbox (${auth})\n`, ); } }); From ad120d78a31939d52603f51456446b6607dd68a0 Mon Sep 17 00:00:00 2001 From: Jeremie Charrier Date: Tue, 10 Nov 2026 10:29:41 -0500 Subject: [PATCH 5/5] Use one OAuth client per Proof environment Sandbox signs in with caynxy5ad and production with caynqpyde. status reports the client_id of each login. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- src/commands/auth.ts | 8 ++++---- src/context.ts | 3 ++- src/environment.ts | 5 ++++- src/oauth.ts | 31 +++++++++++++++++-------------- tests/cli.test.ts | 32 +++++++++++++++++++++++++++----- 6 files changed, 55 insertions(+), 26 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 4f0747d..60cdefb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -6,7 +6,7 @@ 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.** Two login modes, one 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`), diff --git a/src/commands/auth.ts b/src/commands/auth.ts index 4c20ed3..051b72a 100644 --- a/src/commands/auth.ts +++ b/src/commands/auth.ts @@ -11,7 +11,7 @@ import { writeCredentials, type Tokens, } from "../credentials.ts"; -import { CLIENT_ID, ENVIRONMENTS } from "../environment.ts"; +import { CLIENT_IDS, ENVIRONMENTS } from "../environment.ts"; import { deviceLogin, login, revoke } from "../oauth.ts"; import { CliError, EXIT, event, failureJson } from "../output.ts"; @@ -106,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; }; @@ -122,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, }, @@ -133,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, @@ -144,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 65706bf..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"; @@ -47,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 cfda98a..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.

"; @@ -134,12 +133,13 @@ export async function login( 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); @@ -165,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, @@ -182,7 +182,7 @@ export async function login( ); return tokens( deps, - await oauth.processAuthorizationCodeResponse(as, CLIENT, response), + await oauth.processAuthorizationCodeResponse(as, client, response), ); } finally { close(); @@ -214,6 +214,7 @@ export async function deviceLogin( 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", @@ -223,7 +224,7 @@ export async function deviceLogin( const started = await reach("start the device sign-in", () => oauth.deviceAuthorizationRequest( as, - CLIENT, + client, oauth.None(), { scope: SCOPE }, requestOptions(deps), @@ -233,7 +234,7 @@ export async function deviceLogin( try { device = await oauth.processDeviceAuthorizationResponse( as, - CLIENT, + client, started, ); } catch (error) { @@ -273,7 +274,7 @@ export async function deviceLogin( const response = await reach("check the device sign-in", () => oauth.deviceCodeGrantRequest( as, - CLIENT, + client, oauth.None(), device.device_code, requestOptions(deps), @@ -282,7 +283,7 @@ export async function deviceLogin( try { return tokens( deps, - await oauth.processDeviceCodeResponse(as, CLIENT, response), + await oauth.processDeviceCodeResponse(as, client, response), ); } catch (error) { switch (oauthErrorOf(error)) { @@ -317,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), @@ -329,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( @@ -341,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 d1d7520..82b585b 100644 --- a/tests/cli.test.ts +++ b/tests/cli.test.ts @@ -15,6 +15,7 @@ import { cli, DEVICE_AUTHORIZATION, deviceRoute, + SANDBOX, NOW, oauthError, PENDING, @@ -314,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); @@ -523,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( @@ -596,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 () => { @@ -671,7 +672,7 @@ test("login --device opens the URL with the code, polls until approved and store call.url.endsWith("/oauth/v2/device_authorization"), )!; const startForm = new URLSearchParams(await start.text()); - assert.equal(startForm.get("client_id"), "cag5xwbbz"); + 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); @@ -681,7 +682,7 @@ test("login --device opens the URL with the code, polls until approved and store "urn:ietf:params:oauth:grant-type:device_code", ); assert.equal(pollForm.get("device_code"), "the-device-code"); - assert.equal(pollForm.get("client_id"), "cag5xwbbz"); + assert.equal(pollForm.get("client_id"), "caynxy5ad"); assert.equal(pollForm.has("client_secret"), false); assert.deepEqual(await readJson(auth), { sandbox: { @@ -697,6 +698,27 @@ test("login --device opens the URL with the code, polls until approved and store 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 [ [