diff --git a/CHANGELOG.md b/CHANGELOG.md index ed63413..a58d396 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,9 +11,10 @@ repository's [tags](https://github.com/firstdraft/cli/tags) identify the source ## 0.10.0 -Lets First Draft tell a setup that it is out of date, and adds the account and report commands, so a person working -alone hears when to update and their agent can send the progress and failure reports the person agreed to. Moves the -Rails target to profile `rails-sketch/2026-11` and the accepted API contract to `0.9.x`. +Lets First Draft tell a setup that it is out of date, and adds the account, report, and `start` commands and a device +login in two steps, so a person working alone hears when to update, their agent can log them in, and it can send the +progress and failure reports the person agreed to. Moves the Rails target to profile `rails-sketch/2026-11` and the +accepted API contract to `0.9.x`. - `plan init` writes Plans that target `rails-sketch/2026-11`. `plan compile` and `compilation download` accept only artifacts for that profile; an artifact for `rails-sketch/2026-10` reports `invalid_artifact`. The CLI sends a @@ -40,7 +41,8 @@ Rails target to profile `rails-sketch/2026-11` and the accepted API contract to stop never replaces the result of `logout`. - A `429` on any command except `logout`, `login` included, fails with `rate_limited`. It carries `status` 429, `retry_at` from `Retry-After` when that is readable, First Draft's problem in `response` when it sent a valid one - of at most 64 KiB, and `current` when a Compilation had already started. Its detail says to try again after + of at most 64 KiB, except from `start`, which passes on no text First Draft wrote, and `current` when a + Compilation had already started. Its detail says to try again after `retry_at`, when `response.detail` says, or in a minute. When `current` is present, the detail says to follow that Compilation with `compilation status` instead of compiling again. - `firstdraft account` prints `{"reports": "on"}` or `{"reports": "off"}` for the signed-in account, at the origin @@ -58,21 +60,37 @@ Rails target to profile `rails-sketch/2026-11` and the accepted API contract to with a line number, and says when frames after the first 20 were dropped; the printed JSON is exactly what is sent. Both commands find the Project from the generated application's root after root adoption, or from the Project's directory. +- `firstdraft start`, which an agent runs once before other work, prints fixed sentences on standard output, one fact + per line: the CLI version and, when `FIRSTDRAFT_PLUGIN_VERSION` holds one, the plugin's; the update line, when + First Draft names a newer version; whether this computer has a saved login for the origin and whether a token in + the environment takes its place; and, when reports are on, when to send progress and failure reports and with + which command. With reports off, it says nothing about reports. With a token, it makes one request, an account + read; without one, it makes none and names the two login steps below. It exits 0 only when First Draft accepted + the token. A setup below the minimum or on another API contract fails with `update_required` or + `api_contract_unsupported`, even though the account read was its only request. +- `firstdraft login --no-wait` asks for a device grant, prints the link, the user code, and when they expire, saves + the waiting login as `device-login.json` beside `credentials.json` with mode `0600`, and exits. After the person + approves, `firstdraft login --finish` polls at the grant's interval for at most 15 seconds, saves the token, and + removes that file; it also removes it once the grant is refused, expired, or spent. It prints `Logged in:`, + `Still waiting:`, `Expired:`, or `Refused:` with the next step. The device code is never printed. The browser login + and the one-process `login --interactive` are unchanged. - After an ambiguous push, from `plan push` or `plan compile`, or an ambiguous direct Compilation start, `request_outcome_unknown` now says to run the same command once more with the same options and environment, and what a `412` or `compilation_active` answer then means, instead of telling the caller to stop. The recovery for an unconfirmed Publication under `plan compile --github` is unchanged. - New `error` values, each with exit status 1: `update_required`, `api_contract_unsupported`, `rate_limited`, - `account_unavailable`, `report_rejected`, and `report_unavailable`. `account` and the report commands also report - `authentication_required` and `invalid_server_response` (exit status 1) and `invalid_arguments` and - `invalid_configuration` (exit status 2). The report commands also report `local_input_unreadable` and - `project_not_pushed` (exit status 1). + `account_unavailable`, `report_rejected`, `report_unavailable`, and, from `login --finish`, `authorization_pending` + and `login_not_started`. `account`, `start`, and the report commands also report `authentication_required` and + `invalid_server_response` (exit status 1) and `invalid_arguments` and `invalid_configuration` (exit status 2). The + report commands also report `local_input_unreadable` and `project_not_pushed` (exit status 1). `login_failed` gains + the reasons `device_login_invalid` and `device_login_unavailable` for the waiting device login's file. Use CLI 0.10.0 with a Service that serves API `0.9.x`. Once a response from an origin names API `0.8.x`, the CLI sends nothing more and says to use the CLI version that origin supports. A plugin's launcher should set `FIRSTDRAFT_PLUGIN_VERSION` and `FIRSTDRAFT_AGENT`; without the first, the CLI compares its own version with the CLI versions. Callers that parse standard error should drop the `First Draft: ` lines, which any network command may now -write before its result. +write before its result; `start` writes its update line on standard output instead. A Skill that checked +`firstdraft --help` runs `firstdraft start` in its place and may run the two login steps itself. ## 0.9.0 diff --git a/docs/commands.md b/docs/commands.md index bdfa881..70ea79e 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -3,7 +3,8 @@ This page owns the detailed public semantics of the current command surface. Run `firstdraft --help` or a command group's `--help` for concise executable syntax. See [Errors and recovery](errors.md) before retrying a failed mutation. -The current `0.10.x` source line contains the auditable command shell, browser and device login, local Foundation Plan +The current `0.10.x` source line contains the auditable command shell, the agent's `start` check, browser and device +login in one command or in two steps that an agent runs, local Foundation Plan initialization, local application-key and UUID generation, conditional whole-document push, whole-graph analysis status polling, direct Compile-and-materialize and private publish orchestration, retained-Compilation inspection and cancellation, the account's report setting, and progress and failure reports. It requires the service's `0.9.x` API @@ -14,10 +15,13 @@ contract. The [changelog](https://github.com/firstdraft/cli/blob/main/CHANGELOG. | Command | Network | Purpose | | ------------------------------------- | ------- | ----------------------------------------------------------- | +| `firstdraft start` | Yes | Check versions, login, and reports before other work | | `firstdraft plan init` | No | Create an empty local Foundation Plan and Project identity | | `firstdraft generate application-key` | No | Preview deterministic name-to-key derivation | | `firstdraft generate uuid` | No | Generate one or more Foundation Plan subject identities | | `firstdraft login` | Yes | Approve the CLI in a browser and save a token for an origin | +| `firstdraft login --no-wait` | Yes | Start a device login for an agent and exit | +| `firstdraft login --finish` | Yes | Finish that device login once the person approved | | `firstdraft logout` | Yes | Revoke and remove the saved token for an origin | | `firstdraft plan push` | Yes | Conditionally submit the exact whole Plan | | `firstdraft plan status` | Yes | Read or wait for the current whole-graph analysis | @@ -67,7 +71,8 @@ firstdraft login --interactive # also -i or --device The CLI prints a verification URL, a short user code, and a URL that already includes the code. Open either URL on any device, confirm the code, and approve. The CLI polls at the server's interval, adds five seconds when asked to -slow down, and stops when the code expires. +slow down, and stops when the code expires. An agent cannot hold that wait open, so it runs the same flow in +[two steps](#log-in-from-an-agent). Neither flow sends this computer's hostname. Their requests carry `FirstDraft-Client` like every other request ([What the CLI sends](#what-the-cli-sends)). A denied approval exits with `authorization_denied`. A login that is not approved in time exits with @@ -77,6 +82,61 @@ login still had to send, as [update line and refusals](#update-line-and-refusals `login_failed`. No credential is saved unless the login succeeds. See [Errors and recovery](errors.md#login-and-logout-errors). +### Log in from an agent + +The agent may start the login. It runs the device flow as two short commands, which +[`firstdraft start`](#check-readiness-before-work) names, and shows the person the link and the code: + +```sh +firstdraft login --no-wait +firstdraft login --finish +``` + +`--no-wait` asks First Draft for a device grant, saves it, prints these lines on standard output, and exits 0: + +```text +To log in to , ask the person to open this link in a browser, check that the page shows the code , and approve: + +The link and the code expire in minutes, at . +When the person says they approved, run 'firstdraft login --finish'. +``` + +When First Draft sends no link that includes the code, the first line asks the person to enter the code instead, and +the second is the plain verification link. On staging, each command the CLI prints for the agent ends in `--staging`. +The person approves on that page, where First Draft also asks the reports question until it has an answer. + +The device code is a credential, so the CLI never prints it; only the link and the user code appear. `--no-wait` saves +the waiting login, device code included, as `device-login.json` beside `credentials.json`, with mode `0600`; the +directory is created with mode `0700` when it does not exist. The file holds one waiting login, and another `--no-wait` replaces it. As with `login`, an unusable +credentials file stops it before any request. + +`--finish` reads that file for the selected origin and polls First Draft at the grant's interval for at most 15 +seconds from its start, each request included. It waits first when the previous poll was less than an interval ago, and a `slow_down` answer lengthens the +interval by five seconds; the file keeps both for the next `--finish`. It then says on standard output which of these +happened, and every outcome but the first also ends with its handled error on standard error: + +- **Logged in** (exit 0): it removes the file, saves the token as `login` does, and prints + `Logged in: this computer is now logged in to .` and `Run 'firstdraft start' again.` If the file cannot be + removed, a note on standard error names it; it then holds only a spent device code. +- **Still waiting** (`authorization_pending`): `Still waiting: First Draft has not confirmed that the person approved the login.`, the link + lines again, and + `The link and the code expire at . When the person says they approved, run 'firstdraft login --finish' again.` + The file stays. +- **Expired** (`authorization_expired`): + `Expired: the link and the code expired before this computer finished the login, so no new login was saved for .` + and `To try again, run 'firstdraft login --no-wait'.` +- **Refused** (`authorization_denied`): + `Refused: the person denied this login, so no new login was saved for .` and + `Ask the person before you start another login with 'firstdraft login --no-wait'.` +- **No waiting login** (`login_not_started`), when none was started for this origin or it already ended: + `No login is waiting: this computer has no device login for that has not ended.` and + `Run 'firstdraft start' to see whether this computer is logged in.` + +An expired, refused, or spent grant (`invalid_grant`) removes the file. A network failure or server error keeps it, so +`--finish` can run again. `--no-wait` and `--finish` select the origin as `login` does, may be given with +`--interactive` or `--device`, and cannot be given together. `firstdraft login --interactive` still waits in one +process for a person in their own terminal. + ### Saved credentials The token is saved in `$XDG_CONFIG_HOME/firstdraft/credentials.json`, or `~/.config/firstdraft/credentials.json` @@ -104,7 +164,7 @@ Tokens from the environment still work and take precedence over a saved login. C [First Draft](https://firstdraft.com/api-tokens) and provide it through `FIRSTDRAFT_API_TOKEN`. For staging, create a separate token at [First Draft staging](https://staging.firstdraft.com/api-tokens) and provide it through `FIRSTDRAFT_STAGING_API_TOKEN`. Keep token values out of shell history and command arguments. `login` and `logout` -note on standard error when an environment token will override the saved login. +note on standard error when an environment token will override the saved login, and `start` says so among its lines. ### Origins and projects @@ -160,6 +220,7 @@ Beyond the header, a command sends only what it needs: | Commands | Request content | | ----------------------------------------- | ---------------------------------------------------------------- | | `login`, `logout` | OAuth parameters; `logout` sends the saved token to revoke it | +| `start` | An account read, and nothing without a token | | `plan push`, `plan compile` | The exact local Plan bytes and the saved Head ETag | | `plan status`, `compilation *`, `account` | Only the IDs in the request path | | `report progress`, `report failure` | An account read; with reports on, the report printed just before | @@ -180,12 +241,14 @@ notice therefore comes from First Draft's answer to the command being run, not f - **Older than the latest:** the CLI writes one line on standard error, once per command and just before the command's own result, whether or not a terminal is attached, so an agent sees it and can pass it on: `First Draft: an update is available (plugin ; this setup has plugin ). Tell the person the update steps are at https://firstdraft.com/update`. - Without a plugin version the line names `CLI ` and `CLI `. + Without a plugin version the line names `CLI ` and `CLI `. `start` writes the same line on + standard output, after its version line. - **Older than the minimum, or a contract other than API `0.9.x`:** the CLI finishes handling that response, so local state stays in step with First Draft, and sends nothing more. When the command still had a request to send, it exits with `update_required` or `api_contract_unsupported` instead of its own result. When that response was the command's last, the command reports its own result, after one `First Draft: ` line on standard error that names - the stop and says the command finished. For an older contract, or a prerelease of a release inside the accepted range, it says to use the CLI that origin supports instead of updating; a prerelease of a newer release counts as newer. Either replaces the update line above. + the stop and says the command finished; `start` is the exception and always exits with the error, because such a + setup is not ready. For an older contract, or a prerelease of a release inside the accepted range, it says to use the CLI that origin supports instead of updating; a prerelease of a newer release counts as newer. Either replaces the update line above. - **A `429` answer**, which First Draft sends when a limit is reached, such as an account's Compilations for the day or its reports for the hour, usually with `Retry-After`: the request did nothing, and whatever else the response says, the command exits with `rate_limited` and the time to try again. @@ -194,6 +257,74 @@ A header value that is not a version is ignored, and a prerelease contract count always finishes removing the local token, so neither the stop line nor a refusal replaces its result. [Errors and recovery](errors.md#update-and-limit-errors) explains each error. +## Check readiness before work + +An agent runs `firstdraft start` once, before other First Draft work; the Skill runs it first. It selects the origin as +`login` does, with `--staging` or `FIRSTDRAFT_API_URL`: + +```sh +firstdraft start +``` + +It prints plain text for the agent on standard output, one fact per line. The sentences are fixed. The update line is +the one every command prints, and the rest ship in `src/agent-sentences.js`, where `login --no-wait` and +`login --finish` take theirs. First Draft's answer only chooses among them: the only values they carry are the origin, +versions, and the name of a token variable. It prints no token and no account fact other than whether reports are on, +and its handled errors leave out the problem text First Draft sent. + +With a token for the origin, from the environment or a saved login, `start` makes one request, `GET /v1/account`, and +reads the version headers on that answer as every command does. Without one, it makes no request. It exits 0 only when +First Draft accepted the token, and every other outcome ends with its handled error on standard error. + +The first line names the versions: `First Draft CLI .`, or `First Draft CLI with plugin .` +when `FIRSTDRAFT_PLUGIN_VERSION` holds a version. When First Draft names a newer version, the +[update line](#update-line-and-refusals) comes second. Then, by outcome: + +- **Ready, reports off** (exit 0). Nothing is said about reports: + + ```text + This computer has a saved login for . + Ready: First Draft accepted this computer's login. + ``` + +- **Ready, reports on** (exit 0). The same two lines, then the sentences that say when to send reports and with which + command: + + ```text + Reports are on: this person agreed that you send First Draft progress and failure reports about the code it generates. + Progress: run 'firstdraft report progress --step ' when bin/setup finishes (setup), when the first spec run finishes (specs_first_run), when every item under the README's Behavior to write is written (behavior_written), when the specs pass (specs_passing), and when the preview starts (preview_started). Add the counts you have; 'firstdraft report progress --help' lists them. + Failure: when generated code fails in a way the README does not list, run 'firstdraft report failure --kind ' once you have fixed it or stopped trying, where is setup_failure, spec_failure, boot_error, or lint_failure; 'firstdraft report failure --help' lists the other fields. + Use compilation.id from 'firstdraft plan compile', and run each report command from the generated application's root, or from the Project's directory after --output. Each prints what it sends: pass only text that may leave this computer, never secrets or the person's data. + ``` + +- **An environment token** (exit 0 when accepted). The login lines say which token is used: + + ```text + This computer has no saved login for . + FIRSTDRAFT_API_TOKEN is set, so the CLI uses that token in place of any saved login for , and no login is needed. + Ready: First Draft accepted FIRSTDRAFT_API_TOKEN. + ``` + + The first line says `a saved login` when one exists, and staging names `FIRSTDRAFT_STAGING_API_TOKEN`. + +- **Not logged in** (`authentication_required`, exit 1, no request). The next step is the + [agent's login](#log-in-from-an-agent): + + ```text + This computer has no saved login for . + To log in, run 'firstdraft login --no-wait'. It prints a link and a code: show both to the person and ask them to approve the login in their browser. + When the person says they approved, run 'firstdraft login --finish', then run 'firstdraft start' again. + ``` + +- **Login not accepted** (`authentication_required`, exit 1). After the login lines, a saved login First Draft + rejected gets `Not logged in: First Draft did not accept the saved login for .` and the two login steps + above. A rejected environment token gets + `Not logged in: First Draft did not accept FIRSTDRAFT_API_TOKEN. Ask the person to replace it or unset it; while it is set, the CLI uses no saved login.` +- **Below the minimum, or another API contract** (`update_required` or `api_contract_unsupported`, exit 1). The + login lines, then the [refusal](errors.md#update-and-limit-errors) instead of `Ready`. +- **Account not read** (`account_unavailable`, `invalid_server_response`, or `rate_limited`, exit 1). The login lines, + then the error. `account_unavailable` is safe to retry. + ## Start a Foundation Plan From the project that the Plan describes: @@ -631,7 +762,7 @@ retries. ## Service endpoints The CLI calls these Service API routes. The `/v1` routes send the selected token as a Bearer credential; -`account` reads `/v1/account` at the origin selected as for `login`; the report commands read it, and every other +`account` and `start` read `/v1/account` at the origin selected as for `login`; the report commands read it, and every other `/v1` request goes, to the origin pinned for the Project. The `/oauth` routes go to the origin selected for `login` or `logout` and send form-encoded OAuth parameters without a Bearer credential. Every request refuses redirects and has a bounded timeout. Each request takes its method and path from one @@ -658,10 +789,11 @@ timeout. Each request takes its method and path from one `plan push` sends the Plan `PUT`, and `plan status` reads the analysis. `plan compile` does both. It then starts a Compilation, polls it, and downloads its artifact. With `--github`, it starts and polls the Publication instead. `compilation status` reads one retained Compilation. `compilation download` reads it and downloads its artifact. -`compilation cancel` cancels it. `account` reads `/v1/account`. `report progress` and `report failure` read it and, -with reports on, post their report. +`compilation cancel` cancels it. `account` reads `/v1/account`, and `start` reads it when it has a token. +`report progress` and `report failure` read it and, with reports on, post their report. `login` exchanges its authorization code at `/oauth/token`. With `--interactive`, it starts at -`/oauth/device_authorization` and then polls `/oauth/token`. `logout` calls `/oauth/revoke`. The browser, not the +`/oauth/device_authorization` and then polls `/oauth/token`. `login --no-wait` makes only the first request, and +`login --finish` only the polls. `logout` calls `/oauth/revoke`. The browser, not the CLI, opens `/oauth/authorize` and `/device`, so they have no rows. The first push sends `If-None-Match: *`. Later pushes, the Compilation start `POST`, and the Publication `PUT` send diff --git a/docs/errors.md b/docs/errors.md index 55c85d3..272a9c8 100644 --- a/docs/errors.md +++ b/docs/errors.md @@ -10,8 +10,9 @@ write one [update or stop line](commands.md#update-line-and-refusals), and `plan both begin with the exact `First Draft: ` prefix, so machine consumers can remove only those lines and parse the remaining JSON document. `login` may first write its human-readable authorization instructions; its JSON object starts on the line after them. `report` prints what it sends on standard output before sending it, so standard -output may hold that preview when it fails. Branch on the stable `error` value rather than -the human-readable `detail`. +output may hold that preview when it fails. `start`, `login --no-wait`, and `login --finish` print their plain +sentences for the agent on standard output, which holds them when the command fails. Branch on the stable `error` +value rather than the human-readable `detail`. Handled output never includes command arguments, local Plan bytes, raw artifact bytes, raw filesystem or network errors, or unvalidated response bodies. `local_state_not_saved` is the sole exception to private-state redaction: @@ -32,13 +33,25 @@ used. The CLI never substitutes one environment's credential for another's. Run environment (with `--staging` or the same `FIRSTDRAFT_API_URL`), or refresh the environment token, then follow the command's recovery instructions below. If a saved login is rejected, run `firstdraft login` again. +From `start`, `authentication_required` means it is not ready: no token exists for the origin, so it made no +request, or First Draft rejected the token it sent. Its standard output says which and names the next step: the +[agent's two login steps](commands.md#log-in-from-an-agent), or, for a rejected environment token, asking the person +to replace or unset it. No handled error from `start` carries `response`, so none repeats text First Draft wrote. + ## Login and logout errors `login` and `logout` never print a token. A local credential failure can occur after the server has issued or revoked a token. -- `authorization_denied`: the approval was denied in the browser. Run `firstdraft login` again to retry. -- `authorization_expired`: no loopback callback arrived within five minutes, or the device code expired before - approval. Run `firstdraft login` again. Use `--interactive` if no browser on this machine can reach the printed URL. +- `authorization_denied`: the approval was denied in the browser. Run `firstdraft login` again to retry. After + `login --finish`, the person refused: ask them before starting another login with `login --no-wait`. +- `authorization_expired`: no loopback callback arrived within five minutes, or the device code expired before the + CLI received a token. Run `firstdraft login` again. Use `--interactive` if no browser on this machine can reach the printed URL. + After `login --finish`, start again with `login --no-wait`, which prints a new link and code. +- `authorization_pending`, from `login --finish`: First Draft has not confirmed an approval yet, and the CLI stopped after its + short wait. The link and the code still work until the time it prints; when the person says they approved, run + `login --finish` again. +- `login_not_started`, from `login --finish`: no waiting login started with `login --no-wait` exists for the + selected origin, or it already ended. Run `firstdraft start` to see whether this computer is logged in. - `login_failed`: the login could not be completed. `reason`, when present, is the server's OAuth error code (for example `invalid_grant` for a used, expired, or mismatched code), `loopback_unavailable` when the local listener could not start, `credentials_invalid` / `credentials_unavailable` when the credentials file could not be read or @@ -47,6 +60,11 @@ command's recovery instructions below. If a saved login is rejected, run `firstd request was made; repair or remove the file and retry. With `phase: "write"`, First Draft issued a token but the CLI could not save it. Revoke that new token on the selected origin's `/api-tokens` page, then repair the credentials file and retry login. Any previously saved token remains unchanged when the replacement fails. + `device_login_invalid` or `device_login_unavailable` means the waiting device login, `device-login.json` at + `credentials_path`, was malformed or could not be read, written, or removed; it carries no `phase`. Remove that + file, then run `firstdraft start` to see whether this computer is logged in. From `login --finish`, `reason` + `invalid_grant` means the grant is spent and its file was removed: start again with `login --no-wait`. Any other + poll failure, such as a network failure or a server error, keeps the file, so `login --finish` can run again. - `logout_failed`: the credentials file could not be read or updated. It carries `reason`, `credentials_path`, and `phase`. With `phase: "read"`, no token was revoked or removed; repair or remove the file and retry. With `phase: "write"`, local removal failed after the revocation attempt. `revoked: true` means First Draft confirmed @@ -68,6 +86,7 @@ These errors replace a command's result when a First Draft response told the CLI finished. The CLI finishes handling that response, so a push it accepted still saves its ETag, and then sends nothing more. When the stopping response was the command's last, the command reports its own result instead, after one `First Draft: ` line that names the required update ([update line and refusals](commands.md#update-line-and-refusals)). +`start` always reports the error, because a setup that must update is not ready. - `update_required`: First Draft's `FirstDraft-Minimum-Plugin` is newer than this setup's plugin, or, when no plugin version is set, its `FirstDraft-Minimum-CLI` is newer than this CLI. `plugin_version` and `minimum_plugin_version`, @@ -239,7 +258,8 @@ stopped without following the replacement. | Network commands except `logout` | `rate_limited` | 1 | First Draft refused a request at a limit; `retry_at` says when to try again. | | `plan init` | `local_initialization_failed` | 1 | Initialization failed without overwriting an existing path. | | Network commands | `invalid_configuration` | 2 | API origin or saved Head state is incompatible. | -| `login` | `authorization_denied`, `authorization_expired` | 1 | The approval was denied, or not granted before the callback wait or device code expired. | +| `login` | `authorization_denied`, `authorization_expired` | 1 | The approval was denied, or the callback wait or device code ended before the CLI received a token. | +| `login --finish` | `authorization_pending`, `login_not_started` | 1 | First Draft has not confirmed an approval yet, or no device login is waiting for the origin. | | `login` | `login_failed` | 1 | Nothing was saved; `phase: "write"` means a token was issued ([recovery](#login-and-logout-errors)). | | `logout` | `logout_failed` | 1 | Check `phase` and `revoked`; revocation may have happened ([recovery](#login-and-logout-errors)). | | Network commands | `authentication_required` | 1 | No environment or saved token exists for the origin, or First Draft rejected it. | @@ -267,7 +287,7 @@ stopped without following the replacement. | Download commands | `artifact_unavailable`, `invalid_artifact` | 1 | Artifact transport or integrity validation failed; direct Compile post-start errors include `current`. | | Download commands | `invalid_output_path` | 2 | The absent destination or root-adoption preconditions failed; `reason` identifies the stable refusal. | | Download commands | `materialization_failed` | 1 | The output changed or its transaction failed; `reason` identifies incomplete rollback when applicable. | -| `account` | `account_unavailable`, `invalid_server_response` | 1 | The account read failed or violated its contract. | +| `account`, `start` | `account_unavailable`, `invalid_server_response` | 1 | The account read failed or violated its contract. | | `report progress`, `report failure` | `report_rejected`, `report_unavailable`, `account_unavailable`, `invalid_server_response` | 1 | The report was refused or its outcome is unconfirmed, or the account read failed; continue without it. | Root-output `invalid_output_path.reason` values are `destination_exists`, `root_not_real`, `root_not_writable`, diff --git a/scripts/check-pack.js b/scripts/check-pack.js index a0456e0..4aaeb8e 100644 --- a/scripts/check-pack.js +++ b/scripts/check-pack.js @@ -36,6 +36,7 @@ if (result.status !== 0) { "docs/commands.md", "docs/errors.md", "package.json", + "src/agent-sentences.js", "src/api-authentication.js", "src/api-response.js", "src/application-identity.js", @@ -50,6 +51,7 @@ if (result.status !== 0) { "src/commands/plan-push.js", "src/commands/plan-status.js", "src/commands/report.js", + "src/commands/start.js", "src/compilation-artifact.js", "src/credentials.js", "src/file-system.js", diff --git a/scripts/smoke-package.js b/scripts/smoke-package.js index 6478d82..dfa0017 100644 --- a/scripts/smoke-package.js +++ b/scripts/smoke-package.js @@ -321,6 +321,54 @@ try { ); assert.equal(emptyLogout.stderr, ""); + const invalidStart = spawnPackedCli( + ["start", "--canary-secret-option"], + installationDirectory, + ); + assertHandledFailure(invalidStart, 2, { + error: "invalid_arguments", + detail: "Invalid arguments. Run 'firstdraft start --help' for usage.", + }); + + const loggedOutStart = spawnPackedCli(["start"], installationDirectory, { + FIRSTDRAFT_API_TOKEN: "", + FIRSTDRAFT_PLUGIN_VERSION: "0.10.0", + }); + assert.equal(loggedOutStart.status, 1); + assert.equal( + loggedOutStart.stdout, + [ + `First Draft CLI ${packageMetadata.version} with plugin 0.10.0.`, + "This computer has no saved login for https://firstdraft.com.", + "To log in, run 'firstdraft login --no-wait'. It prints a link and a code: show both to the person and ask them to approve the login in their browser.", + "When the person says they approved, run 'firstdraft login --finish', then run 'firstdraft start' again.", + "", + ].join("\n"), + ); + assert.equal( + JSON.parse(loggedOutStart.stderr).error, + "authentication_required", + ); + + const conflictingLogin = spawnPackedCli( + ["login", "--no-wait", "--finish"], + installationDirectory, + ); + assertHandledFailure(conflictingLogin, 2, { + error: "invalid_arguments", + detail: "Invalid arguments. Run 'firstdraft login --help' for usage.", + }); + + const finishWithoutLogin = spawnPackedCli( + ["login", "--finish"], + installationDirectory, + ); + assert.equal(finishWithoutLogin.status, 1); + assert.equal( + JSON.parse(finishWithoutLogin.stderr).error, + "login_not_started", + ); + exercisePackedEnvironmentSelection(temporaryDirectory); await exercisePackedCompilation(projectDirectory); } finally { diff --git a/src/agent-sentences.js b/src/agent-sentences.js new file mode 100644 index 0000000..dfbe34a --- /dev/null +++ b/src/agent-sentences.js @@ -0,0 +1,177 @@ +import { STAGING_API_URL } from "./api-authentication.js"; + +// The plain sentences the CLI prints for an agent, kept here so they are +// written once. `firstdraft start` and the two steps of the agent's device +// login print only these, besides the update line every command shares +// (src/service-client.js). A First Draft answer only chooses among them, and +// the only values they carry are an origin, versions, a token variable's +// name, and a device login's validated link, user code, and expiry. +// docs/commands.md quotes them and the Skill copies them, so a change here is +// a change to both. + +/** + * A command the agent can run as printed. A staging origin adds the flag that + * selects it; a custom origin keeps coming from FIRSTDRAFT_API_URL. + * + * @param {string} origin + * @param {string} command + */ +export function commandLine(origin, command) { + return `'firstdraft ${command}${origin === STAGING_API_URL ? " --staging" : ""}'`; +} + +/** @param {{cli: string, plugin: string | null}} versions */ +export function versionLine({ cli, plugin }) { + return plugin === null + ? `First Draft CLI ${cli}.` + : `First Draft CLI ${cli} with plugin ${plugin}.`; +} + +/** + * Whether a token for `origin` is saved on this computer or set in the + * environment, which takes precedence. + * + * @param {{origin: string, saved: boolean, environmentVariable: string | null}} login + */ +export function loginLines({ origin, saved, environmentVariable }) { + return [ + saved + ? `This computer has a saved login for ${origin}.` + : `This computer has no saved login for ${origin}.`, + ...(environmentVariable === null + ? [] + : [ + `${environmentVariable} is set, so the CLI uses that token in place of any saved login for ${origin}, and no login is needed.`, + ]), + ]; +} + +/** @param {string} origin */ +export function loginSteps(origin) { + return [ + `To log in, run ${commandLine(origin, "login --no-wait")}. It prints a link and a code: show both to the person and ask them to approve the login in their browser.`, + `When the person says they approved, run ${commandLine(origin, "login --finish")}, then run ${commandLine(origin, "start")} again.`, + ]; +} + +/** @param {string | null} environmentVariable */ +export function readyLine(environmentVariable) { + return environmentVariable === null + ? "Ready: First Draft accepted this computer's login." + : `Ready: First Draft accepted ${environmentVariable}.`; +} + +/** + * @param {string} origin + * @param {string | null} environmentVariable + */ +export function rejectedLoginLines(origin, environmentVariable) { + return environmentVariable === null + ? [ + `Not logged in: First Draft did not accept the saved login for ${origin}.`, + ...loginSteps(origin), + ] + : [ + `Not logged in: First Draft did not accept ${environmentVariable}. Ask the person to replace it or unset it; while it is set, the CLI uses no saved login.`, + ]; +} + +/** + * Printed when the person said yes to reports, and only then: the agent of a + * person who said no hears nothing about reports. Any command that tells the + * agent about reports prints these same sentences. + */ +export const REPORTS_ON_LINES = Object.freeze([ + "Reports are on: this person agreed that you send First Draft progress and failure reports about the code it generates.", + "Progress: run 'firstdraft report progress --step ' when bin/setup finishes (setup), when the first spec run finishes (specs_first_run), when every item under the README's Behavior to write is written (behavior_written), when the specs pass (specs_passing), and when the preview starts (preview_started). Add the counts you have; 'firstdraft report progress --help' lists them.", + "Failure: when generated code fails in a way the README does not list, run 'firstdraft report failure --kind ' once you have fixed it or stopped trying, where is setup_failure, spec_failure, boot_error, or lint_failure; 'firstdraft report failure --help' lists the other fields.", + "Use compilation.id from 'firstdraft plan compile', and run each report command from the generated application's root, or from the Project's directory after --output. Each prints what it sends: pass only text that may leave this computer, never secrets or the person's data.", +]); + +/** + * @typedef {object} DeviceLoginLink + * @property {string} origin + * @property {string} userCode + * @property {string} verificationUri + * @property {string | undefined} verificationUriComplete + * @property {number} expiresAt epoch milliseconds + */ + +/** + * What `login --no-wait` prints. The device code is a credential and never + * appears; the link and the user code are for the person. + * + * @param {DeviceLoginLink & {expiresIn: number}} login + */ +export function deviceLoginStartedLines(login) { + const minutes = Math.max(1, Math.floor(login.expiresIn / 60)); + return [ + ...linkLines(login), + `The link and the code expire in ${minutes} ${minutes === 1 ? "minute" : "minutes"}, at ${utcTime(login.expiresAt)}.`, + `When the person says they approved, run ${commandLine(login.origin, "login --finish")}.`, + ]; +} + +/** @param {string} origin */ +export function deviceLoginFinishedLines(origin) { + return [ + `Logged in: this computer is now logged in to ${origin}.`, + `Run ${commandLine(origin, "start")} again.`, + ]; +} + +/** @param {DeviceLoginLink} login */ +export function deviceLoginPendingLines(login) { + return [ + "Still waiting: First Draft has not confirmed that the person approved the login.", + ...linkLines(login), + `The link and the code expire at ${utcTime(login.expiresAt)}. When the person says they approved, run ${commandLine(login.origin, "login --finish")} again.`, + ]; +} + +/** @param {string} origin */ +export function deviceLoginExpiredLines(origin) { + return [ + `Expired: the link and the code expired before this computer finished the login, so no new login was saved for ${origin}.`, + `To try again, run ${commandLine(origin, "login --no-wait")}.`, + ]; +} + +/** @param {string} origin */ +export function deviceLoginRefusedLines(origin) { + return [ + `Refused: the person denied this login, so no new login was saved for ${origin}.`, + `Ask the person before you start another login with ${commandLine(origin, "login --no-wait")}.`, + ]; +} + +/** @param {string} origin */ +export function deviceLoginNotStartedLines(origin) { + return [ + `No login is waiting: this computer has no device login for ${origin} that has not ended.`, + `Run ${commandLine(origin, "start")} to see whether this computer is logged in.`, + ]; +} + +/** @param {DeviceLoginLink} login */ +function linkLines({ + origin, + userCode, + verificationUri, + verificationUriComplete, +}) { + return verificationUriComplete === undefined + ? [ + `To log in to ${origin}, ask the person to open this link in a browser, enter the code ${userCode}, and approve:`, + verificationUri, + ] + : [ + `To log in to ${origin}, ask the person to open this link in a browser, check that the page shows the code ${userCode}, and approve:`, + verificationUriComplete, + ]; +} + +/** @param {number} milliseconds */ +function utcTime(milliseconds) { + return new Date(milliseconds).toISOString().replace(/\.\d{3}Z$/, "Z"); +} diff --git a/src/api-authentication.js b/src/api-authentication.js index 087deae..fd47431 100644 --- a/src/api-authentication.js +++ b/src/api-authentication.js @@ -35,6 +35,13 @@ export function environmentTokenFor(origin, { apiToken, stagingApiToken }) { return hasToken(token) ? token : undefined; } +/** The variable that holds the environment token for an origin. @param {string} origin */ +export function environmentTokenVariable(origin) { + return origin === STAGING_API_URL + ? "FIRSTDRAFT_STAGING_API_TOKEN" + : "FIRSTDRAFT_API_TOKEN"; +} + /** * @param {object} options * @param {typeof globalThis.fetch} [options.fetchFunction] @@ -69,7 +76,7 @@ export function authenticateApiCommand({ /** @param {string} origin */ const tokenFor = (origin) => environmentTokenFor(origin, { apiToken, stagingApiToken }) ?? - storedToken(readStoredTokens(), origin); + storedTokenFor(readStoredTokens(), origin); /** @type {typeof globalThis.fetch} */ const authorizedFetch = (input, init) => { const endpoint = new URL(input instanceof Request ? input.url : input); @@ -97,8 +104,13 @@ export function authenticateApiCommand({ }; } -/** @param {Readonly>} tokens @param {string} origin */ -function storedToken(tokens, origin) { +/** + * The token a saved login holds for exactly this origin, if any. + * + * @param {Readonly>} tokens + * @param {string} origin + */ +export function storedTokenFor(tokens, origin) { const token = Object.hasOwn(tokens, origin) ? tokens[origin] : undefined; return hasToken(token) ? token : undefined; } diff --git a/src/cli.js b/src/cli.js index eb5143b..2285edf 100644 --- a/src/cli.js +++ b/src/cli.js @@ -6,11 +6,27 @@ import { isValidApplicationKey, isValidApplicationName, } from "./application-identity.js"; +import { + REPORTS_ON_LINES, + commandLine, + deviceLoginExpiredLines, + deviceLoginFinishedLines, + deviceLoginNotStartedLines, + deviceLoginPendingLines, + deviceLoginRefusedLines, + deviceLoginStartedLines, + loginLines, + loginSteps, + readyLine, + rejectedLoginLines, + versionLine, +} from "./agent-sentences.js"; import { ApiAuthenticationRequiredError, STAGING_API_URL, authenticateApiCommand, environmentTokenFor, + environmentTokenVariable, isAuthenticationProblem, } from "./api-authentication.js"; import { @@ -51,8 +67,12 @@ import { LoginDeniedError, LoginExpiredError, LoginFailedError, + LoginNotStartedError, + LoginPendingError, + finishDeviceLogin, login, resolveLoginOrigin, + startDeviceLogin, } from "./commands/login.js"; import { LogoutFailedError, logout } from "./commands/logout.js"; import { initializePlan } from "./commands/plan-init.js"; @@ -97,6 +117,7 @@ import { progressReportBody, sendReport, } from "./commands/report.js"; +import { readLoginState, readReadiness } from "./commands/start.js"; import { SERVICE_ROUTES } from "./api-response.js"; import { storedTokenReader } from "./credentials.js"; import { isFileSystemError } from "./file-system.js"; @@ -133,6 +154,7 @@ Commands: logout Revoke and remove the saved token plan Work with Foundation Plans report Send a progress or failure report to First Draft + start Check versions, login, and reports before other work Options: --staging Use staging for API commands (production is the default) @@ -159,6 +181,27 @@ progress and failure reports. Only the person turns reports on or off: when approving firstdraft login, or later on their First Draft account page. `; +const START_HELP = `First Draft CLI + +Usage: + firstdraft start + +Options: + --staging Use staging + -h, --help Show help + +Environment: + FIRSTDRAFT_API_TOKEN Authenticate production or custom API origins + FIRSTDRAFT_STAGING_API_TOKEN Authenticate staging.firstdraft.com + FIRSTDRAFT_API_URL Use a custom API origin + +An agent runs this once before other First Draft work. It prints the versions, +any update notice, whether this computer is logged in and how to log in if +not, and, when the person agreed to reports, when to send them. With a token +it reads the account once; without one it makes no request. It exits 0 only +when First Draft accepted the login. +`; + const REPORT_HELP = `First Draft CLI Usage: @@ -435,11 +478,15 @@ const LOGIN_HELP = `First Draft CLI Usage: firstdraft login [--interactive] + firstdraft login --no-wait + firstdraft login --finish Options: --staging Log in to staging -i, --interactive Approve with a code on another device (no local browser) --device Same as --interactive + --no-wait Start a device login, print its link and code, and exit + --finish Finish the device login that --no-wait started -h, --help Show help Environment: @@ -451,6 +498,10 @@ waits up to five minutes for First Draft to redirect to a one-time listener on 127.0.0.1. The token is saved for the selected origin in firstdraft/credentials.json under the configuration directory and is never printed. Token environment variables take precedence over a saved login. + +An agent logs in with two short commands. --no-wait saves the waiting login in +firstdraft/device-login.json and exits; once the person approves, --finish +waits at most 15 seconds, saves the token, and removes that file. `; const LOGOUT_HELP = `First Draft CLI @@ -512,6 +563,8 @@ const LOGIN_EXPIRED_DETAIL = "The login was not approved before it expired. No credential was saved. Run 'firstdraft login' again to retry."; const LOGIN_FAILED_DETAIL = "The login could not be completed. No credential was saved. Run 'firstdraft login' again, or use 'firstdraft login --interactive' if this machine has no browser."; +const START_INVALID_ARGUMENTS_DETAIL = + "Invalid arguments. Run 'firstdraft start --help' for usage."; const LOGIN_CREDENTIALS_DETAIL = "The credentials file could not be read. No network request was made. Repair or remove it, then run 'firstdraft login' again."; const CREDENTIALS_LOCKED_RECOVERY = @@ -805,9 +858,12 @@ export async function run({ fileSystem: credentialsFileSystem, lockTimeoutMs: credentialsLockTimeoutMs, }; + // `start` says everything for the agent on standard output, its update line + // included; every other command writes that line on standard error. + const notices = argv[0] === "start" ? stdout : stderr; const service = createServiceSession({ env, - notify: (line) => stderr.write(line), + notify: (line) => notices.write(line), now: serviceNow, }); @@ -830,10 +886,11 @@ export async function run({ }); } - if (argv[0] === "account" || argv[0] === "report") { + if (argv[0] === "account" || argv[0] === "report" || argv[0] === "start") { const commands = { account: runAccount, report: runReport, + start: runStart, }; return commands[argv[0]]({ argv: argv.slice(1), @@ -1684,6 +1741,8 @@ async function runLogin({ staging: { type: "boolean" }, interactive: { type: "boolean", short: "i" }, device: { type: "boolean" }, + "no-wait": { type: "boolean" }, + finish: { type: "boolean" }, help: { type: "boolean", short: "h" }, }, allowPositionals: false, @@ -1695,7 +1754,8 @@ async function runLogin({ if ( !parsed || repeatedValueOption(parsed.tokens) || - (parsed.values.interactive && parsed.values.device) + (parsed.values.interactive && parsed.values.device) || + (parsed.values["no-wait"] && parsed.values.finish) ) { writeJson(stderr, { error: "invalid_arguments", @@ -1715,6 +1775,24 @@ async function runLogin({ }); if (origin === null) return 2; + // Both steps of the agent's device login imply the device flow, so + // --interactive and --device may accompany them without changing anything. + if (parsed.values["no-wait"] || parsed.values.finish) { + return (parsed.values.finish ? runLoginFinish : runLoginNoWait)({ + origin, + stdout, + stderr, + fetchFunction, + createRequestSignal, + credentials, + loginSleep, + loginNow, + apiToken, + stagingApiToken, + service, + }); + } + try { await service.settle( login({ @@ -1730,52 +1808,210 @@ async function runLogin({ }), ); } catch (error) { - const stopStatus = writeServiceStop(stderr, error); - if (stopStatus !== null) return stopStatus; + const status = writeLoginError(stderr, error, origin, { + denied: LOGIN_DENIED_DETAIL, + expired: LOGIN_EXPIRED_DETAIL, + failed: LOGIN_FAILED_DETAIL, + }); + if (status !== null) return status; - if (error instanceof LoginDeniedError) { + throw error; + } + + stdout.write(`Logged in to ${origin}\n`); + writeEnvironmentTokenNote(stderr, origin, { apiToken, stagingApiToken }); + return 0; +} + +/** + * @typedef {Pick & {origin: string}} DeviceLoginCommandOptions + */ + +/** + * The agent's first login step: prints the link and the code in fixed + * sentences on standard output and exits without waiting. + * + * @param {DeviceLoginCommandOptions} options + */ +async function runLoginNoWait({ + origin, + stdout, + stderr, + fetchFunction, + createRequestSignal, + credentials, + loginNow, + service, +}) { + let login; + try { + login = await service.settle( + startDeviceLogin({ + origin, + fetchFunction: service.fetch(fetchFunction), + createRequestSignal, + now: loginNow, + credentials, + }), + ); + } catch (error) { + const status = writeLoginError(stderr, error, origin, { + denied: LOGIN_DENIED_DETAIL, + expired: LOGIN_EXPIRED_DETAIL, + failed: `The login could not be started. No credential was saved. Run ${commandLine(origin, "login --no-wait")} again.`, + retry: commandLine(origin, "login --no-wait"), + }); + if (status !== null) return status; + + throw error; + } + + writeLines(stdout, deviceLoginStartedLines(login)); + return 0; +} + +/** + * The agent's second login step: says whether this computer is now logged + * in, still waiting, expired, or refused. + * + * @param {DeviceLoginCommandOptions} options + */ +async function runLoginFinish({ + origin, + stdout, + stderr, + fetchFunction, + createRequestSignal, + credentials, + loginSleep, + loginNow, + apiToken, + stagingApiToken, + service, +}) { + const restart = commandLine(origin, "login --no-wait"); + let finished; + try { + finished = await service.settle( + finishDeviceLogin({ + origin, + fetchFunction: service.fetch(fetchFunction), + createRequestSignal, + sleep: loginSleep, + now: loginNow, + credentials, + }), + ); + } catch (error) { + if (error instanceof LoginPendingError) { + writeLines(stdout, deviceLoginPendingLines(error.login)); writeJson(stderr, { - error: "authorization_denied", - detail: LOGIN_DENIED_DETAIL, + error: "authorization_pending", + detail: `First Draft has not confirmed that the person approved the login, and the CLI stopped waiting. When the person says they approved, run ${commandLine(origin, "login --finish")} again.`, }); return 1; } - if (error instanceof LoginExpiredError) { + if (error instanceof LoginNotStartedError) { + writeLines(stdout, deviceLoginNotStartedLines(origin)); writeJson(stderr, { - error: "authorization_expired", - detail: LOGIN_EXPIRED_DETAIL, + error: "login_not_started", + detail: `No device login is waiting for ${origin}: none was started with ${restart}, or it already ended. Run ${commandLine(origin, "start")} to see whether this computer is logged in.`, }); return 1; } - if (error instanceof LoginFailedError) { - writeJson(stderr, { - error: "login_failed", - detail: - error.credentialsPath === undefined - ? LOGIN_FAILED_DETAIL - : error.phase === "write" - ? `First Draft issued a token, but it could not be saved. Revoke the new token at ${origin}/api-tokens, then ${credentialsRecovery(error.reason)} and retry login.` - : LOGIN_CREDENTIALS_DETAIL, - ...(error.phase === undefined ? {} : { phase: error.phase }), - ...(error.reason === undefined ? {} : { reason: error.reason }), - ...(error.status === undefined ? {} : { status: error.status }), - ...(error.credentialsPath === undefined - ? {} - : { credentials_path: error.credentialsPath }), - }); - return 1; + if (error instanceof LoginDeniedError) { + writeLines(stdout, deviceLoginRefusedLines(origin)); + } else if (error instanceof LoginExpiredError) { + writeLines(stdout, deviceLoginExpiredLines(origin)); } + const status = writeLoginError(stderr, error, origin, { + denied: `The login was denied in the browser. No credential was saved. Ask the person before you start another login with ${restart}.`, + expired: `The login expired before this computer finished it. No credential was saved. Run ${restart} to start again.`, + failed: + error instanceof LoginFailedError && error.reason === "invalid_grant" + ? `The login could not be finished, and no credential was saved. Start again with ${restart}.` + : `The login could not be finished, and no credential was saved. Run ${commandLine(origin, "login --finish")} again; if it fails again, start over with ${restart}.`, + retry: commandLine(origin, "login --finish"), + }); + if (status !== null) return status; throw error; } - stdout.write(`Logged in to ${origin}\n`); + writeLines(stdout, deviceLoginFinishedLines(origin)); + if (finished.leftover !== null) { + stderr.write( + `Note: ${finished.leftover} could not be removed. It holds only a spent device code; remove it.\n`, + ); + } writeEnvironmentTokenNote(stderr, origin, { apiToken, stagingApiToken }); return 0; } +/** + * Writes the handled error of a login, in any of its forms. + * + * @param {Writer} stderr + * @param {unknown} error + * @param {string} origin + * @param {{denied: string, expired: string, failed: string, retry?: string}} details + * `retry` names the command to run again after a credentials read failure + * @returns {number | null} + */ +function writeLoginError(stderr, error, origin, details) { + const stopStatus = writeServiceStop(stderr, error); + if (stopStatus !== null) return stopStatus; + + if (error instanceof LoginDeniedError) { + writeJson(stderr, { + error: "authorization_denied", + detail: details.denied, + }); + return 1; + } + + if (error instanceof LoginExpiredError) { + writeJson(stderr, { + error: "authorization_expired", + detail: details.expired, + }); + return 1; + } + + if (error instanceof LoginFailedError) { + writeJson(stderr, { + error: "login_failed", + detail: + error.credentialsPath === undefined + ? details.failed + : error.reason === "device_login_invalid" || + error.reason === "device_login_unavailable" + ? `The device login file at credentials_path could not be used. Remove it, then run ${commandLine(origin, "start")} to see whether this computer is logged in.` + : error.phase === "write" + ? `First Draft issued a token, but it could not be saved. Revoke the new token at ${origin}/api-tokens, then ${credentialsRecovery(error.reason)} and retry login.` + : details.retry === undefined + ? LOGIN_CREDENTIALS_DETAIL + : `The credentials file could not be read. No network request was made. Repair or remove it, then run ${details.retry} again.`, + ...(error.phase === undefined ? {} : { phase: error.phase }), + ...(error.reason === undefined ? {} : { reason: error.reason }), + ...(error.status === undefined ? {} : { status: error.status }), + ...(error.credentialsPath === undefined + ? {} + : { credentials_path: error.credentialsPath }), + }); + return 1; + } + + return null; +} + +/** @param {Writer} writer @param {readonly string[]} lines */ +function writeLines(writer, lines) { + writer.write(lines.map((line) => `${line}\n`).join("")); +} + /** @param {LoginCommandOptions} options */ async function runLogout({ argv, @@ -1912,12 +2148,8 @@ function selectLoginOrigin(stderr, options) { function writeEnvironmentTokenNote(stderr, origin, tokens) { if (environmentTokenFor(origin, tokens) === undefined) return; - const variable = - origin === STAGING_API_URL - ? "FIRSTDRAFT_STAGING_API_TOKEN" - : "FIRSTDRAFT_API_TOKEN"; stderr.write( - `Note: ${variable} is set and takes precedence over the saved login for ${origin}.\n`, + `Note: ${environmentTokenVariable(origin)} is set and takes precedence over the saved login for ${origin}.\n`, ); } @@ -3146,13 +3378,152 @@ async function runAccount({ } } +/** + * Prints, for the agent, the facts it needs before other work, in the fixed + * sentences of src/agent-sentences.js. Exits 0 only when First Draft + * accepted the login. + * + * @param {ServiceCommandOptions} options + */ +async function runStart({ + argv, + stdout, + stderr, + fetchFunction, + createRequestSignal, + credentials, + apiUrl, + apiToken, + stagingApiToken, + staging, + service, +}) { + const parsed = parseArguments(() => + parseArgs({ + args: [...argv], + options: { + staging: { type: "boolean" }, + help: { type: "boolean", short: "h" }, + }, + allowPositionals: false, + strict: true, + tokens: true, + }), + ); + + if (!parsed || repeatedValueOption(parsed.tokens)) { + writeJson(stderr, { + error: "invalid_arguments", + detail: START_INVALID_ARGUMENTS_DETAIL, + }); + return 2; + } + + if (parsed.values.help) { + stdout.write(START_HELP); + return 0; + } + + const selectedStaging = staging || parsed.values.staging; + const origin = selectLoginOrigin(stderr, { + apiUrl, + staging: selectedStaging, + }); + if (origin === null) return 2; + + writeLines(stdout, [ + versionLine({ cli: VERSION, plugin: service.pluginVersion }), + ]); + const readStoredTokens = storedTokenReader(credentials); + const login = readLoginState({ + origin, + apiToken, + stagingApiToken, + readStoredTokens, + }); + const loginSentences = loginLines(login); + const logIn = `Log in with ${commandLine(origin, "login --no-wait")} and, once the person approves, ${commandLine(origin, "login --finish")}.`; + + const authentication = authenticateApiCommand({ + fetchFunction: service.fetch(fetchFunction), + apiUrl: origin, + apiToken, + stagingApiToken, + staging: selectedStaging, + readStoredTokens, + }); + if (authentication === null || !authentication.hasTokenFor(origin)) { + writeLines(stdout, [...loginSentences, ...loginSteps(origin)]); + writeJson(stderr, { + error: "authentication_required", + detail: `This computer has no token for ${origin}, so the CLI made no request. ${logIn}`, + }); + return 1; + } + + try { + const account = await service.settle( + readReadiness({ + origin, + fetchFunction: authentication.fetchFunction, + createRequestSignal, + service, + }), + ); + writeLines(stdout, [ + ...loginSentences, + readyLine(login.environmentVariable), + ...(account.reports === "on" ? REPORTS_ON_LINES : []), + ]); + return 0; + } catch (error) { + if ( + error instanceof AccountUnavailableError && + isAuthenticationProblem(error.status, error.response) + ) { + writeLines(stdout, [ + ...loginSentences, + ...rejectedLoginLines(origin, login.environmentVariable), + ]); + writeJson(stderr, { + error: "authentication_required", + detail: + login.environmentVariable === null + ? `First Draft did not accept the saved login for ${origin}. ${logIn}` + : `First Draft did not accept ${login.environmentVariable}. Ask the person to replace it or unset it.`, + status: error.status, + }); + return 1; + } + + writeLines(stdout, loginSentences); + // `start` passes on no text that First Draft wrote, so its errors leave + // out the problem's own words. + const status = + writeAccountCommandError(stderr, error, { serviceText: false }) ?? + writeAccountReadError(stderr, error, { + unavailable: `Could not read the account, so the CLI could not check the login or the reports choice. This read-only request is safe to retry: run ${commandLine(origin, "start")} again.`, + invalid: ACCOUNT_INVALID_RESPONSE_DETAIL, + serviceText: false, + }); + if (status !== null) return status; + + throw error; + } +} + /** * @param {Writer} writer * @param {unknown} error - * @param {{unavailable: string, invalid: string}} details + * @param {{unavailable: string, invalid: string, serviceText?: boolean}} details + * `serviceText: false` leaves out the problem First Draft sent * @returns {number | null} */ -function writeAccountReadError(writer, error, { unavailable, invalid }) { +function writeAccountReadError( + writer, + error, + { unavailable, invalid, serviceText = true }, +) { if (error instanceof AccountUnavailableError) { if (isAuthenticationProblem(error.status, error.response)) { writeAuthenticationRequired(writer, error.status, error.response); @@ -3162,7 +3533,7 @@ function writeAccountReadError(writer, error, { unavailable, invalid }) { error: "account_unavailable", detail: unavailable, ...(typeof error.status === "number" ? { status: error.status } : {}), - ...(error.response ? { response: error.response } : {}), + ...(serviceText && error.response ? { response: error.response } : {}), }); return 1; } @@ -3604,9 +3975,10 @@ function authenticateAccountCommand( * * @param {Writer} writer * @param {unknown} error + * @param {{serviceText?: boolean}} [options] passed to writeServiceStop */ -function writeAccountCommandError(writer, error) { - const stopStatus = writeServiceStop(writer, error); +function writeAccountCommandError(writer, error, options) { + const stopStatus = writeServiceStop(writer, error, options); if (stopStatus !== null) return stopStatus; if (error instanceof ApiAuthenticationRequiredError) { @@ -3632,9 +4004,11 @@ function writeAccountCommandError(writer, error) { * * @param {Writer} writer * @param {unknown} error + * @param {{serviceText?: boolean}} [options] `serviceText: false` leaves out + * the problem First Draft sent with a limit, and the advice to read it * @returns {number | null} */ -function writeServiceStop(writer, error) { +function writeServiceStop(writer, error, { serviceText = true } = {}) { if (!(error instanceof ServiceStopError)) return null; const current = @@ -3685,12 +4059,15 @@ function writeServiceStop(writer, error) { } const retryAt = error instanceof RateLimitedError ? error.retryAt : undefined; - const limit = error instanceof RateLimitedError ? error.response : null; + const limit = + serviceText && error instanceof RateLimitedError ? error.response : null; // A limit without Retry-After or a problem detail, such as the one shared // by device logins, lasts about a minute. const retry = retryAt !== undefined - ? `Try again after ${retryAt}; response.detail, when present, says which limit.` + ? serviceText + ? `Try again after ${retryAt}; response.detail, when present, says which limit.` + : `Try again after ${retryAt}.` : limit ? "Try again when response.detail says." : "Try again in a minute."; @@ -3706,9 +4083,7 @@ function writeServiceStop(writer, error) { ...(error instanceof RateLimitedError && error.retryAt !== undefined ? { retry_at: error.retryAt } : {}), - ...(error instanceof RateLimitedError && error.response - ? { response: error.response } - : {}), + ...(limit ? { response: limit } : {}), ...(current === undefined ? {} : { current }), }); return 1; diff --git a/src/commands/login.js b/src/commands/login.js index a2d6bcb..3ca5ab3 100644 --- a/src/commands/login.js +++ b/src/commands/login.js @@ -8,27 +8,52 @@ import { CredentialsInvalidError, CredentialsLockedError, credentialsPath, + deleteDeviceLogin, + deviceLoginPath, readCredentials, + readDeviceLogin, writeCredential, + writeDeviceLogin, } from "../credentials.js"; import { isFileSystemError } from "../file-system.js"; import { LOOPBACK_TIMEOUT_MS, OAuthError, + SLOW_DOWN_INCREMENT_MS, authorizationUrl, createPkcePair, createState, exchangeAuthorizationCode, pollDeviceToken, requestDeviceAuthorization, + requestDeviceToken, startLoopbackServer, } from "../oauth.js"; import { normalizeApiUrl } from "../plan-state.js"; import { DEFAULT_API_URL } from "./plan-push.js"; +/** How long `login --finish` keeps asking before it says it is still waiting. */ +export const FINISH_WAIT_MS = 15_000; + +// The answers after which a device grant can never yield a token, so its +// saved device login is removed. +const ENDED_GRANT_CODES = ["access_denied", "expired_token", "invalid_grant"]; + export class LoginDeniedError extends Error {} export class LoginExpiredError extends Error {} +/** No device login started with --no-wait is waiting for the origin. */ +export class LoginNotStartedError extends Error {} + +/** First Draft has not confirmed that the person approved the device login. */ +export class LoginPendingError extends Error { + /** @param {import("../credentials.js").DeviceLogin} login */ + constructor(login) { + super("The device login is still waiting for approval."); + this.login = login; + } +} + export class LoginFailedError extends Error { /** * @param {string} message @@ -91,17 +116,7 @@ export async function login({ const request = { origin, fetchFunction, createRequestSignal }; /** @param {import("../oauth.js").AccessToken} token */ - const save = (token) => { - try { - writeCredential(credentials, origin, { - access_token: token.access_token, - token_type: token.token_type, - created_at: new Date(now()).toISOString(), - }); - } catch (error) { - throw credentialsError(error, credentials, "write"); - } - }; + const save = (token) => saveToken(credentials, origin, token, now); try { if (device) { @@ -226,6 +241,224 @@ async function deviceLogin({ prompt, sleep, now, ...request }) { }); } +/** + * @typedef {object} DeviceLoginOptions + * @property {string} origin + * @property {typeof globalThis.fetch} [fetchFunction] + * @property {(timeoutMs?: number) => AbortSignal} [createRequestSignal] + * @property {(delayMs: number, signal?: AbortSignal) => Promise} [sleep] + * @property {() => number} [now] + * @property {import("../credentials.js").CredentialStore} [credentials] + */ + +/** + * The first step of a device login that an agent can run: asks First Draft + * for a device grant, saves what `finishDeviceLogin` needs, and returns + * without waiting for approval. The saved login replaces any other. + * + * @param {DeviceLoginOptions} options + * @returns {Promise} + */ +export async function startDeviceLogin({ + origin, + fetchFunction, + createRequestSignal, + now = Date.now, + credentials = {}, +}) { + // The token is saved there later, so an unusable file stops the login + // before the person is asked to approve it. + readStore(credentials); + + let authorization; + try { + authorization = await requestDeviceAuthorization({ + origin, + fetchFunction, + createRequestSignal, + }); + } catch (error) { + throw loginError(error); + } + + const startedAt = now(); + const login = { + origin, + deviceCode: authorization.deviceCode, + userCode: authorization.userCode, + verificationUri: authorization.verificationUri, + verificationUriComplete: authorization.verificationUriComplete, + interval: authorization.interval, + expiresAt: startedAt + authorization.expiresIn * 1000, + // First Draft answers a grant's first poll whenever it comes. + nextPollAt: startedAt, + }; + withDeviceLogin(credentials, () => writeDeviceLogin(credentials, login)); + return { ...login, expiresIn: authorization.expiresIn }; +} + +/** + * The second step: polls the waiting device login at its interval, for at + * most FINISH_WAIT_MS from the start of the command with each request + * included, and saves the token once the person has approved. Removes the + * saved device login when the grant has ended, and otherwise keeps it with + * the next time First Draft accepts a poll. + * + * @param {DeviceLoginOptions} options + * @returns {Promise<{origin: string, leftover: string | null}>} `leftover` + * names the spent device login file when it could not be removed + */ +export async function finishDeviceLogin({ + origin, + fetchFunction, + createRequestSignal = (timeoutMs) => AbortSignal.timeout(timeoutMs ?? 0), + sleep = defaultSleep, + now = Date.now, + credentials = {}, +}) { + const deadline = now() + FINISH_WAIT_MS; + const waiting = withDeviceLogin(credentials, () => + readDeviceLogin(credentials), + ); + if (waiting === null || waiting.origin !== origin) { + throw new LoginNotStartedError("No device login is waiting."); + } + readStore(credentials); + + const expired = () => { + withDeviceLogin(credentials, () => deleteDeviceLogin(credentials)); + return new LoginExpiredError("The device code expired."); + }; + let { interval } = waiting; + // Never more than one interval away, even after the clock moved back. + let nextPollAt = Math.min(waiting.nextPollAt, now() + interval * 1000); + const keep = () => { + nextPollAt = now() + interval * 1000; + withDeviceLogin(credentials, () => + writeDeviceLogin(credentials, { ...waiting, interval, nextPollAt }), + ); + }; + + while (true) { + if (now() >= waiting.expiresAt) throw expired(); + if (nextPollAt >= deadline || nextPollAt >= waiting.expiresAt) { + throw new LoginPendingError({ ...waiting, interval, nextPollAt }); + } + const delayMs = nextPollAt - now(); + if (delayMs > 0) await sleep(delayMs); + if (now() >= waiting.expiresAt) throw expired(); + // A timer can wake late; no poll starts after the wait has ended. + const remainingMs = deadline - now(); + if (remainingMs <= 0) { + throw new LoginPendingError({ ...waiting, interval, nextPollAt }); + } + + let result; + try { + result = await requestDeviceToken({ + origin, + fetchFunction, + createRequestSignal: () => createRequestSignal(remainingMs), + deviceCode: waiting.deviceCode, + }); + } catch (error) { + if ( + error instanceof OAuthError && + error.code !== undefined && + ENDED_GRANT_CODES.includes(error.code) + ) { + withDeviceLogin(credentials, () => deleteDeviceLogin(credentials)); + } else { + // The poll may have reached First Draft, so the next one waits. + keep(); + } + throw loginError(error); + } + + if (!("pending" in result)) { + // The grant is spent once it issues a token, so its file goes first, + // whether or not the token can then be saved. + const removed = removeSpentDeviceLogin(credentials); + saveToken(credentials, origin, result, now); + return { + origin, + leftover: removed ? null : deviceLoginPath(credentials), + }; + } + + if (result.pending === "slow_down") { + interval += SLOW_DOWN_INCREMENT_MS / 1000; + } + // A pending answer that arrived after the expiry is an expired grant. + if (now() >= waiting.expiresAt) throw expired(); + keep(); + } +} + +/** + * Removes a device login whose grant has issued its token. A spent device + * code authenticates nothing, so a file that cannot be removed does not fail + * the login; the caller says where it is. + * + * @param {import("../credentials.js").CredentialStore} credentials + */ +function removeSpentDeviceLogin(credentials) { + try { + deleteDeviceLogin(credentials); + return true; + } catch (error) { + if (!isFileSystemError(error)) throw error; + return false; + } +} + +/** + * Runs an operation on the saved device login file, reporting a file-system + * failure or a malformed file as a failed login. + * + * @template T + * @param {import("../credentials.js").CredentialStore} credentials + * @param {() => T} callback + * @returns {T} + */ +function withDeviceLogin(credentials, callback) { + try { + return callback(); + } catch (error) { + if ( + !(error instanceof CredentialsInvalidError) && + !isFileSystemError(error) + ) + throw error; + throw new LoginFailedError("The device login file could not be used.", { + reason: + error instanceof CredentialsInvalidError + ? "device_login_invalid" + : "device_login_unavailable", + credentialsPath: deviceLoginPath(credentials), + cause: error, + }); + } +} + +/** + * @param {import("../credentials.js").CredentialStore} credentials + * @param {string} origin + * @param {import("../oauth.js").AccessToken} token + * @param {() => number} now + */ +function saveToken(credentials, origin, token, now) { + try { + writeCredential(credentials, origin, { + access_token: token.access_token, + token_type: token.token_type, + created_at: new Date(now()).toISOString(), + }); + } catch (error) { + throw credentialsError(error, credentials, "write"); + } +} + /** @param {import("../credentials.js").CredentialStore} credentials */ function readStore(credentials) { try { diff --git a/src/commands/start.js b/src/commands/start.js new file mode 100644 index 0000000..2e55d58 --- /dev/null +++ b/src/commands/start.js @@ -0,0 +1,52 @@ +import { + environmentTokenFor, + environmentTokenVariable, + storedTokenFor, +} from "../api-authentication.js"; +import { readAccount } from "./account.js"; + +/** + * Which token a request to `origin` would carry: one set in the environment + * takes precedence over a saved login. + * + * @param {object} options + * @param {string} options.origin + * @param {string} [options.apiToken] + * @param {string} [options.stagingApiToken] + * @param {() => Readonly>} options.readStoredTokens + * from storedTokenReader, which reads an unreadable or malformed + * credentials file as no saved login, as every other command does + * @returns {{origin: string, saved: boolean, environmentVariable: string | null}} + */ +export function readLoginState({ + origin, + apiToken, + stagingApiToken, + readStoredTokens, +}) { + return { + origin, + saved: storedTokenFor(readStoredTokens(), origin) !== undefined, + environmentVariable: + environmentTokenFor(origin, { apiToken, stagingApiToken }) === undefined + ? null + : environmentTokenVariable(origin), + }; +} + +/** + * The one request `firstdraft start` makes. A response that told the CLI to + * stop, such as a minimum version this setup is below, leaves it not ready, + * so it replaces the result, a failed one included, although no later + * request was left to send. + * + * @param {import("./account.js").ReadAccountOptions & {service: import("../service-client.js").ServiceSession}} options + */ +export async function readReadiness({ service, ...request }) { + const account = await readAccount(request).catch((error) => { + service.throwIfStopped(); + throw error; + }); + service.throwIfStopped(); + return account; +} diff --git a/src/credentials.js b/src/credentials.js index efa8861..db648b4 100644 --- a/src/credentials.js +++ b/src/credentials.js @@ -13,7 +13,10 @@ import path from "node:path"; import { isFileSystemError } from "./file-system.js"; export const CREDENTIALS_FORMAT = "firstdraft.cli-credentials/1"; +export const DEVICE_LOGIN_FORMAT = "firstdraft.cli-device-login/1"; const MAX_CREDENTIALS_BYTES = 256 * 1024; +const MAX_DEVICE_LOGIN_BYTES = 16 * 1024; +const USER_CODE = /^[\x21-\x7e]{1,64}$/; const LOCK_TIMEOUT_MS = 10_000; const LOCK_RETRY_MS = 25; @@ -93,6 +96,113 @@ export function credentialsPath(store = {}) { return path.join(base, "firstdraft", "credentials.json"); } +/** + * `device-login.json` beside the credentials file. It holds the one device + * login that `login --no-wait` started and `login --finish` has not ended, + * including its device code, which is a credential. + * + * @param {CredentialStore} [store] + */ +export function deviceLoginPath(store = {}) { + return path.join(path.dirname(credentialsPath(store)), "device-login.json"); +} + +/** + * @typedef {object} DeviceLogin + * @property {string} origin + * @property {string} deviceCode + * @property {string} userCode + * @property {string} verificationUri + * @property {string | undefined} verificationUriComplete + * @property {number} interval seconds between polls + * @property {number} expiresAt epoch milliseconds + * @property {number} nextPollAt epoch milliseconds + */ + +/** + * Reads the waiting device login, or null when there is none. A malformed + * file throws CredentialsInvalidError. + * + * @param {CredentialStore} [store] + * @returns {DeviceLogin | null} + */ +export function readDeviceLogin(store = {}) { + const fileSystem = store.fileSystem ?? DEFAULT_FILE_SYSTEM; + let source; + try { + source = fileSystem.readFileSync(deviceLoginPath(store)); + } catch (error) { + if (isMissingFileError(error)) return null; + throw error; + } + + const parsed = + source.byteLength > MAX_DEVICE_LOGIN_BYTES ? null : parseJson(source); + if ( + !isRecord(parsed) || + parsed.format !== DEVICE_LOGIN_FORMAT || + typeof parsed.origin !== "string" || + typeof parsed.device_code !== "string" || + parsed.device_code.length === 0 || + typeof parsed.user_code !== "string" || + !USER_CODE.test(parsed.user_code) || + !isHttpUrl(parsed.verification_uri) || + (parsed.verification_uri_complete !== undefined && + !isHttpUrl(parsed.verification_uri_complete)) || + !Number.isSafeInteger(parsed.interval) || + Number(parsed.interval) <= 0 || + typeof parsed.expires_at !== "string" || + !Number.isFinite(Date.parse(parsed.expires_at)) || + typeof parsed.next_poll_at !== "string" || + !Number.isFinite(Date.parse(parsed.next_poll_at)) + ) { + throw new CredentialsInvalidError("The device login file is invalid."); + } + + return { + origin: parsed.origin, + deviceCode: parsed.device_code, + userCode: parsed.user_code, + verificationUri: parsed.verification_uri, + verificationUriComplete: parsed.verification_uri_complete, + interval: Number(parsed.interval), + expiresAt: Date.parse(parsed.expires_at), + nextPollAt: Date.parse(parsed.next_poll_at), + }; +} + +/** + * Saves the waiting device login with mode 0600, replacing any other. + * + * @param {CredentialStore} store + * @param {DeviceLogin} login + */ +export function writeDeviceLogin(store, login) { + const fileSystem = store.fileSystem ?? DEFAULT_FILE_SYSTEM; + const target = deviceLoginPath(store); + fileSystem.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 }); + writePrivateFile(store, target, { + format: DEVICE_LOGIN_FORMAT, + origin: login.origin, + device_code: login.deviceCode, + user_code: login.userCode, + verification_uri: login.verificationUri, + ...(login.verificationUriComplete === undefined + ? {} + : { verification_uri_complete: login.verificationUriComplete }), + interval: login.interval, + expires_at: new Date(login.expiresAt).toISOString(), + next_poll_at: new Date(login.nextPollAt).toISOString(), + }); +} + +/** @param {CredentialStore} store */ +export function deleteDeviceLogin(store) { + (store.fileSystem ?? DEFAULT_FILE_SYSTEM).rmSync(deviceLoginPath(store), { + force: true, + }); +} + /** * Reads the credentials file. A missing file is an empty store; an unreadable * or malformed file throws. @@ -274,22 +384,33 @@ function sleep(milliseconds) { /** @param {CredentialStore} store @param {Credentials} credentials */ function saveCredentials(store, credentials) { + writePrivateFile(store, credentialsPath(store), credentials); +} + +/** + * Writes JSON with mode 0600 through a temporary file and an atomic rename, + * so a reader sees the old file or the new one, never a partial write. + * + * @param {CredentialStore} store + * @param {string} target + * @param {unknown} value + */ +function writePrivateFile(store, target, value) { const fileSystem = store.fileSystem ?? DEFAULT_FILE_SYSTEM; - const target = credentialsPath(store); const directory = path.dirname(target); const temporaryId = store.createTemporaryId?.() ?? randomBytes(8).toString("hex"); const temporary = path.join( directory, - `.credentials.json.${temporaryId}.tmp`, + `.${path.basename(target)}.${temporaryId}.tmp`, ); try { - fileSystem.writeFileSync( - temporary, - `${JSON.stringify(credentials, null, 2)}\n`, - { flag: "wx", mode: 0o600, flush: true }, - ); + fileSystem.writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, { + flag: "wx", + mode: 0o600, + flush: true, + }); fileSystem.renameSync(temporary, target); } catch (error) { try { @@ -337,6 +458,23 @@ function isMissingFileError(error) { return error instanceof Error && "code" in error && error.code === "ENOENT"; } +/** @param {Buffer} source */ +function parseJson(source) { + try { + return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(source)); + } catch (error) { + if (error instanceof SyntaxError || error instanceof TypeError) return null; + throw error; + } +} + +/** @param {unknown} value @returns {value is string} */ +function isHttpUrl(value) { + if (typeof value !== "string" || !URL.canParse(value)) return false; + const { protocol } = new URL(value); + return protocol === "https:" || protocol === "http:"; +} + /** @param {unknown} value @returns {value is Record} */ function isRecord(value) { return typeof value === "object" && value !== null && !Array.isArray(value); diff --git a/src/oauth.js b/src/oauth.js index 543048d..4730b77 100644 --- a/src/oauth.js +++ b/src/oauth.js @@ -365,21 +365,36 @@ export async function pollDeviceToken({ }); } - const response = await postForm(request, SERVICE_ROUTES.requestOAuthToken, { - grant_type: DEVICE_CODE_GRANT_TYPE, - device_code: deviceCode, - client_id: CLIENT_ID, - }); - if (response.status === 200) return accessTokenFrom(response); + const result = await requestDeviceToken({ ...request, deviceCode }); + if (!("pending" in result)) return result; + if (result.pending === "slow_down") intervalMs += SLOW_DOWN_INCREMENT_MS; + } +} - const failure = oauthFailure(response.status, response.body); - if (failure.code === "authorization_pending") continue; - if (failure.code === "slow_down") { - intervalMs += SLOW_DOWN_INCREMENT_MS; - continue; - } - throw failure; +/** + * One poll of the token endpoint for a device grant. Resolves the token, or + * which of the two answers that mean "ask again later" First Draft gave; + * rejects with an OAuthError for every other answer. + * + * @param {RequestOptions & {deviceCode: string}} options + * @returns {Promise} + */ +export async function requestDeviceToken({ deviceCode, ...request }) { + const response = await postForm(request, SERVICE_ROUTES.requestOAuthToken, { + grant_type: DEVICE_CODE_GRANT_TYPE, + device_code: deviceCode, + client_id: CLIENT_ID, + }); + if (response.status === 200) return accessTokenFrom(response); + + const failure = oauthFailure(response.status, response.body); + if ( + failure.code === "authorization_pending" || + failure.code === "slow_down" + ) { + return { pending: failure.code }; } + throw failure; } /** diff --git a/src/service-client.js b/src/service-client.js index 0841305..4687c88 100644 --- a/src/service-client.js +++ b/src/service-client.js @@ -75,6 +75,8 @@ export class RateLimitedError extends ServiceStopError { /** * @typedef {object} ServiceSession * @property {string} clientHeader the FirstDraft-Client value sent on every request + * @property {string | null} pluginVersion the plugin's version from + * FIRSTDRAFT_PLUGIN_VERSION, or null when that is unset or not a version * @property {(request?: typeof globalThis.fetch) => typeof globalThis.fetch} fetch * Wraps a fetch function so every request carries FirstDraft-Client and * every response is checked. @@ -268,6 +270,7 @@ export function createServiceSession({ return { clientHeader, + pluginVersion: plugin === null ? null : plugin.text, fetch(request = globalThis.fetch) { /** @type {typeof globalThis.fetch} */ const serviceFetch = async (input, init) => { diff --git a/test/cli.test.js b/test/cli.test.js index 30d0562..fa04150 100644 --- a/test/cli.test.js +++ b/test/cli.test.js @@ -22,6 +22,7 @@ Commands: logout Revoke and remove the saved token plan Work with Foundation Plans report Send a progress or failure report to First Draft + start Check versions, login, and reports before other work Options: --staging Use staging for API commands (production is the default) diff --git a/test/login.test.js b/test/login.test.js index 79dabc6..b8b9fad 100644 --- a/test/login.test.js +++ b/test/login.test.js @@ -28,11 +28,15 @@ const LOGIN_HELP = `First Draft CLI Usage: firstdraft login [--interactive] + firstdraft login --no-wait + firstdraft login --finish Options: --staging Log in to staging -i, --interactive Approve with a code on another device (no local browser) --device Same as --interactive + --no-wait Start a device login, print its link and code, and exit + --finish Finish the device login that --no-wait started -h, --help Show help Environment: @@ -44,6 +48,10 @@ waits up to five minutes for First Draft to redirect to a one-time listener on 127.0.0.1. The token is saved for the selected origin in firstdraft/credentials.json under the configuration directory and is never printed. Token environment variables take precedence over a saved login. + +An agent logs in with two short commands. --no-wait saves the waiting login in +firstdraft/device-login.json and exits; once the person approves, --finish +waits at most 15 seconds, saves the token, and removes that file. `; test("login help is printed on stdout", async (context) => { @@ -68,6 +76,10 @@ test("login rejects invalid, repeated, and conflicting options", async (context) ["login", "-i", "--device"], ["login", "--interactive", "--device"], ["login", "--staging", "--staging"], + ["login", "--no-wait", "--finish"], + ["login", "--no-wait", "--no-wait"], + ["login", "--finish", "--finish"], + ["login", "--finish", "extra"], ["logout", "extra"], ["logout", "--interactive"], ]) { @@ -665,6 +677,580 @@ test("device login rejects an invalid device authorization response", async (con } }); +const STARTED_LINES = [ + `To log in to ${PRODUCTION}, ask the person to open this link in a browser, check that the page shows the code BCDF-GHJK, and approve:`, + `${PRODUCTION}/device?user_code=BCDF-GHJK`, + "The link and the code expire in 15 minutes, at 2026-09-29T12:15:00Z.", + "When the person says they approved, run 'firstdraft login --finish'.", +]; + +test("login --no-wait prints the link and the code, saves the waiting login privately, and exits", async (context) => { + for (const argv of [ + ["login", "--no-wait"], + ["login", "--no-wait", "-i"], + ["login", "--device", "--no-wait"], + ]) { + /** @type {string[]} */ + const requests = []; + const result = await invoke(context, argv, { + loginSleep: async () => assert.fail("--no-wait must not wait"), + startLoopbackServer: async () => assert.fail("No server was expected"), + fetchFunction: async (input, init) => { + requests.push(String(input)); + assert.equal( + new URLSearchParams(String(init?.body)).get("client_id"), + "firstdraft-cli", + ); + return deviceAuthorizationResponse(); + }, + }); + + assert.equal(result.status, 0, result.stderr); + assert.deepEqual(requests, [`${PRODUCTION}/oauth/device_authorization`]); + assert.equal(result.stdout, lines(...STARTED_LINES)); + assert.equal(result.stderr, ""); + assert.doesNotMatch(result.stdout + result.stderr, /canary-device-code/); + + const directory = path.join(result.configHome, "firstdraft"); + assert.deepEqual(readdirSync(directory), ["device-login.json"]); + if (process.platform !== "win32") { + assert.equal(statSync(directory).mode & 0o777, 0o700); + assert.equal( + statSync(path.join(directory, "device-login.json")).mode & 0o777, + 0o600, + ); + } + assert.deepEqual(waitingLogin(result.configHome), { + format: "firstdraft.cli-device-login/1", + origin: PRODUCTION, + device_code: DEVICE_CODE, + user_code: "BCDF-GHJK", + verification_uri: `${PRODUCTION}/device`, + verification_uri_complete: `${PRODUCTION}/device?user_code=BCDF-GHJK`, + interval: 5, + expires_at: "2026-09-29T12:15:00.000Z", + next_poll_at: "2026-09-29T12:00:00.000Z", + }); + } +}); + +test("login --no-wait asks for the code when First Draft sends no prefilled link", async (context) => { + /** @type {Record} */ + const body = { + ...deviceAuthorizationBody(), + verification_uri: `${STAGING}/device`, + expires_in: 60, + }; + delete body.verification_uri_complete; + const result = await invoke(context, ["--staging", "login", "--no-wait"], { + fetchFunction: async (input) => { + assert.equal(new URL(String(input)).origin, STAGING); + return jsonResponse(200, body); + }, + }); + + assert.equal(result.status, 0, result.stderr); + assert.equal( + result.stdout, + lines( + `To log in to ${STAGING}, ask the person to open this link in a browser, enter the code BCDF-GHJK, and approve:`, + `${STAGING}/device`, + "The link and the code expire in 1 minute, at 2026-09-29T12:01:00Z.", + "When the person says they approved, run 'firstdraft login --finish --staging'.", + ), + ); + assert.equal(waitingLogin(result.configHome).origin, STAGING); +}); + +test("login --no-wait stops before the link when the login cannot be kept", async (context) => { + const configHome = temporaryConfigHome(context); + mkdirSync(path.join(configHome, "firstdraft"), { recursive: true }); + const credentialsFile = path.join( + configHome, + "firstdraft", + "credentials.json", + ); + writeFileSync(credentialsFile, "{canary"); + const unreadable = await invoke(context, ["login", "--no-wait"], { + configHome, + }); + assert.equal(unreadable.status, 1); + assert.equal(unreadable.stdout, ""); + assert.deepEqual(errorEnvelope(unreadable.stderr), { + error: "login_failed", + detail: + "The credentials file could not be read. No network request was made. Repair or remove it, then run 'firstdraft login --no-wait' again.", + reason: "credentials_invalid", + phase: "read", + credentials_path: credentialsFile, + }); + + const unsaved = await invoke(context, ["login", "--no-wait"], { + credentialsFileSystem: { + ...fs, + renameSync: () => { + throw Object.assign(new Error("canary"), { code: "EACCES" }); + }, + }, + fetchFunction: async () => deviceAuthorizationResponse(), + }); + assert.equal(unsaved.status, 1); + assert.equal(unsaved.stdout, ""); + assert.deepEqual(errorEnvelope(unsaved.stderr), { + error: "login_failed", + detail: + "The device login file at credentials_path could not be used. Remove it, then run 'firstdraft start' to see whether this computer is logged in.", + reason: "device_login_unavailable", + credentials_path: path.join( + unsaved.configHome, + "firstdraft", + "device-login.json", + ), + }); + assert.deepEqual( + readdirSync(path.join(unsaved.configHome, "firstdraft")), + [], + ); + + const limited = await invoke(context, ["login", "--no-wait"], { + fetchFunction: async () => + jsonResponse(429, { error: "temporarily_unavailable" }), + }); + assert.equal(limited.status, 1); + assert.equal(errorEnvelope(limited.stderr).error, "rate_limited"); + assert.deepEqual(readdirSync(limited.configHome), []); +}); + +test("login --finish saves the token once the person approved and removes the waiting login", async (context) => { + const clock = fakeClock(); + const configHome = await startedLogin(context, clock); + /** @type {string[]} */ + const polls = []; + const result = await invoke(context, ["login", "--finish"], { + configHome, + loginSleep: clock.sleep, + loginNow: clock.now, + startLoopbackServer: async () => assert.fail("No server was expected"), + fetchFunction: async (input, init) => { + assert.equal(String(input), `${PRODUCTION}/oauth/token`); + const form = new URLSearchParams(String(init?.body)); + assert.equal( + form.get("grant_type"), + "urn:ietf:params:oauth:grant-type:device_code", + ); + polls.push(String(form.get("device_code"))); + return tokenResponse(); + }, + }); + + assert.equal(result.status, 0, result.stderr); + assert.deepEqual(polls, [DEVICE_CODE]); + assert.deepEqual(clock.delays, [], "the first poll is answered at once"); + assert.equal( + result.stdout, + lines( + `Logged in: this computer is now logged in to ${PRODUCTION}.`, + "Run 'firstdraft start' again.", + ), + ); + assert.equal(result.stderr, ""); + assertNoSecrets(result); + assert.doesNotMatch(result.stdout, /canary-device-code/); + assert.equal(storedCredentials(configHome)[PRODUCTION]?.access_token, TOKEN); + assert.deepEqual(readdirSync(path.join(configHome, "firstdraft")), [ + "credentials.json", + ]); +}); + +test("login --finish waits briefly, then says it is still waiting and when to poll next", async (context) => { + const clock = fakeClock(); + const configHome = await startedLogin(context, clock); + let polls = 0; + /** @type {(number | undefined)[]} */ + const timeouts = []; + const pending = await invoke(context, ["login", "--finish"], { + configHome, + loginSleep: clock.sleep, + loginNow: clock.now, + createRequestSignal: (timeoutMs) => { + timeouts.push(timeoutMs); + return new AbortController().signal; + }, + fetchFunction: async () => { + polls += 1; + return jsonResponse(400, { error: "authorization_pending" }); + }, + }); + + assert.equal(pending.status, 1); + assert.equal(polls, 3); + assert.deepEqual(clock.delays, [5000, 5000]); + assert.deepEqual( + timeouts, + [15000, 10000, 5000], + "each request ends by the end of the wait", + ); + assert.equal( + pending.stdout, + lines( + "Still waiting: First Draft has not confirmed that the person approved the login.", + STARTED_LINES[0] ?? "", + STARTED_LINES[1] ?? "", + "The link and the code expire at 2026-09-29T12:15:00Z. When the person says they approved, run 'firstdraft login --finish' again.", + ), + ); + assert.deepEqual(errorEnvelope(pending.stderr), { + error: "authorization_pending", + detail: + "First Draft has not confirmed that the person approved the login, and the CLI stopped waiting. When the person says they approved, run 'firstdraft login --finish' again.", + }); + assert.equal( + waitingLogin(configHome).next_poll_at, + "2026-09-29T12:00:15.000Z", + ); + + clock.delays.length = 0; + const again = await invoke(context, ["login", "--finish"], { + configHome, + loginSleep: clock.sleep, + loginNow: clock.now, + fetchFunction: async () => + jsonResponse(400, { error: "authorization_pending" }), + }); + assert.equal(errorEnvelope(again.stderr).error, "authorization_pending"); + assert.deepEqual( + clock.delays, + [5000, 5000], + "a later --finish keeps to the interval and to its own 15 seconds", + ); + + clock.delays.length = 0; + const finished = await invoke(context, ["login", "--finish"], { + configHome, + loginSleep: clock.sleep, + loginNow: clock.now, + fetchFunction: async () => tokenResponse(), + }); + assert.equal(finished.status, 0, finished.stderr); + assert.deepEqual(clock.delays, [5000]); +}); + +test("login --finish sends no poll after its wait has ended, even when a timer wakes late", async (context) => { + const clock = fakeClock(); + const configHome = await startedLogin(context, clock); + let polls = 0; + const result = await invoke(context, ["login", "--finish"], { + configHome, + loginSleep: (delayMs) => clock.sleep(delayMs + 10_200), + loginNow: clock.now, + fetchFunction: async () => { + polls += 1; + return jsonResponse(400, { error: "authorization_pending" }); + }, + }); + assert.equal(result.status, 1); + assert.equal(errorEnvelope(result.stderr).error, "authorization_pending"); + assert.equal(polls, 1, "the poll after the late wakeup is not sent"); +}); + +test("a credentials file that cannot be read names the same login step, staging included", async (context) => { + const configHome = temporaryConfigHome(context); + const started = await invoke(context, ["--staging", "login", "--no-wait"], { + configHome, + fetchFunction: async () => + jsonResponse(200, { + ...deviceAuthorizationBody(), + verification_uri: `${STAGING}/device`, + verification_uri_complete: `${STAGING}/device?user_code=BCDF-GHJK`, + }), + }); + assert.equal(started.status, 0, started.stderr); + writeFileSync( + path.join(configHome, "firstdraft", "credentials.json"), + "{canary", + ); + for (const step of ["--no-wait", "--finish"]) { + const result = await invoke(context, ["login", step, "--staging"], { + configHome, + }); + assert.equal(result.status, 1); + assert.equal( + errorEnvelope(result.stderr).detail, + `The credentials file could not be read. No network request was made. Repair or remove it, then run 'firstdraft login ${step} --staging' again.`, + ); + } +}); + +test("login --finish treats a pending answer that arrives after the expiry as expired", async (context) => { + const clock = fakeClock(); + const configHome = await startedLogin(context, clock); + await clock.sleep(899_000); + const result = await invoke(context, ["login", "--finish"], { + configHome, + loginSleep: clock.sleep, + loginNow: clock.now, + fetchFunction: async () => { + await clock.sleep(1500); + return jsonResponse(400, { error: "authorization_pending" }); + }, + }); + assert.equal(result.status, 1); + assert.equal(errorEnvelope(result.stderr).error, "authorization_expired"); + assert.match(result.stdout, /^Expired: /); + assert.deepEqual(readdirSync(path.join(configHome, "firstdraft")), []); +}); + +test("login --finish succeeds when only the spent device login cannot be removed", async (context) => { + const clock = fakeClock(); + const configHome = await startedLogin(context, clock); + const file = path.join(configHome, "firstdraft", "device-login.json"); + const result = await invoke(context, ["login", "--finish"], { + configHome, + loginSleep: clock.sleep, + loginNow: clock.now, + credentialsFileSystem: { + ...fs, + rmSync: (target, options) => { + if (String(target) === file) { + throw Object.assign(new Error("canary"), { code: "EACCES" }); + } + fs.rmSync(target, options); + }, + }, + fetchFunction: async () => tokenResponse(), + }); + assert.equal(result.status, 0, result.stderr); + assert.match(result.stdout, /^Logged in: /); + assert.equal( + result.stderr, + `Note: ${file} could not be removed. It holds only a spent device code; remove it.\n`, + ); + assert.equal(storedCredentials(configHome)[PRODUCTION]?.access_token, TOKEN); +}); + +test("login --finish slows down when First Draft asks and keeps the longer interval", async (context) => { + const clock = fakeClock(); + const configHome = await startedLogin(context, clock); + const outcomes = ["slow_down", "authorization_pending"]; + const pending = await invoke(context, ["login", "--finish"], { + configHome, + loginSleep: clock.sleep, + loginNow: clock.now, + fetchFunction: async () => + jsonResponse(400, { error: outcomes.shift() ?? "authorization_pending" }), + }); + assert.equal(pending.status, 1); + assert.equal(errorEnvelope(pending.stderr).error, "authorization_pending"); + assert.deepEqual(clock.delays, [10000]); + assert.equal(waitingLogin(configHome).interval, 10); + assert.equal( + waitingLogin(configHome).next_poll_at, + "2026-09-29T12:00:20.000Z", + ); +}); + +test("login --finish says plainly when the login was refused or expired, and removes it", async (context) => { + /** @type {[string, string, string[] | null, string][]} */ + const cases = [ + [ + "access_denied", + "authorization_denied", + [ + `Refused: the person denied this login, so no new login was saved for ${PRODUCTION}.`, + "Ask the person before you start another login with 'firstdraft login --no-wait'.", + ], + "The login was denied in the browser. No credential was saved. Ask the person before you start another login with 'firstdraft login --no-wait'.", + ], + [ + "expired_token", + "authorization_expired", + [ + `Expired: the link and the code expired before this computer finished the login, so no new login was saved for ${PRODUCTION}.`, + "To try again, run 'firstdraft login --no-wait'.", + ], + "The login expired before this computer finished it. No credential was saved. Run 'firstdraft login --no-wait' to start again.", + ], + [ + "invalid_grant", + "login_failed", + null, + "The login could not be finished, and no credential was saved. Start again with 'firstdraft login --no-wait'.", + ], + ]; + for (const [code, error, stdout, detail] of cases) { + const clock = fakeClock(); + const configHome = await startedLogin(context, clock); + const result = await invoke(context, ["login", "--finish"], { + configHome, + loginSleep: clock.sleep, + loginNow: clock.now, + fetchFunction: async () => jsonResponse(400, { error: code }), + }); + assert.equal(result.status, 1); + assert.equal(result.stdout, stdout === null ? "" : lines(...stdout)); + const envelope = errorEnvelope(result.stderr); + assert.equal(envelope.error, error); + assert.equal(envelope.detail, detail); + assert.deepEqual(readdirSync(path.join(configHome, "firstdraft")), []); + } + + const clock = fakeClock(); + const configHome = await startedLogin(context, clock); + await clock.sleep(15 * 60 * 1000); + const expired = await invoke(context, ["login", "--finish"], { + configHome, + loginSleep: clock.sleep, + loginNow: clock.now, + }); + assert.equal(expired.status, 1); + assert.equal(errorEnvelope(expired.stderr).error, "authorization_expired"); + assert.match(expired.stdout, /^Expired: /); + assert.deepEqual(readdirSync(path.join(configHome, "firstdraft")), []); +}); + +test("login --finish keeps the waiting login after a failure it can retry", async (context) => { + for (const response of [ + () => { + throw new TypeError("canary network failure"); + }, + () => new Response("canary", { status: 500 }), + ]) { + const clock = fakeClock(); + const configHome = await startedLogin(context, clock); + const result = await invoke(context, ["login", "--finish"], { + configHome, + loginSleep: clock.sleep, + loginNow: clock.now, + fetchFunction: async () => response(), + }); + assert.equal(result.status, 1); + assert.equal(result.stdout, ""); + const envelope = errorEnvelope(result.stderr); + assert.equal(envelope.error, "login_failed"); + assert.equal( + envelope.detail, + "The login could not be finished, and no credential was saved. Run 'firstdraft login --finish' again; if it fails again, start over with 'firstdraft login --no-wait'.", + ); + assert.doesNotMatch(result.stderr, /canary/); + assert.equal( + waitingLogin(configHome).next_poll_at, + "2026-09-29T12:00:05.000Z", + ); + } +}); + +test("login --finish without a waiting login for the origin says so", async (context) => { + const none = await invoke(context, ["login", "--finish"]); + assert.equal(none.status, 1); + assert.equal( + none.stdout, + lines( + `No login is waiting: this computer has no device login for ${PRODUCTION} that has not ended.`, + "Run 'firstdraft start' to see whether this computer is logged in.", + ), + ); + assert.deepEqual(errorEnvelope(none.stderr), { + error: "login_not_started", + detail: `No device login is waiting for ${PRODUCTION}: none was started with 'firstdraft login --no-wait', or it already ended. Run 'firstdraft start' to see whether this computer is logged in.`, + }); + + const clock = fakeClock(); + const configHome = await startedLogin(context, clock); + const before = waitingLogin(configHome); + const other = await invoke(context, ["login", "--finish", "--staging"], { + configHome, + }); + assert.equal(other.status, 1); + assert.equal(errorEnvelope(other.stderr).error, "login_not_started"); + assert.match(other.stdout, /'firstdraft start --staging'/); + assert.deepEqual(waitingLogin(configHome), before); +}); + +test("login --finish refuses a malformed waiting login before any request", async (context) => { + const configHome = temporaryConfigHome(context); + mkdirSync(path.join(configHome, "firstdraft")); + const file = path.join(configHome, "firstdraft", "device-login.json"); + for (const source of [ + "{canary", + JSON.stringify({ format: "firstdraft.cli-device-login/1" }), + ]) { + writeFileSync(file, source); + const result = await invoke(context, ["login", "--finish"], { configHome }); + assert.equal(result.status, 1); + assert.deepEqual(errorEnvelope(result.stderr), { + error: "login_failed", + detail: + "The device login file at credentials_path could not be used. Remove it, then run 'firstdraft start' to see whether this computer is logged in.", + reason: "device_login_invalid", + credentials_path: file, + }); + assert.equal(readFileSync(file, "utf8"), source); + } +}); + +test("login --finish reports an issued token it could not save", async (context) => { + const clock = fakeClock(); + const configHome = await startedLogin(context, clock); + const result = await invoke(context, ["login", "--finish"], { + configHome, + loginSleep: clock.sleep, + loginNow: clock.now, + credentialsFileSystem: { + ...fs, + renameSync: (source, target) => { + if (String(target).endsWith("credentials.json")) { + throw Object.assign(new Error(TOKEN), { code: "EACCES" }); + } + fs.renameSync(source, target); + }, + }, + fetchFunction: async () => tokenResponse(), + }); + assert.equal(result.status, 1); + assert.equal(result.stdout, ""); + const envelope = errorEnvelope(result.stderr); + assert.equal(envelope.error, "login_failed"); + assert.equal(envelope.phase, "write"); + assert.equal(envelope.reason, "credentials_unavailable"); + assert.match(envelope.detail, /issued a token, but it could not be saved/); + assert.equal( + existsSync(path.join(configHome, "firstdraft", "device-login.json")), + false, + "the spent grant is removed even when the token cannot be saved", + ); + assertNoSecrets(result); +}); + +/** + * Runs `login --no-wait` and returns its configuration directory. + * + * @param {import("node:test").TestContext} context + * @param {ReturnType} clock + */ +async function startedLogin(context, clock) { + const started = await invoke(context, ["login", "--no-wait"], { + loginNow: clock.now, + fetchFunction: async () => deviceAuthorizationResponse(), + }); + assert.equal(started.status, 0, started.stderr); + return started.configHome; +} + +/** @param {string} configHome */ +function waitingLogin(configHome) { + return JSON.parse( + readFileSync( + path.join(configHome, "firstdraft", "device-login.json"), + "utf8", + ), + ); +} + +/** @param {...string} values */ +function lines(...values) { + return values.map((value) => `${value}\n`).join(""); +} + /** * @param {import("node:test").TestContext} context * @param {readonly string[]} argv diff --git a/test/start.test.js b/test/start.test.js new file mode 100644 index 0000000..3564987 --- /dev/null +++ b/test/start.test.js @@ -0,0 +1,599 @@ +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { run } from "../src/cli.js"; +import { VERSION } from "../src/version.js"; + +const PRODUCTION = "https://firstdraft.com"; +const STAGING = "https://staging.firstdraft.com"; +const SAVED_TOKEN = "fd_canary-saved-token"; +const ENVIRONMENT_TOKEN = "fd_canary-environment-token"; + +const START_HELP = `First Draft CLI + +Usage: + firstdraft start + +Options: + --staging Use staging + -h, --help Show help + +Environment: + FIRSTDRAFT_API_TOKEN Authenticate production or custom API origins + FIRSTDRAFT_STAGING_API_TOKEN Authenticate staging.firstdraft.com + FIRSTDRAFT_API_URL Use a custom API origin + +An agent runs this once before other First Draft work. It prints the versions, +any update notice, whether this computer is logged in and how to log in if +not, and, when the person agreed to reports, when to send them. With a token +it reads the account once; without one it makes no request. It exits 0 only +when First Draft accepted the login. +`; + +const REPORTS_ON = [ + "Reports are on: this person agreed that you send First Draft progress and failure reports about the code it generates.", + "Progress: run 'firstdraft report progress --step ' when bin/setup finishes (setup), when the first spec run finishes (specs_first_run), when every item under the README's Behavior to write is written (behavior_written), when the specs pass (specs_passing), and when the preview starts (preview_started). Add the counts you have; 'firstdraft report progress --help' lists them.", + "Failure: when generated code fails in a way the README does not list, run 'firstdraft report failure --kind ' once you have fixed it or stopped trying, where is setup_failure, spec_failure, boot_error, or lint_failure; 'firstdraft report failure --help' lists the other fields.", + "Use compilation.id from 'firstdraft plan compile', and run each report command from the generated application's root, or from the Project's directory after --output. Each prints what it sends: pass only text that may leave this computer, never secrets or the person's data.", +]; + +test("start help is printed without a request", async (context) => { + for (const argv of [ + ["start", "--help"], + ["start", "-h"], + ]) { + const result = await invoke(context, argv); + assert.deepEqual( + { status: result.status, stdout: result.stdout, stderr: result.stderr }, + { status: 0, stdout: START_HELP, stderr: "" }, + ); + } +}); + +test("start rejects invalid arguments before any request", async (context) => { + for (const argv of [ + ["start", "canary-positional"], + ["start", "--canary-option"], + ["start", "--staging", "--staging"], + ]) { + const result = await invoke(context, argv); + assert.equal(result.status, 2); + assert.equal(result.stdout, ""); + assert.deepEqual(JSON.parse(result.stderr), { + error: "invalid_arguments", + detail: "Invalid arguments. Run 'firstdraft start --help' for usage.", + }); + } + + const conflict = await invoke(context, ["start", "--staging"], { + apiUrl: "https://canary.example", + }); + assert.equal(conflict.status, 2); + assert.equal(conflict.stdout, ""); + assert.equal(JSON.parse(conflict.stderr).error, "invalid_configuration"); +}); + +test("without a token, start makes no request and names both login steps", async (context) => { + const result = await invoke(context, ["start"], { + env: { FIRSTDRAFT_PLUGIN_VERSION: "0.10.0" }, + }); + + assert.equal(result.status, 1); + assert.equal( + result.stdout, + lines( + `First Draft CLI ${VERSION} with plugin 0.10.0.`, + `This computer has no saved login for ${PRODUCTION}.`, + "To log in, run 'firstdraft login --no-wait'. It prints a link and a code: show both to the person and ask them to approve the login in their browser.", + "When the person says they approved, run 'firstdraft login --finish', then run 'firstdraft start' again.", + ), + ); + assert.deepEqual(JSON.parse(result.stderr), { + error: "authentication_required", + detail: `This computer has no token for ${PRODUCTION}, so the CLI made no request. Log in with 'firstdraft login --no-wait' and, once the person approves, 'firstdraft login --finish'.`, + }); +}); + +test("start names the staging flag in every command it prints", async (context) => { + for (const argv of [ + ["--staging", "start"], + ["start", "--staging"], + ]) { + const result = await invoke(context, argv, { + apiToken: ENVIRONMENT_TOKEN, + }); + assert.equal(result.status, 1); + assert.equal( + result.stdout, + lines( + `First Draft CLI ${VERSION}.`, + `This computer has no saved login for ${STAGING}.`, + "To log in, run 'firstdraft login --no-wait --staging'. It prints a link and a code: show both to the person and ask them to approve the login in their browser.", + "When the person says they approved, run 'firstdraft login --finish --staging', then run 'firstdraft start --staging' again.", + ), + ); + } +}); + +test("a malformed credentials file counts as no saved login", async (context) => { + const configHome = temporaryConfigHome(context); + mkdirSync(path.join(configHome, "firstdraft")); + writeFileSync( + path.join(configHome, "firstdraft", "credentials.json"), + "{canary", + ); + const result = await invoke(context, ["start"], { configHome }); + assert.equal(result.status, 1); + assert.match(result.stdout, /has no saved login/); + assert.doesNotMatch(result.stdout + result.stderr, /canary/); +}); + +test("with reports on, start reads the account once and says when to send reports", async (context) => { + /** @type {{url: string, init: RequestInit | undefined}[]} */ + const requests = []; + const result = await invoke(context, ["start"], { + saved: { [PRODUCTION]: SAVED_TOKEN }, + fetchFunction: async (input, init) => { + requests.push({ url: String(input), init }); + return account("on"); + }, + }); + + assert.equal(result.status, 0, result.stderr); + assert.equal( + result.stdout, + lines( + `First Draft CLI ${VERSION}.`, + `This computer has a saved login for ${PRODUCTION}.`, + "Ready: First Draft accepted this computer's login.", + ...REPORTS_ON, + ), + ); + assert.equal(result.stderr, ""); + assert.equal(requests.length, 1); + assert.equal(requests[0]?.url, `${PRODUCTION}/v1/account`); + assert.equal(requests[0]?.init?.method, "GET"); + const headers = new Headers(requests[0]?.init?.headers); + assert.equal(headers.get("authorization"), `Bearer ${SAVED_TOKEN}`); + assert.equal( + headers.get("firstdraft-client"), + `cli/${VERSION}; os/${process.platform}`, + ); + assertNoTokens(result); +}); + +test("with reports off, start says nothing about reports", async (context) => { + const result = await invoke(context, ["start"], { + saved: { [PRODUCTION]: SAVED_TOKEN }, + fetchFunction: async () => account("off"), + }); + + assert.equal(result.status, 0, result.stderr); + assert.equal( + result.stdout, + lines( + `First Draft CLI ${VERSION}.`, + `This computer has a saved login for ${PRODUCTION}.`, + "Ready: First Draft accepted this computer's login.", + ), + ); + assert.doesNotMatch(result.stdout + result.stderr, /report/i); +}); + +test("start says when an environment token takes the place of the saved login", async (context) => { + /** @type {Record[]} */ + const savedLogins = [{}, { [PRODUCTION]: SAVED_TOKEN }]; + for (const saved of savedLogins) { + /** @type {string | null} */ + let authorization = null; + const result = await invoke(context, ["start"], { + saved, + apiToken: ENVIRONMENT_TOKEN, + fetchFunction: async (_input, init) => { + authorization = new Headers(init?.headers).get("authorization"); + return account("off"); + }, + }); + + assert.equal(result.status, 0, result.stderr); + assert.equal(authorization, `Bearer ${ENVIRONMENT_TOKEN}`); + assert.equal( + result.stdout, + lines( + `First Draft CLI ${VERSION}.`, + `This computer has ${PRODUCTION in saved ? "a" : "no"} saved login for ${PRODUCTION}.`, + `FIRSTDRAFT_API_TOKEN is set, so the CLI uses that token in place of any saved login for ${PRODUCTION}, and no login is needed.`, + "Ready: First Draft accepted FIRSTDRAFT_API_TOKEN.", + ), + ); + assertNoTokens(result); + } + + const staging = await invoke(context, ["start", "--staging"], { + stagingApiToken: ENVIRONMENT_TOKEN, + fetchFunction: async (input) => { + assert.equal(new URL(String(input)).origin, STAGING); + return account("off"); + }, + }); + assert.equal(staging.status, 0, staging.stderr); + assert.match( + staging.stdout, + /^FIRSTDRAFT_STAGING_API_TOKEN is set, so the CLI uses that token in place of any saved login for https:\/\/staging\.firstdraft\.com, and no login is needed\.$/m, + ); +}); + +test("start prints the update line from First Draft's answer on standard output", async (context) => { + for (const [env, headers, update] of [ + [ + {}, + { "FirstDraft-Latest-CLI": "99.0.0", "FirstDraft-Minimum-CLI": "0.1.0" }, + `First Draft: an update is available (CLI 99.0.0; this setup has CLI ${VERSION}). Tell the person the update steps are at https://firstdraft.com/update`, + ], + [ + { FIRSTDRAFT_PLUGIN_VERSION: "0.10.0" }, + { + "FirstDraft-Latest-Plugin": "0.11.0", + "FirstDraft-Minimum-Plugin": "0.1.0", + }, + "First Draft: an update is available (plugin 0.11.0; this setup has plugin 0.10.0). Tell the person the update steps are at https://firstdraft.com/update", + ], + ]) { + const result = await invoke(context, ["start"], { + env: /** @type {Record} */ (env), + saved: { [PRODUCTION]: SAVED_TOKEN }, + fetchFunction: async () => + account("off", /** @type {Record} */ (headers)), + }); + + assert.equal(result.status, 0, result.stderr); + assert.equal(result.stderr, ""); + const [version, notice, ...rest] = result.stdout.split("\n"); + assert.match(String(version), /^First Draft CLI /); + assert.equal(notice, update); + assert.deepEqual(rest, [ + `This computer has a saved login for ${PRODUCTION}.`, + "Ready: First Draft accepted this computer's login.", + "", + ]); + } +}); + +test("below the minimum, start gives the handled refusal instead of ready", async (context) => { + const result = await invoke(context, ["start"], { + saved: { [PRODUCTION]: SAVED_TOKEN }, + fetchFunction: async () => + account("on", { + "FirstDraft-Latest-CLI": "99.0.0", + "FirstDraft-Minimum-CLI": "99.0.0", + }), + }); + + assert.equal(result.status, 1); + assert.equal( + result.stdout, + lines( + `First Draft CLI ${VERSION}.`, + `This computer has a saved login for ${PRODUCTION}.`, + ), + ); + assert.deepEqual(JSON.parse(result.stderr), { + error: "update_required", + detail: `First Draft requires CLI 99.0.0 or later, and this setup has CLI ${VERSION}. The CLI stopped before the command finished and sent nothing more. Tell the person to update with the steps at https://firstdraft.com/update, then run the same command again, with the same options.`, + cli_version: VERSION, + minimum_cli_version: "99.0.0", + update_url: "https://firstdraft.com/update", + }); +}); + +test("an API contract outside the accepted range is not ready", async (context) => { + for (const contract of ["0.8.0", "0.10.0"]) { + const result = await invoke(context, ["start"], { + saved: { [PRODUCTION]: SAVED_TOKEN }, + fetchFunction: async () => + account("on", { "FirstDraft-API-Contract": contract }), + }); + assert.equal(result.status, 1); + assert.doesNotMatch(result.stdout, /Ready|Reports/); + const envelope = JSON.parse(result.stderr); + assert.equal(envelope.error, "api_contract_unsupported"); + assert.equal(envelope.api_contract, contract); + } +}); + +test("a rejected login says how to log in again", async (context) => { + const saved = await invoke(context, ["start"], { + saved: { [PRODUCTION]: SAVED_TOKEN }, + fetchFunction: async () => unauthorized(), + }); + assert.equal(saved.status, 1); + assert.equal( + saved.stdout, + lines( + `First Draft CLI ${VERSION}.`, + `This computer has a saved login for ${PRODUCTION}.`, + `Not logged in: First Draft did not accept the saved login for ${PRODUCTION}.`, + "To log in, run 'firstdraft login --no-wait'. It prints a link and a code: show both to the person and ask them to approve the login in their browser.", + "When the person says they approved, run 'firstdraft login --finish', then run 'firstdraft start' again.", + ), + ); + const envelope = JSON.parse(saved.stderr); + assert.equal(envelope.error, "authentication_required"); + assert.equal( + envelope.detail, + `First Draft did not accept the saved login for ${PRODUCTION}. Log in with 'firstdraft login --no-wait' and, once the person approves, 'firstdraft login --finish'.`, + ); + assert.equal(envelope.status, 401); + + const environment = await invoke(context, ["start"], { + apiToken: ENVIRONMENT_TOKEN, + fetchFunction: async () => unauthorized(), + }); + assert.equal(environment.status, 1); + assert.match( + environment.stdout, + /\nNot logged in: First Draft did not accept FIRSTDRAFT_API_TOKEN\. Ask the person to replace it or unset it; while it is set, the CLI uses no saved login\.\n$/, + ); + assert.doesNotMatch(environment.stdout, /login --no-wait/); + assert.equal( + JSON.parse(environment.stderr).detail, + "First Draft did not accept FIRSTDRAFT_API_TOKEN. Ask the person to replace it or unset it.", + ); + assertNoTokens(environment); +}); + +test("an unreadable account leaves start not ready and safe to retry", async (context) => { + const cases = [ + [ + () => + new Response( + JSON.stringify({ + type: "about:blank", + title: "Service Unavailable", + status: 503, + code: "service_unavailable", + detail: "Try again.", + }), + { + status: 503, + headers: { "Content-Type": "application/problem+json" }, + }, + ), + "account_unavailable", + ], + [ + () => { + throw new TypeError("canary network failure"); + }, + "account_unavailable", + ], + [() => json({ reports: "maybe" }), "invalid_server_response"], + ]; + for (const [response, error] of cases) { + const result = await invoke(context, ["start"], { + saved: { [PRODUCTION]: SAVED_TOKEN }, + fetchFunction: async () => /** @type {() => Response} */ (response)(), + }); + assert.equal(result.status, 1); + assert.equal( + result.stdout, + lines( + `First Draft CLI ${VERSION}.`, + `This computer has a saved login for ${PRODUCTION}.`, + ), + ); + const envelope = JSON.parse(result.stderr); + assert.equal(envelope.error, error); + if (error === "account_unavailable") { + assert.equal( + envelope.detail, + "Could not read the account, so the CLI could not check the login or the reports choice. This read-only request is safe to retry: run 'firstdraft start' again.", + ); + } + assert.doesNotMatch(result.stdout + result.stderr, /canary/); + } + + const limited = await invoke(context, ["start"], { + saved: { [PRODUCTION]: SAVED_TOKEN }, + fetchFunction: async () => + new Response(null, { status: 429, headers: { "Retry-After": "60" } }), + }); + assert.equal(limited.status, 1); + assert.equal(JSON.parse(limited.stderr).error, "rate_limited"); +}); + +test("a version refusal wins over a failed account read", async (context) => { + for (const [response, error] of [ + [ + () => { + const rejected = unauthorized(); + return new Response(rejected.body, { + status: 401, + headers: { + "Content-Type": "application/problem+json", + "FirstDraft-Latest-CLI": "99.0.0", + "FirstDraft-Minimum-CLI": "99.0.0", + }, + }); + }, + "update_required", + ], + [ + () => + new Response(JSON.stringify({ reports: "maybe" }), { + status: 200, + headers: { + "Content-Type": "application/json", + "FirstDraft-API-Contract": "0.10.0", + }, + }), + "api_contract_unsupported", + ], + ]) { + const result = await invoke(context, ["start"], { + saved: { [PRODUCTION]: SAVED_TOKEN }, + fetchFunction: async () => /** @type {() => Response} */ (response)(), + }); + assert.equal(result.status, 1); + assert.equal( + result.stdout, + lines( + `First Draft CLI ${VERSION}.`, + `This computer has a saved login for ${PRODUCTION}.`, + ), + ); + assert.equal(JSON.parse(result.stderr).error, error); + } +}); + +test("start passes on none of the text in First Draft's problem answers", async (context) => { + for (const [status, headers] of [ + [401, {}], + [429, { "Retry-After": "60" }], + [503, {}], + ]) { + const result = await invoke(context, ["start", "--staging"], { + saved: { [STAGING]: SAVED_TOKEN }, + serviceNow: () => Date.parse("2026-11-21T12:00:00Z"), + fetchFunction: async () => + new Response( + JSON.stringify({ + type: "about:blank", + title: "Problem for canary@example.com", + status, + code: status === 401 ? "authentication_required" : "canary_code", + detail: "Write to canary@example.com.", + }), + { + status: /** @type {number} */ (status), + headers: { + "Content-Type": "application/problem+json", + .../** @type {Record} */ (headers), + }, + }, + ), + }); + assert.equal(result.status, 1); + const envelope = JSON.parse(result.stderr); + assert.equal(envelope.response, undefined); + assert.doesNotMatch(result.stdout + result.stderr, /canary/); + if (status === 429) { + assert.equal(envelope.error, "rate_limited"); + assert.equal(envelope.retry_at, "2026-11-21T12:01:00Z"); + assert.match(envelope.detail, /Try again after 2026-11-21T12:01:00Z\.$/); + } + if (status === 503) { + assert.equal( + envelope.detail, + "Could not read the account, so the CLI could not check the login or the reports choice. This read-only request is safe to retry: run 'firstdraft start --staging' again.", + ); + } + } +}); + +/** @param {...string} values */ +function lines(...values) { + return values.map((value) => `${value}\n`).join(""); +} + +/** + * @param {"on" | "off"} reports + * @param {Record} [headers] + */ +function account(reports, headers = {}) { + return new Response( + JSON.stringify({ reports, email: "canary@example.com" }), + { + status: 200, + headers: { + "Content-Type": "application/json", + "FirstDraft-API-Contract": "0.9.0", + ...headers, + }, + }, + ); +} + +/** @param {unknown} body */ +function json(body) { + return new Response(JSON.stringify(body), { + status: 200, + headers: { "Content-Type": "application/json" }, + }); +} + +function unauthorized() { + return new Response( + JSON.stringify({ + type: "about:blank", + title: "Unauthorized", + status: 401, + code: "authentication_required", + detail: "A valid token is required.", + }), + { status: 401, headers: { "Content-Type": "application/problem+json" } }, + ); +} + +/** @param {{stdout: string, stderr: string}} result */ +function assertNoTokens(result) { + assert.doesNotMatch(result.stdout + result.stderr, /fd_canary|canary@/); +} + +/** @param {import("node:test").TestContext} context */ +function temporaryConfigHome(context) { + const directory = mkdtempSync(path.join(tmpdir(), "firstdraft-start-")); + context.after(() => rmSync(directory, { recursive: true, force: true })); + return directory; +} + +/** + * @param {import("node:test").TestContext} context + * @param {readonly string[]} argv + * @param {Partial & {configHome?: string, saved?: Record}} [options] + */ +async function invoke(context, argv, options = {}) { + const { + configHome = temporaryConfigHome(context), + saved = {}, + env = {}, + ...rest + } = options; + if (Object.keys(saved).length > 0) { + mkdirSync(path.join(configHome, "firstdraft"), { recursive: true }); + writeFileSync( + path.join(configHome, "firstdraft", "credentials.json"), + JSON.stringify({ + format: "firstdraft.cli-credentials/1", + origins: Object.fromEntries( + Object.entries(saved).map(([origin, token]) => [ + origin, + { + access_token: token, + token_type: "Bearer", + created_at: "2026-11-01T00:00:00.000Z", + }, + ]), + ), + }), + ); + } + let stdout = ""; + let stderr = ""; + const status = await run({ + argv, + stdout: { write: (text) => (stdout += text) }, + stderr: { write: (text) => (stderr += text) }, + apiToken: "", + stagingApiToken: "", + apiUrl: undefined, + env: { XDG_CONFIG_HOME: configHome, ...env }, + homedir: () => assert.fail("The home directory must not be used"), + fetchFunction: async () => assert.fail("No network request was expected"), + ...rest, + }); + return { status, stdout, stderr }; +}