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
8 changes: 5 additions & 3 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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: <code>`
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.**
Expand Down
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -105,6 +129,7 @@ export PROOF_ACCESS_TOKEN=$(x401-cli token --sandbox)
| `--timeout <d>` | `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 <file>` | `fetch` | Writes the body to a file |
| `--proof-request <v>` | `present` | The `PROOF-REQUEST` value, `-` for stdin, `@file` |
Expand Down
21 changes: 17 additions & 4 deletions src/cli.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -38,6 +39,7 @@ Options
--timeout <duration> 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 <m> fetch: HTTP method
-H, --header <h> fetch: header "Name: value", repeatable
-d, --data <body> fetch: body; @file or @- for stdin
Expand Down Expand Up @@ -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" },
Expand All @@ -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(),
}),
Expand Down Expand Up @@ -193,6 +197,13 @@ export async function run(argv: string[], deps: Deps): Promise<number> {
}

function openBrowser(url: string): Promise<void> {
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]
Expand All @@ -202,10 +213,11 @@ function openBrowser(url: string): Promise<void> {
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)}`)),
);
});
}

Expand All @@ -227,6 +239,7 @@ if (
fetch: globalThis.fetch,
openBrowser,
now: () => Math.floor(Date.now() / 1000),
sleep,
readStdin,
});
process.exitCode = code;
Expand Down
18 changes: 11 additions & 7 deletions src/commands/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[] =>
Expand All @@ -22,12 +22,16 @@ const environmentOf = (ctx: Context): Environment =>
ctx.options.sandbox ? "sandbox" : "production";

async function signIn(ctx: Context, environment: Environment): Promise<Tokens> {
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);
Expand Down Expand Up @@ -102,6 +106,7 @@ export async function logoutCommand(ctx: Context): Promise<void> {
type Status = {
environment: Environment;
issuer: string;
client_id: string;
expires_at: number | null;
refreshable: boolean;
};
Expand All @@ -118,6 +123,7 @@ export async function statusCommand(ctx: Context): Promise<number> {
{
environment,
issuer: loginIssuer(environment, tokens),
client_id: CLIENT_IDS[environment],
expires_at: tokens.expires_at ?? null,
refreshable: tokens.refresh_token !== undefined,
},
Expand All @@ -129,7 +135,6 @@ export async function statusCommand(ctx: Context): Promise<number> {
`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,
Expand All @@ -140,11 +145,10 @@ export async function statusCommand(ctx: Context): Promise<number> {
} 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()
Expand Down
5 changes: 4 additions & 1 deletion src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand All @@ -16,6 +16,7 @@ export type Deps = {
fetch: typeof globalThis.fetch;
openBrowser: (url: string) => Promise<void>;
now: () => number;
sleep: (ms: number) => Promise<void>;
readStdin: () => Promise<Buffer>;
issuers?: Issuers;
};
Expand All @@ -27,6 +28,7 @@ export type Options = {
timeoutMs: number;
noWait: boolean;
noBrowser: boolean;
device: boolean;
method?: string;
headers: string[];
data?: string;
Expand All @@ -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,
};
Expand Down
5 changes: 4 additions & 1 deletion src/environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Record<Environment, string>> = {
production: "caynqpyde",
sandbox: "caynxy5ad",
};
export const SCOPE = "agentic";

export type Issuers = Partial<Record<Environment, string>>;
Expand Down
Loading
Loading