From cf8cf91d8f6b72f774802d5ff56138dc138f295d Mon Sep 17 00:00:00 2001 From: Raghu Betina Date: Tue, 24 Nov 2026 01:08:09 -0600 Subject: [PATCH] Add host commands for First Draft hosting First Draft hosting runs one application on one DigitalOcean Droplet, and the owner's own agent operates it. The service never logs in to the Droplet and never receives a private key, so the steps that need the key or the person's GitHub login have to run on the owner's computer: the CLI generates the SSH key with ssh-keygen, sends only its public line, and stores the private key and the app's generated secrets as Actions secrets through gh's standard input. A push to the default branch deploys only when every check passes, and a freshly compiled app fails its own specs until its Behavior to write is written. So no host command deploys, and create and status end with a next sentence that says what stands between the owner and a live app: a Droplet still setting itself up, red checks, a failed deploy job, or checks that passed before the repository was connected. DEPLOY_HOST is set only after cloud-init reports done, so the deploy job cannot race the Droplet's first boot. The routes follow the service's hosting sketch, which no released API contract includes yet. The group lives in its own modules, so cli.js gains only an import, a help line, and the dispatch. --- docs/commands.md | 188 +++++- docs/errors.md | 110 ++-- scripts/check-pack.js | 3 + scripts/smoke-package.js | 19 + src/api-response.js | 44 ++ src/cli.js | 44 ++ src/commands/host-command.js | 1100 +++++++++++++++++++++++++++++++++ src/commands/host.js | 701 +++++++++++++++++++++ src/host-tools.js | 359 +++++++++++ test/api-environments.test.js | 1 + test/cli.test.js | 1 + test/host.test.js | 901 +++++++++++++++++++++++++++ 12 files changed, 3405 insertions(+), 66 deletions(-) create mode 100644 src/commands/host-command.js create mode 100644 src/commands/host.js create mode 100644 src/host-tools.js create mode 100644 test/host.test.js diff --git a/docs/commands.md b/docs/commands.md index b66b1b3..86878c4 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -36,6 +36,12 @@ contract. The [changelog](https://github.com/firstdraft/cli/blob/main/CHANGELOG. | `firstdraft note unstated_request` | Yes | Print, then send, a request the Plan could not state | | `firstdraft note unclear_guidance` | Yes | Print, then send, a Skill page or diagnostic that was unclear | | `firstdraft note wrong_output` | Yes | Print, then send, analysis or generated code that was wrong | +| `firstdraft host create` | Yes | Create the app's Droplet and connect its repository | +| `firstdraft host status` | Yes | Show the host, its release, and what stands in the way | +| `firstdraft host resize` | Yes | Change the Droplet's size, once the owner agrees | +| `firstdraft host destroy` | Yes | Remove the Droplet, once the owner agrees | +| `firstdraft host domain` | Yes | Connect, check, or disconnect the app's own domain | +| `firstdraft host email` | Yes | Show email state, or store new SMTP credentials | ## Select an environment and authenticate @@ -220,14 +226,20 @@ CLI without the plugin's launcher, such as a direct npm installation, may set th 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 | -| `note ` | An account read; with reports on, the note printed just before | +| 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 | +| `note ` | An account read; with reports on, the note printed just before | +| `host *` | The Environment name in the path; `host create` adds the region, size, and SSH public key; `resize` the size; `destroy` the confirmation; `domain connect` the hostname | + +Host commands also run programs on the owner's computer: `gh`, which sends its own requests to GitHub with the +person's GitHub login, and `ssh-keygen` and `ssh`. [Operate a First Draft host](#operate-a-first-draft-host) lists +what each command runs. `host status` also requests `https:///up` from the application itself, with no +token and no `FirstDraft-Client` header. ### Update line and refusals @@ -870,6 +882,116 @@ Compilation record only for a note about generated code without `--compilation-i application and no conversation. A note holds only what its options give, plus that recorded ID, so pass only text that may be sent, and never code from the person's project. +## Operate a First Draft host + +First Draft hosting runs one application on one DigitalOcean Droplet that First Draft creates. First Draft's service +never logs in to the Droplet and never receives a private key: the owner's computer holds the SSH key, and GitHub +Actions deploys. A push to the default branch deploys only when every check in `.github/workflows/ci.yml` passes, +through that workflow's `deploy` job, which runs Kamal; no host command deploys. A freshly compiled application fails +its own specs until its Behavior to write is written, so a new host serves nothing until then. + +Run host commands from the application's root, where `config/deploy.yml` and the Git repository are; the Project is +the one pinned there, including an adopted root's `.firstdraft/design`. Each takes `--environment ` (default +`production`) and `--staging`, and uses the pinned origin. Each prints one JSON object on standard output, with a +`next` sentence that says what to do next, and a handled error as one JSON envelope on standard error. They need: + +- `gh`, logged in with access to the application's repository, for Actions secrets, variables, and CI runs; +- `ssh-keygen` and `ssh` (the OpenSSH client), for `host create`. + +They need no Docker, Ruby, or Kamal on the owner's computer. + +### Create a host + +```sh +firstdraft host create [--region ] [--size ] +``` + +The command first checks that `config/deploy.yml` exists and that `ci.yml` has a `deploy` job, or reports +`deploy_files_missing`. Each later step is skipped when it is already done, so running the command again continues +where it stopped: + +1. It reads the repository and its default branch with `gh repo view`, then reads the host. +2. Without a host, it generates an Ed25519 key with `ssh-keygen` at + `$XDG_CONFIG_HOME/firstdraft/hosts///id_ed25519` (or under `~/.config`), and sends only + the public line to First Draft, which creates the Droplet. A host that exists must trust this computer's key (its + `ssh_key_fingerprint`), or the command reports `host_key_missing`. +3. It stores the private key as the Actions secret `SSH_PRIVATE_KEY`, and generates `SECRET_KEY_BASE` and + `POSTGRES_PASSWORD` when `gh secret list` does not name them. Each value goes to `gh secret set` on standard + input; none is printed. +4. It waits for the host to be `ready`, then for the Droplet's first-boot setup: it runs `cloud-init status` over + `ssh` as the host's `ssh_user`. The first connection records the Droplet's key in that directory's `known_hosts`, + and later connections refuse a different one. +5. Once setup is done, it sets the repository variables `APP_HOST` (the Droplet's `sslip.io` name, unless already + set) and `DEPLOY_HOST` (its IPv4). The `deploy` job is skipped until `DEPLOY_HOST` is set, so no deploy reaches a + Droplet that is still setting itself up. + +It waits at most five minutes and then prints where it stopped in `step`: `provisioning`, `setting_up`, or +`connected`. The output names the host, the `url`, the secret and variable names it stored, the newest CI run on the +default branch (`checks`), and `next`. A host whose creation failed reports `host_failed` with `host.failure`; a +first-boot setup that reported an error reports `host_setup_failed`. + +### Read a host's status + +```sh +firstdraft host status [--wait] +``` + +The command reads the host, and once it is `ready`, its backups and connected domain; `domain` is `null` without +one, and `host` is `null` when the Environment has none. It also reads the newest CI run on the default branch with +`gh run list` and its jobs with `gh run view`, and requests `/up` on `APP_HOST`. `next` tells these apart: + +- the Droplet is still being created or setting itself up; +- CI failed on the default branch, naming the failed jobs, so nothing deployed; +- CI is still running; +- the checks passed before the repository was connected, so nothing deployed (push, or `gh run rerun `); +- the last `deploy` job failed; +- the app is live, or it deployed but `/up` does not answer. + +`host.release` is First Draft's own record of the last deploy. `--wait` repeats the reads every 10 seconds while the +host or the CI run is busy, for at most five minutes. + +### Resize or destroy a host + +```sh +firstdraft host resize --size --yes +firstdraft host destroy --confirm +``` + +Both need the owner's agreement first. Without `--yes`, or with a `--confirm` value other than the Environment's +name, the command sends nothing and reports `confirmation_required` (exit 2). `resize` powers the Droplet off, +changes its CPU and memory but not its disk, and powers it on; the app is down meanwhile. `destroy` asks First Draft +to remove the Droplet, then deletes the `DEPLOY_HOST` and `APP_HOST` variables and the `SSH_PRIVATE_KEY` secret with +`gh`, and this computer's key directory. Its `github.left` names anything `gh` could not delete. + +### Connect a domain + +```sh +firstdraft host domain +firstdraft host domain connect +firstdraft host domain check +firstdraft host domain disconnect +``` + +Domains are the owner's own; First Draft registers none. `connect` returns the DNS records to create at the owner's +DNS provider, as `{purpose, type, name, value, required, status, found}` rows; email records join them once the app +record is right. `check` checks them now. Once the `app` record is `ok`, it sets `APP_HOST` to the hostname with +`gh variable set`, and `app_host_changed` says so: the next deploy serves the domain and obtains its certificate. +`disconnect` removes the domain and sets `APP_HOST` back to the Droplet's `sslip.io` name. Without a command, the +command prints the last check. + +### Email + +```sh +firstdraft host email +firstdraft host email connect +``` + +Without a command, it prints whether the app can send email, its sending domain, and the month's allowance. Nothing +is sent before a domain is connected. `connect` asks First Draft for a new SMTP credential, which revokes the earlier +one, stores the password as the Actions secret `SMTP_PASSWORD`, and stores `SMTP_ADDRESS`, `SMTP_PORT`, +`SMTP_USERNAME`, and `SMTP_HEADERS` (the headers as JSON) as variables. It prints no password. The app sends email +after its next deploy. + ## Service endpoints The CLI calls these Service API routes. The `/v1` routes send the selected token as a Bearer credential; @@ -880,23 +1002,34 @@ timeout. Each request takes its method and path from one `SERVICE_ROUTES` entry in `src/api-response.js`. `test/service-endpoints.test.js` fails when this table and `SERVICE_ROUTES` differ, or when no file in `src/` uses a declared route. -| Method | Path | Purpose | -| ------ | -------------------------------------------------------------------------- | ------------------------------------ | -| `PUT` | `/v1/projects/{project_id}/foundation-plan` | Create or replace the Head | -| `GET` | `/v1/projects/{project_id}/analysis` | Read the Head's current analysis | -| `POST` | `/v1/projects/{project_id}/compilations` | Start a Compilation of the Head | -| `GET` | `/v1/projects/{project_id}/compilations/{compilation_id}` | Read one retained Compilation | -| `POST` | `/v1/projects/{project_id}/compilations/{compilation_id}/cancel` | Cancel that Compilation | -| `GET` | `/v1/projects/{project_id}/compilations/{compilation_id}/artifact` | Download that Compilation's artifact | -| `PUT` | `/v1/projects/{project_id}/github-publication` | Start or rejoin the Publication | -| `GET` | `/v1/projects/{project_id}/github-publication` | Poll or reconcile the Publication | -| `GET` | `/v1/account` | Read whether the account reports | -| `POST` | `/v1/projects/{project_id}/compilations/{compilation_id}/progress-reports` | Send a progress report | -| `POST` | `/v1/projects/{project_id}/compilations/{compilation_id}/failure-reports` | Send a failure report | -| `POST` | `/v1/projects/{project_id}/notes` | Send a note | -| `POST` | `/oauth/token` | Exchange a login grant for a token | -| `POST` | `/oauth/device_authorization` | Start a device-flow login | -| `POST` | `/oauth/revoke` | Revoke a saved token | +| Method | Path | Purpose | +| -------- | --------------------------------------------------------------------------------------- | ------------------------------------ | +| `PUT` | `/v1/projects/{project_id}/foundation-plan` | Create or replace the Head | +| `GET` | `/v1/projects/{project_id}/analysis` | Read the Head's current analysis | +| `POST` | `/v1/projects/{project_id}/compilations` | Start a Compilation of the Head | +| `GET` | `/v1/projects/{project_id}/compilations/{compilation_id}` | Read one retained Compilation | +| `POST` | `/v1/projects/{project_id}/compilations/{compilation_id}/cancel` | Cancel that Compilation | +| `GET` | `/v1/projects/{project_id}/compilations/{compilation_id}/artifact` | Download that Compilation's artifact | +| `PUT` | `/v1/projects/{project_id}/github-publication` | Start or rejoin the Publication | +| `GET` | `/v1/projects/{project_id}/github-publication` | Poll or reconcile the Publication | +| `GET` | `/v1/account` | Read whether the account reports | +| `POST` | `/v1/projects/{project_id}/compilations/{compilation_id}/progress-reports` | Send a progress report | +| `POST` | `/v1/projects/{project_id}/compilations/{compilation_id}/failure-reports` | Send a failure report | +| `POST` | `/v1/projects/{project_id}/notes` | Send a note | +| `POST` | `/v1/projects/{project_id}/environments/{environment_name}/host` | Create the Environment's host | +| `GET` | `/v1/projects/{project_id}/environments/{environment_name}/host` | Read the host | +| `PATCH` | `/v1/projects/{project_id}/environments/{environment_name}/host` | Resize the host | +| `DELETE` | `/v1/projects/{project_id}/environments/{environment_name}/host` | Destroy the host | +| `GET` | `/v1/projects/{project_id}/environments/{environment_name}/host/backups` | Read the host's backups | +| `PUT` | `/v1/projects/{project_id}/environments/{environment_name}/host/domain` | Connect a domain | +| `GET` | `/v1/projects/{project_id}/environments/{environment_name}/host/domain` | Read the domain's last check | +| `POST` | `/v1/projects/{project_id}/environments/{environment_name}/host/domain/check` | Check the domain's records now | +| `DELETE` | `/v1/projects/{project_id}/environments/{environment_name}/host/domain` | Disconnect the domain | +| `GET` | `/v1/projects/{project_id}/environments/{environment_name}/host/email` | Read the host's email state | +| `POST` | `/v1/projects/{project_id}/environments/{environment_name}/host/email/smtp-credentials` | Create new SMTP credentials | +| `POST` | `/oauth/token` | Exchange a login grant for a token | +| `POST` | `/oauth/device_authorization` | Start a device-flow login | +| `POST` | `/oauth/revoke` | Revoke a saved token | `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. @@ -904,6 +1037,11 @@ Compilation, polls it, and downloads its artifact. With `--github`, it starts an `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. Each `note` command reads it and, with reports on, posts its note. +`host create` reads the host, and creates it when there is none, then polls it. `host status` reads the host, its +backups, and its domain. `host resize` and `host destroy` send the `PATCH` and `DELETE`. `host domain` reads the +domain, `connect` sends the `PUT`, `check` the check `POST`, and `disconnect` reads the host and sends the `DELETE`. +`host email` reads the email state, and `connect` creates SMTP credentials. These routes are drafted against the +Service's hosting sketch; no released API contract includes them yet. `login` exchanges its authorization code at `/oauth/token`. With `--interactive`, it starts at `/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 diff --git a/docs/errors.md b/docs/errors.md index 3dab8e0..95ab054 100644 --- a/docs/errors.md +++ b/docs/errors.md @@ -256,49 +256,77 @@ A GitHub preflight retry with no `retry_at` is paused and requires operator reco retrying. `publication_changed` means the pinned Publication identity or provenance changed, so the CLI deliberately stopped without following the replacement. +## Hosting recovery + +Host commands make one request per step and keep no local record of progress, so recovery reads before it repeats: + +- **Reads** (`host status`, `host domain`, `host email`) are safe to retry after `host_unavailable`. +- **`host create`** is safe to run again after any failure: it reads the host first and skips each finished step. + It never creates a second host for the Environment, and First Draft answers a second create with the existing + host. `host_key_missing` means the Droplet trusts a key this computer does not hold; run host commands from the + computer that created it, or copy `key_directory` from there. Do not delete the host to recover. +- **`host resize`, `host destroy`, `host domain connect`, and `host email connect`** change something. After + `host_unavailable` or `invalid_host_response`, run `host status` (or `host domain`, `host email`) before repeating + one. `response.code` `host_busy` means another operation is still running; wait with `host status --wait`. +- **`github_failed`** names the `gh` command and its first line of output. Steps before it are done; fix the `gh` + login or repository access (`gh auth status`) and run the same command again. After `host email connect`, the new + SMTP password may not be stored; running it again makes another and revokes this one. +- **`tool_unavailable`** names the missing program, `gh`, `ssh-keygen`, or `ssh`; nothing after the step that needed + it ran. +- **`ssh_failed`** during `host create` means `ssh` refused the connection for a reason other than the Droplet still + booting, such as a changed host key. Stop and tell the owner rather than removing `known_hosts`. +- **`host_failed`** and **`host_setup_failed`** need First Draft to look; do not run `host create` again. + ## Error index -| Commands | `error` | Exit | Meaning | -| ---------------------------------------------- | -------------------------------------------------------------------------------------------------- | ---: | --------------------------------------------------------------------------------------------------------------- | -| Any leaf command | `invalid_arguments` | 2 | Syntax was invalid; no request was made. | -| Network commands except `logout` | `update_required`, `api_contract_unsupported` | 1 | First Draft needs a newer plugin or CLI, or serves another API contract ([recovery](#update-and-limit-errors)). | -| 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 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. | -| Plan, `compilation *`, `report`, `note` | `local_input_unreadable` | 1 | Required local Plan or private state, or the Compilation record, could not be read. | -| Status, Compile, Compilation, `report`, `note` | `project_not_pushed` | 1 | No API origin is pinned for the local Project. | -| `plan push`, `plan compile` | `request_outcome_unknown` | 1 | A mutation or its response could not be verified; `plan compile` identifies its mutation phase. | -| `plan push`, `plan compile` | `local_state_not_saved` | 1 | The Plan was accepted but the private ETag state could not be replaced; includes `recovery_state`. | -| `plan push`, `plan compile` | `server_rejected` | 1 | First Draft returned validated Plan diagnostics or rejected the request with a validated problem. | -| `plan status` | `server_rejected` | 1 | First Draft rejected the analysis status request with a validated non-authentication problem. | -| `plan status` | `status_unavailable`, `invalid_server_response` | 1 | The analysis read failed or violated its protocol. | -| `plan compile` | `analysis_status_unavailable`, `invalid_analysis_status`, `analysis_status_rejected` | 1 | The bounded analysis read failed, was invalid, or was rejected. | -| Analysis waits | `analysis_changed`, `wait_timed_out`, `analysis_wait_timed_out` | 1 | The pinned analysis changed or remained processing at the deadline. | -| `plan compile` | `plan_not_valid` | 1 | Analysis completed without `valid`; `current` contains diagnostics and status. | -| `plan compile` | `local_plan_changed` | 1 | Local bytes or saved state changed after acceptance, before the selected mutation. | -| `plan compile` | `compilation_start_rejected`, `compilation_status_unavailable`, `invalid_compilation_status` | 1 | Direct start was rejected or retained status failed; post-start errors include `current`. | -| `plan compile` | `compilation_changed`, `compilation_wait_timed_out`, `compilation_failed`, `compilation_cancelled` | 1 | The pinned direct Compilation changed, timed out, failed, or was cancelled. | -| `plan compile --github` | `publication_start_rejected`, `publication_status_unavailable`, `invalid_publication_status` | 1 | Publication start or status failed its validated transport contract. | -| `plan compile --github` | `publication_changed`, `publication_wait_timed_out`, `publication_failed`, `publication_cancelled` | 1 | The pinned Publication changed, timed out, or reached a non-success terminal state. | -| `compilation status`, `compilation download` | `compilation_status_unavailable`, `invalid_compilation_status` | 1 | The retained status could not be read or violated its exact contract. | -| `compilation status --wait` | `compilation_changed`, `compilation_wait_timed_out` | 1 | Retained identity/provenance changed or the wait ended. | -| `compilation download` | `compilation_not_succeeded` | 1 | Status was not `succeeded`; no artifact request was made. | -| `compilation cancel` | `compilation_cancel_rejected` | 1 | Nothing was cancelled; `response.code` says why ([recovery](#stuck-compilation-recovery)). | -| `compilation cancel` | `compilation_cancel_unavailable` | 1 | The cancellation could not be confirmed; repeating it is safe. | -| `compilation cancel` | `invalid_compilation_status` | 1 | The response violated the Compilation contract; check status before repeating. | -| 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`, `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. | -| `note ` | `note_rejected`, `note_unavailable`, `account_unavailable`, `invalid_server_response` | 1 | The note was refused or its outcome is unconfirmed, or the account read failed; continue without it. | -| `report`, `note wrong_output` | `compilation_not_recorded` | 1 | No Compilation was given or recorded; nothing was sent ([recovery](#report-and-note-errors)). | -| `note ` | `note_incomplete` | 2 | A field the note needs had nothing left after shaping; nothing was sent. | +| Commands | `error` | Exit | Meaning | +| ------------------------------------------------------ | -------------------------------------------------------------------------------------------------- | ---: | -------------------------------------------------------------------------------------------------------------------- | +| Any leaf command | `invalid_arguments` | 2 | Syntax was invalid; no request was made. | +| Network commands except `logout` | `update_required`, `api_contract_unsupported` | 1 | First Draft needs a newer plugin or CLI, or serves another API contract ([recovery](#update-and-limit-errors)). | +| 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 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. | +| Plan, `compilation *`, `report`, `note`, `host` | `local_input_unreadable` | 1 | Required local Plan or private state, or the Compilation record, could not be read. | +| Status, Compile, Compilation, `report`, `note`, `host` | `project_not_pushed` | 1 | No API origin is pinned for the local Project. | +| `plan push`, `plan compile` | `request_outcome_unknown` | 1 | A mutation or its response could not be verified; `plan compile` identifies its mutation phase. | +| `plan push`, `plan compile` | `local_state_not_saved` | 1 | The Plan was accepted but the private ETag state could not be replaced; includes `recovery_state`. | +| `plan push`, `plan compile` | `server_rejected` | 1 | First Draft returned validated Plan diagnostics or rejected the request with a validated problem. | +| `plan status` | `server_rejected` | 1 | First Draft rejected the analysis status request with a validated non-authentication problem. | +| `plan status` | `status_unavailable`, `invalid_server_response` | 1 | The analysis read failed or violated its protocol. | +| `plan compile` | `analysis_status_unavailable`, `invalid_analysis_status`, `analysis_status_rejected` | 1 | The bounded analysis read failed, was invalid, or was rejected. | +| Analysis waits | `analysis_changed`, `wait_timed_out`, `analysis_wait_timed_out` | 1 | The pinned analysis changed or remained processing at the deadline. | +| `plan compile` | `plan_not_valid` | 1 | Analysis completed without `valid`; `current` contains diagnostics and status. | +| `plan compile` | `local_plan_changed` | 1 | Local bytes or saved state changed after acceptance, before the selected mutation. | +| `plan compile` | `compilation_start_rejected`, `compilation_status_unavailable`, `invalid_compilation_status` | 1 | Direct start was rejected or retained status failed; post-start errors include `current`. | +| `plan compile` | `compilation_changed`, `compilation_wait_timed_out`, `compilation_failed`, `compilation_cancelled` | 1 | The pinned direct Compilation changed, timed out, failed, or was cancelled. | +| `plan compile --github` | `publication_start_rejected`, `publication_status_unavailable`, `invalid_publication_status` | 1 | Publication start or status failed its validated transport contract. | +| `plan compile --github` | `publication_changed`, `publication_wait_timed_out`, `publication_failed`, `publication_cancelled` | 1 | The pinned Publication changed, timed out, or reached a non-success terminal state. | +| `compilation status`, `compilation download` | `compilation_status_unavailable`, `invalid_compilation_status` | 1 | The retained status could not be read or violated its exact contract. | +| `compilation status --wait` | `compilation_changed`, `compilation_wait_timed_out` | 1 | Retained identity/provenance changed or the wait ended. | +| `compilation download` | `compilation_not_succeeded` | 1 | Status was not `succeeded`; no artifact request was made. | +| `compilation cancel` | `compilation_cancel_rejected` | 1 | Nothing was cancelled; `response.code` says why ([recovery](#stuck-compilation-recovery)). | +| `compilation cancel` | `compilation_cancel_unavailable` | 1 | The cancellation could not be confirmed; repeating it is safe. | +| `compilation cancel` | `invalid_compilation_status` | 1 | The response violated the Compilation contract; check status before repeating. | +| 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`, `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. | +| `note ` | `note_rejected`, `note_unavailable`, `account_unavailable`, `invalid_server_response` | 1 | The note was refused or its outcome is unconfirmed, or the account read failed; continue without it. | +| `report`, `note wrong_output` | `compilation_not_recorded` | 1 | No Compilation was given or recorded; nothing was sent ([recovery](#report-and-note-errors)). | +| `note ` | `note_incomplete` | 2 | A field the note needs had nothing left after shaping; nothing was sent. | +| `host *` | `host_rejected` | 1 | First Draft refused with a validated problem; `response.code` says why ([recovery](#hosting-recovery)). | +| `host *` | `host_unavailable`, `invalid_host_response` | 1 | The request failed or its result is unconfirmed, or the response broke its contract ([recovery](#hosting-recovery)). | +| `host resize`, `host destroy` | `confirmation_required` | 2 | The owner's confirmation flag is missing or names another Environment; nothing was sent. | +| `host create` | `deploy_files_missing` | 1 | The application has no Kamal deploy files or `deploy` job; `missing` lists them. Nothing was sent. | +| `host *` | `tool_unavailable`, `github_failed` | 1 | `gh`, `ssh-keygen`, or `ssh` is missing, or a `gh` command failed; `tool`, `command`, and `message` say which. | +| `host create` | `host_key_missing`, `ssh_failed` | 1 | The host trusts a key this computer lacks, or `ssh` refused the connection ([recovery](#hosting-recovery)). | +| `host create` | `host_failed`, `host_setup_failed` | 1 | DigitalOcean or the Droplet's first-boot setup failed; tell the owner. | Root-output `invalid_output_path.reason` values are `destination_exists`, `root_not_real`, `root_not_writable`, `root_platform_unsupported`, `root_reserved_path`, `root_entry_unsupported`, `root_enclosing_worktree`, diff --git a/scripts/check-pack.js b/scripts/check-pack.js index 7319e00..74442e9 100644 --- a/scripts/check-pack.js +++ b/scripts/check-pack.js @@ -43,6 +43,8 @@ if (result.status !== 0) { "src/cli.js", "src/commands/account.js", "src/commands/compilation.js", + "src/commands/host-command.js", + "src/commands/host.js", "src/commands/login.js", "src/commands/logout.js", "src/commands/note.js", @@ -56,6 +58,7 @@ if (result.status !== 0) { "src/compilation-artifact.js", "src/credentials.js", "src/file-system.js", + "src/host-tools.js", "src/oauth.js", "src/plan-compile-progress.js", "src/plan-state.js", diff --git a/scripts/smoke-package.js b/scripts/smoke-package.js index 4872ab0..390c23e 100644 --- a/scripts/smoke-package.js +++ b/scripts/smoke-package.js @@ -273,6 +273,25 @@ try { "Invalid arguments. Run 'firstdraft compilation cancel --help' for usage.", }); + const invalidHost = spawnPackedCli( + ["host", "status", "--canary-secret-option"], + installationDirectory, + ); + assertHandledFailure(invalidHost, 2, { + error: "invalid_arguments", + detail: "Invalid arguments. Run 'firstdraft host status --help' for usage.", + }); + + const unconfirmedDestroy = spawnPackedCli( + ["host", "destroy"], + installationDirectory, + ); + assertHandledFailure(unconfirmedDestroy, 2, { + error: "confirmation_required", + detail: + "Destroying removes the Droplet and its data. Ask the owner, suggest a database export first, then pass --confirm production. Nothing was sent.", + }); + const invalidAccount = spawnPackedCli( ["account", "--canary-secret-option"], installationDirectory, diff --git a/src/api-response.js b/src/api-response.js index b604906..a12e129 100644 --- a/src/api-response.js +++ b/src/api-response.js @@ -75,6 +75,50 @@ export const SERVICE_ROUTES = { method: "POST", path: "/v1/projects/{project_id}/notes", }, + createHost: { + method: "POST", + path: "/v1/projects/{project_id}/environments/{environment_name}/host", + }, + readHost: { + method: "GET", + path: "/v1/projects/{project_id}/environments/{environment_name}/host", + }, + resizeHost: { + method: "PATCH", + path: "/v1/projects/{project_id}/environments/{environment_name}/host", + }, + destroyHost: { + method: "DELETE", + path: "/v1/projects/{project_id}/environments/{environment_name}/host", + }, + readBackups: { + method: "GET", + path: "/v1/projects/{project_id}/environments/{environment_name}/host/backups", + }, + connectDomain: { + method: "PUT", + path: "/v1/projects/{project_id}/environments/{environment_name}/host/domain", + }, + readDomain: { + method: "GET", + path: "/v1/projects/{project_id}/environments/{environment_name}/host/domain", + }, + checkDomain: { + method: "POST", + path: "/v1/projects/{project_id}/environments/{environment_name}/host/domain/check", + }, + disconnectDomain: { + method: "DELETE", + path: "/v1/projects/{project_id}/environments/{environment_name}/host/domain", + }, + readEmail: { + method: "GET", + path: "/v1/projects/{project_id}/environments/{environment_name}/host/email", + }, + createSmtpCredentials: { + method: "POST", + path: "/v1/projects/{project_id}/environments/{environment_name}/host/email/smtp-credentials", + }, requestOAuthToken: { method: "POST", path: "/oauth/token", diff --git a/src/cli.js b/src/cli.js index 5002f8f..2252d1a 100644 --- a/src/cli.js +++ b/src/cli.js @@ -75,6 +75,7 @@ import { resolveLoginOrigin, startDeviceLogin, } from "./commands/login.js"; +import { runHost } from "./commands/host-command.js"; import { LogoutFailedError, logout } from "./commands/logout.js"; import { initializePlan } from "./commands/plan-init.js"; import { @@ -162,6 +163,7 @@ Commands: account Show whether this account sends reports compilation Inspect, download, and cancel Compilations generate Generate local values + host Create and operate the application's First Draft host login Log in to First Draft and save a token logout Revoke and remove the saved token note Send a note about a problem with First Draft @@ -868,6 +870,9 @@ const PINNED_NOT_PUSHED_DETAIL = * @property {() => number} [loginNow] * @property {import("./oauth.js").StartLoopbackServer} [startLoopbackServer] * @property {() => number} [serviceNow] the clock for a limit's retry time + * @property {import("./host-tools.js").ToolRunner} [hostTools] runs gh, ssh-keygen, and ssh + * @property {(ms: number) => Promise} [hostSleep] + * @property {() => number} [hostNow] */ /** @@ -967,6 +972,9 @@ export async function run({ loginNow, startLoopbackServer, serviceNow, + hostTools, + hostSleep, + hostNow, }) { const staging = argv[0] === "--staging"; if (staging) argv = argv.slice(1); @@ -1099,6 +1107,42 @@ export async function run({ }); } + if (argv[0] === "host") { + const directory = cwd ?? getCwd(); + return runHost({ + argv: argv.slice(1), + stdout, + stderr, + cwd: directory, + credentials, + fetchFunction, + createRequestSignal, + hostTools, + hostSleep, + hostNow, + shared: { + authenticate: (stagingOption) => + authenticatePinnedProject({ + argv, + stdout, + stderr, + cwd: directory, + getCwd, + fetchFunction, + credentials, + apiUrl, + apiToken, + stagingApiToken, + staging: staging || stagingOption === true, + service, + }), + writeSharedError: writePinnedProjectError, + writeAuthenticationRequired, + settle: (promise) => service.settle(promise), + }, + }); + } + return runRoot({ argv, stdout, stderr }); } diff --git a/src/commands/host-command.js b/src/commands/host-command.js new file mode 100644 index 0000000..4897633 --- /dev/null +++ b/src/commands/host-command.js @@ -0,0 +1,1100 @@ +import { randomBytes } from "node:crypto"; +import { existsSync, readFileSync } from "node:fs"; +import path from "node:path"; +import { setTimeout as delay } from "node:timers/promises"; +import { parseArgs } from "node:util"; + +import { isAuthenticationProblem } from "../api-authentication.js"; +import { + GithubCommandError, + SshCommandError, + ToolUnavailableError, + generateHostKey, + github, + hostKeyDirectory, + readHostKey, + readPrivateKey, + removeHostKey, + runTool, + ssh, +} from "../host-tools.js"; +import { + DEFAULT_ENVIRONMENT, + HostRejectedError, + HostResponseInvalidError, + HostUnavailableError, + checkDomain, + connectDomain, + createHost, + createSmtpCredentials, + defaultHostname, + destroyHost, + disconnectDomain, + isEnvironmentName, + isHostname, + isSlug, + readBackups, + readDomain, + readEmail, + readHost, + resizeHost, +} from "./host.js"; + +const WAIT_MS = 5 * 60_000; +const HOST_POLL_MS = 5_000; +const SETUP_POLL_MS = 10_000; +const UP_TIMEOUT_MS = 10_000; +const DEPLOY_FILES = ["config/deploy.yml", ".github/workflows/ci.yml"]; +// The deploy job stream H's prototype runs after every check on main. +const DEPLOY_JOB = "deploy"; +const BUSY_STATES = new Set(["provisioning", "resizing", "destroying"]); + +const ENVIRONMENT_HELP = `Environment: + FIRSTDRAFT_API_TOKEN Authenticate production or custom API origins + FIRSTDRAFT_STAGING_API_TOKEN Authenticate staging.firstdraft.com +`; +const COMMON_OPTIONS = ` --environment Deployed Environment (default: production) + --staging Use staging; reject a different saved origin + -h, --help Show help`; + +export const HOST_HELP = `First Draft CLI + +Usage: + firstdraft host [options] + +Commands: + create Create the app's Droplet and connect its repository + status Show the host, its release, and what stands in the way + resize Change the Droplet's size + destroy Remove the Droplet + domain Connect and check the app's own domain + email Show email state and store SMTP credentials + +Options: + -h, --help Show help + +Run host commands from the application's root. They use gh, logged in to +GitHub with access to the application's repository; create also uses +ssh-keygen and ssh. A push to the default branch whose checks all pass +deploys; no host command deploys. +`; + +const HOST_CREATE_HELP = `First Draft CLI + +Usage: + firstdraft host create [--region ] [--size ] + +Options: + --region DigitalOcean region (default: nyc1) + --size Droplet size (default: s-1vcpu-1gb) +${COMMON_OPTIONS} + +${ENVIRONMENT_HELP} +The command generates this host's SSH key on this computer, asks First Draft +to create the Droplet, and stores the key and the app's generated secrets as +GitHub Actions secrets with gh. Once the Droplet has finished setting itself +up, it sets the DEPLOY_HOST and APP_HOST repository variables, so the next +push whose checks all pass deploys. It waits at most five minutes; run it +again to continue. It prints no secret. +`; + +const HOST_STATUS_HELP = `First Draft CLI + +Usage: + firstdraft host status [--wait] + +Options: + --wait Wait while the host or a deploy is busy (5 min) +${COMMON_OPTIONS} + +${ENVIRONMENT_HELP} +The command prints the host, its backups and domain, the newest CI run on the +default branch, whether /up answers, and next: what stands between the owner +and a live app. +`; + +const HOST_RESIZE_HELP = `First Draft CLI + +Usage: + firstdraft host resize --size --yes + +Options: + --size The new Droplet size + --yes Confirm: the app is down while it resizes +${COMMON_OPTIONS} + +${ENVIRONMENT_HELP} +Ask the owner before passing --yes. The Droplet powers off, changes CPU and +memory, and powers on; its disk keeps its size. +`; + +const HOST_DESTROY_HELP = `First Draft CLI + +Usage: + firstdraft host destroy --confirm + +Options: + --confirm The Environment's name, to confirm +${COMMON_OPTIONS} + +${ENVIRONMENT_HELP} +Ask the owner first. First Draft removes the Droplet; its off-server backups +are kept for their retention period. The CLI then deletes the DEPLOY_HOST +and APP_HOST variables and the SSH_PRIVATE_KEY secret, and this computer's +key for the host. +`; + +const HOST_DOMAIN_HELP = `First Draft CLI + +Usage: + firstdraft host domain [options] + firstdraft host domain connect [options] + firstdraft host domain check [options] + firstdraft host domain disconnect [options] + +Options: +${COMMON_OPTIONS} + +${ENVIRONMENT_HELP} +Without a command, it prints the last check of the connected domain. connect +returns the DNS records to create at the owner's DNS provider. check checks +them now; once the app record is right, it sets APP_HOST to the domain, and +the next deploy serves it. disconnect removes the domain and sets APP_HOST +back to the Droplet's own name. +`; + +const HOST_EMAIL_HELP = `First Draft CLI + +Usage: + firstdraft host email [options] + firstdraft host email connect [options] + +Options: +${COMMON_OPTIONS} + +${ENVIRONMENT_HELP} +Without a command, it prints whether the app can send email and how much of +the month's allowance it has used. connect asks First Draft for new SMTP +credentials, revoking the earlier ones, and stores them with gh: the password +as the SMTP_PASSWORD secret, the rest as variables. It prints no password. +`; + +const HELP = new Map([ + ["create", HOST_CREATE_HELP], + ["status", HOST_STATUS_HELP], + ["resize", HOST_RESIZE_HELP], + ["destroy", HOST_DESTROY_HELP], + ["domain", HOST_DOMAIN_HELP], + ["email", HOST_EMAIL_HELP], +]); + +const DETAILS = { + invalidArguments: (/** @type {string} */ command) => + `Invalid arguments. Run 'firstdraft host ${command} --help' for usage.`, + deployFilesMissing: + "This application has no Kamal deploy files, so it was compiled for another host. Nothing was sent.", + rejected: + "First Draft rejected the request; response.code says why. host_not_found means the Environment has no host yet: run 'firstdraft host create'. host_busy means another operation is still running: run 'firstdraft host status --wait'. hosting_not_allowed means this account cannot hold another host yet.", + unavailable: + "Could not complete the request or confirm its result. A read is safe to retry. After create, resize, destroy, or a domain or email change, run 'firstdraft host status' before repeating it.", + invalidResponse: + "First Draft returned an invalid hosting response. Retrying unchanged will not repair this protocol mismatch; run 'firstdraft host status' to see the host.", + toolUnavailable: (/** @type {string} */ tool) => + `The ${tool} program is not installed or not on PATH. Ask the person to install ${tool === "gh" ? "GitHub's gh and run 'gh auth login'" : "the OpenSSH client"}, then run the command again.`, + githubFailed: + "A gh command failed; message is its first line of output. Check that gh is logged in ('gh auth status') with access to this repository, then run the command again: every step it completed is skipped.", + sshFailed: + "ssh could not run the command on the host; message says why. A changed host key means the Droplet is not the one this computer first reached: stop and tell the owner.", + hostKeyMissing: + "This Environment's host trusts an SSH key that this computer does not have. Run host commands from the computer that created the host, or copy its key directory (key_directory) here.", + hostFailed: + "First Draft could not create or change the Droplet; host.failure says why. Tell the owner; do not run create again until First Draft has looked.", + setupFailed: + "The Droplet's first-boot setup (cloud-init) reported an error, so the repository was not connected to it. Tell the owner.", + confirmResize: + "Resizing takes the app down and can change the bill. Ask the owner, then pass --yes. Nothing was sent.", + confirmDestroy: (/** @type {string} */ environment) => + `Destroying removes the Droplet and its data. Ask the owner, suggest a database export first, then pass --confirm ${environment}. Nothing was sent.`, +}; + +/** + * @typedef {object} HostShared + * @property {(staging: boolean | undefined) => {apiUrl: string, projectId: string, fetchFunction: typeof globalThis.fetch} | null} authenticate + * @property {(writer: {write(text: string): unknown}, error: unknown) => number | null} writeSharedError + * @property {(writer: {write(text: string): unknown}, status?: number, response?: Record) => void} writeAuthenticationRequired + * @property {(promise: Promise) => Promise} settle + */ + +/** + * @typedef {object} HostOptions + * @property {readonly string[]} argv + * @property {{write(text: string): unknown}} stdout + * @property {{write(text: string): unknown}} stderr + * @property {string} cwd + * @property {import("../credentials.js").CredentialStore} credentials + * @property {typeof globalThis.fetch} [fetchFunction] unwrapped, for /up + * @property {(timeoutMs: number) => AbortSignal} [createRequestSignal] + * @property {import("../host-tools.js").ToolRunner} [hostTools] + * @property {(ms: number) => Promise} [hostSleep] + * @property {() => number} [hostNow] + * @property {HostShared} shared + */ + +/** @param {HostOptions} options */ +export async function runHost(options) { + const [command, ...argv] = options.argv; + if (command === undefined || command === "--help" || command === "-h") { + options.stdout.write(HOST_HELP); + return 0; + } + if (!HELP.has(command)) { + writeJson(options.stderr, { + error: "invalid_arguments", + detail: "Invalid arguments. Run 'firstdraft host --help' for usage.", + }); + return 2; + } + + const sub = + (command === "domain" || command === "email") && + argv[0] !== undefined && + !argv[0].startsWith("-") + ? argv[0] + : undefined; + const parsed = parseCommand(command, sub, sub ? argv.slice(1) : argv); + if (parsed === null) { + writeJson(options.stderr, { + error: "invalid_arguments", + detail: DETAILS.invalidArguments(command), + }); + return 2; + } + if (parsed.help) { + options.stdout.write(/** @type {string} */ (HELP.get(command))); + return 0; + } + + if (command === "resize" && parsed.values.yes !== true) { + writeJson(options.stderr, { + error: "confirmation_required", + detail: DETAILS.confirmResize, + }); + return 2; + } + if (command === "destroy" && parsed.values.confirm !== parsed.environment) { + writeJson(options.stderr, { + error: "confirmation_required", + detail: DETAILS.confirmDestroy(parsed.environment), + }); + return 2; + } + if (command === "create") { + const missing = DEPLOY_FILES.filter( + (file) => !existsSync(path.join(options.cwd, file)), + ); + const workflow = path.join(options.cwd, DEPLOY_FILES[1] ?? ""); + if ( + missing.length === 0 && + !/^ {2}deploy:/m.test(readFileSync(workflow, "utf8")) + ) { + missing.push(`${DEPLOY_FILES[1]} job ${DEPLOY_JOB}`); + } + if (missing.length > 0) { + writeJson(options.stderr, { + error: "deploy_files_missing", + detail: DETAILS.deployFilesMissing, + missing, + }); + return 1; + } + } + + try { + const authentication = options.shared.authenticate( + parsed.values.staging === true, + ); + if (authentication === null) { + options.shared.writeAuthenticationRequired(options.stderr); + return 1; + } + const context = { + ...authentication, + environment: parsed.environment, + createRequestSignal: options.createRequestSignal, + }; + const result = await options.shared.settle( + dispatch(command, sub, parsed, context, options), + ); + writeJson(options.stdout, result); + return 0; + } catch (error) { + return writeHostError(options, error); + } +} + +/** + * @param {string} command + * @param {string | undefined} sub + * @param {readonly string[]} argv + */ +function parseCommand(command, sub, argv) { + /** @type {Record} */ + const flags = { + environment: { type: "string" }, + staging: { type: "boolean" }, + help: { type: "boolean", short: "h" }, + }; + if (command === "create") { + flags.region = { type: "string" }; + flags.size = { type: "string" }; + } + if (command === "status") flags.wait = { type: "boolean" }; + if (command === "resize") { + flags.size = { type: "string" }; + flags.yes = { type: "boolean" }; + } + if (command === "destroy") flags.confirm = { type: "string" }; + + let parsed; + try { + parsed = parseArgs({ + args: [...argv], + options: flags, + allowPositionals: true, + strict: true, + tokens: true, + }); + } catch (error) { + if ( + error instanceof Error && + "code" in error && + String(error.code).startsWith("ERR_PARSE_ARGS_") + ) { + return null; + } + throw error; + } + + const names = parsed.tokens + .filter((token) => token.kind === "option" && token.name !== "help") + .map((token) => (token.kind === "option" ? token.name : "")); + if (new Set(names).size !== names.length) return null; + + const values = /** @type {Record} */ ( + parsed.values + ); + if (values.help) + return { help: true, values, environment: "", positionals: [] }; + + const environment = values.environment ?? DEFAULT_ENVIRONMENT; + if (!isEnvironmentName(environment)) return null; + for (const slug of [values.region, values.size]) { + if (slug !== undefined && !isSlug(slug)) return null; + } + if (command === "resize" && values.size === undefined) return null; + + const positionals = parsed.positionals; + const expected = command === "domain" && sub === "connect" ? 1 : 0; + if (positionals.length !== expected) return null; + if ( + command === "domain" && + !["connect", "check", "disconnect", undefined].includes(sub) + ) { + return null; + } + if (command === "email" && !["connect", undefined].includes(sub)) return null; + if ( + sub === "connect" && + command === "domain" && + !isHostname(positionals[0]) + ) { + return null; + } + + return { help: false, values, environment, positionals }; +} + +/** + * @typedef {{help: boolean, values: Record, environment: string, positionals: string[]}} ParsedCommand + * @typedef {import("./host.js").HostContext} HostContext + */ + +/** + * @param {string} command + * @param {string | undefined} sub + * @param {ParsedCommand} parsed + * @param {HostContext} context + * @param {HostOptions} options + */ +async function dispatch(command, sub, parsed, context, options) { + const tools = options.hostTools ?? runTool; + if (command === "create") return create(parsed, context, options, tools); + if (command === "status") return status(parsed, context, options, tools); + if (command === "resize") { + const result = await resizeHost({ + ...context, + size: /** @type {string} */ (parsed.values.size), + }); + return { + ...result, + next: "The app is down while the Droplet resizes. Run 'firstdraft host status --wait' until host.state is ready.", + }; + } + if (command === "destroy") return destroy(context, options, tools); + if (command === "domain") return domain(sub, parsed, context, options, tools); + return email(sub, context, options, tools); +} + +/** + * @param {ParsedCommand} parsed + * @param {HostContext} context + * @param {HostOptions} options + * @param {import("../host-tools.js").ToolRunner} tools + */ +async function create(parsed, context, options, tools) { + const now = options.hostNow ?? Date.now; + const sleep = options.hostSleep ?? delay; + const deadline = now() + WAIT_MS; + const gh = github(tools, options.cwd); + const { repository, defaultBranch } = gh.repository(); + const keyDirectory = hostKeyDirectory( + options.credentials, + context.projectId, + context.environment, + ); + + let key = readHostKey(keyDirectory); + let response = await readExistingHost(context); + if (response === null) { + key ??= generateHostKey( + tools, + keyDirectory, + `firstdraft-${context.environment}-${repository}`, + ); + response = await createHost({ + ...context, + region: /** @type {string | undefined} */ (parsed.values.region), + size: /** @type {string | undefined} */ (parsed.values.size), + sshPublicKey: key.publicKey, + }); + } + if (key === null || key.fingerprint !== response.host.ssh_key_fingerprint) { + throw new HostKeyMissingError(keyDirectory); + } + + // The deploy job logs in with the same key the Droplet trusts. + const existing = new Set(gh.secretNames()); + gh.setSecret("SSH_PRIVATE_KEY", readPrivateKey(keyDirectory)); + /** @type {string[]} */ + const secrets = ["SSH_PRIVATE_KEY"]; + for (const [name, bytes] of /** @type {const} */ ([ + ["SECRET_KEY_BASE", 64], + // Hex keeps it safe inside DATABASE_URL. + ["POSTGRES_PASSWORD", 24], + ])) { + if (!existing.has(name)) + gh.setSecret(name, randomBytes(bytes).toString("hex")); + secrets.push(name); + } + + let host = response.host; + let progress = host.state; + while (BUSY_STATES.has(host.state) && now() < deadline) { + await sleep(HOST_POLL_MS); + host = (await readHost(context)).host; + if (host.state !== progress) { + progress = host.state; + options.stderr.write(`First Draft: the host is ${host.state}.\n`); + } + } + if (host.state === "failed") throw new HostFailedError(host); + + /** @type {"provisioning" | "setting_up" | "connected"} */ + let step = host.state === "ready" ? "setting_up" : "provisioning"; + const variables = gh.variables(); + if (step === "setting_up" && host.ipv4 !== null) { + const ipv4 = host.ipv4; + // The deploy job is skipped until DEPLOY_HOST is set, so no deploy + // races the Droplet's first-boot setup. + if (variables.get("DEPLOY_HOST") !== ipv4) { + while (step === "setting_up") { + const setup = setupState(tools, key, host, options.cwd); + if (setup === "error") throw new HostSetupFailedError(); + if (setup === "done") step = "connected"; + else if (now() >= deadline) break; + else { + options.stderr.write( + "First Draft: the Droplet is still setting itself up.\n", + ); + await sleep(SETUP_POLL_MS); + } + } + if (step === "connected") { + if (!variables.has("APP_HOST")) { + gh.setVariable("APP_HOST", defaultHostname(ipv4)); + variables.set("APP_HOST", defaultHostname(ipv4)); + } + gh.setVariable("DEPLOY_HOST", ipv4); + variables.set("DEPLOY_HOST", ipv4); + } + } else { + step = "connected"; + } + } + + const checks = step === "connected" ? readChecks(gh, defaultBranch) : null; + const appHost = variables.get("APP_HOST") ?? null; + return { + environment: response.environment, + host, + step, + url: appHost === null ? null : `https://${appHost}`, + github: { + repository, + secrets, + variables: ["DEPLOY_HOST", "APP_HOST"].filter((name) => + variables.has(name), + ), + }, + checks, + key_directory: keyDirectory, + next: nextStep({ + host, + step, + checks, + up: null, + defaultBranch, + command: "create", + }), + }; +} + +/** + * @param {ParsedCommand} parsed + * @param {HostContext} context + * @param {HostOptions} options + * @param {import("../host-tools.js").ToolRunner} tools + */ +async function status(parsed, context, options, tools) { + const now = options.hostNow ?? Date.now; + const sleep = options.hostSleep ?? delay; + const deadline = now() + WAIT_MS; + const gh = github(tools, options.cwd); + const { defaultBranch } = gh.repository(); + + for (;;) { + const response = await readExistingHost(context); + if (response === null) { + return { + environment: { + project_id: context.projectId, + name: context.environment, + }, + host: null, + next: "This Environment has no host. Run 'firstdraft host create' after the owner agrees to pay for one.", + }; + } + const { host } = response; + const variables = gh.variables(); + const step = + host.state === "provisioning" + ? "provisioning" + : variables.get("DEPLOY_HOST") === host.ipv4 + ? "connected" + : "setting_up"; + const ready = host.state === "ready"; + const backups = ready ? (await readBackups(context)).backups : null; + const domain = ready ? await readOptionalDomain(context) : null; + const checks = step === "connected" ? readChecks(gh, defaultBranch) : null; + const appHost = variables.get("APP_HOST") ?? null; + const up = + ready && appHost !== null + ? await probe(options.fetchFunction ?? globalThis.fetch, appHost) + : null; + const result = { + environment: response.environment, + host, + step, + url: appHost === null ? null : `https://${appHost}`, + up, + backups, + domain, + checks, + next: nextStep({ + host, + step, + checks, + up, + defaultBranch, + command: "status", + }), + }; + + const busy = + BUSY_STATES.has(host.state) || + checks?.run?.status === "in_progress" || + checks?.run?.status === "queued"; + if (!parsed.values.wait || !busy || now() >= deadline) return result; + await sleep(SETUP_POLL_MS); + } +} + +/** + * @param {HostContext} context + * @param {HostOptions} options + * @param {import("../host-tools.js").ToolRunner} tools + */ +async function destroy(context, options, tools) { + const gh = github(tools, options.cwd); + gh.repository(); + const result = await destroyHost({ + ...context, + confirm: context.environment, + }); + + // The Droplet is going, so the repository stops deploying to it and this + // computer forgets its key. Each step is attempted, and what is left is + // named, because the destroy itself has already been accepted. + /** @type {string[]} */ + const deleted = []; + /** @type {string[]} */ + const left = []; + const variables = gh.variables(); + const secrets = new Set(gh.secretNames()); + for (const [kind, name] of /** @type {const} */ ([ + ["variable", "DEPLOY_HOST"], + ["variable", "APP_HOST"], + ["secret", "SSH_PRIVATE_KEY"], + ])) { + const present = + kind === "variable" ? variables.has(name) : secrets.has(name); + if (!present) continue; + try { + if (kind === "variable") gh.deleteVariable(name); + else gh.deleteSecret(name); + deleted.push(name); + } catch (error) { + if (!(error instanceof GithubCommandError)) throw error; + left.push(name); + } + } + const keyDirectory = hostKeyDirectory( + options.credentials, + context.projectId, + context.environment, + ); + removeHostKey(keyDirectory); + + return { + ...result, + github: { deleted, left }, + key_directory_removed: keyDirectory, + next: + left.length === 0 + ? "First Draft is removing the Droplet. Run 'firstdraft host status' until it reports no host." + : `First Draft is removing the Droplet. gh could not delete ${left.join(", ")}; delete them with 'gh variable delete' or 'gh secret delete'.`, + }; +} + +/** + * @param {string | undefined} sub + * @param {ParsedCommand} parsed + * @param {HostContext} context + * @param {HostOptions} options + * @param {import("../host-tools.js").ToolRunner} tools + */ +async function domain(sub, parsed, context, options, tools) { + if (sub === undefined) { + const result = await readDomain(context); + return { ...result, next: domainNext(result.domain, false) }; + } + if (sub === "connect") { + const result = await connectDomain({ + ...context, + hostname: /** @type {string} */ (parsed.positionals[0]), + }); + return { + ...result, + next: "Ask the owner to create each record in records at their DNS provider, then run 'firstdraft host domain check'. DNS changes can take hours to appear.", + }; + } + + const gh = github(tools, options.cwd); + if (sub === "disconnect") { + const { host } = await readHost(context); + const result = await disconnectDomain(context); + const variables = gh.variables(); + const fallback = host.ipv4 === null ? null : defaultHostname(host.ipv4); + const changed = fallback !== null && variables.get("APP_HOST") !== fallback; + if (changed) gh.setVariable("APP_HOST", fallback); + return { + ...result, + app_host: variables.get("APP_HOST") ?? null, + app_host_now: changed ? fallback : (variables.get("APP_HOST") ?? null), + next: changed + ? "APP_HOST is the Droplet's own name again; the next deploy stops serving the domain. Remove its DNS records at the DNS provider." + : "The domain is disconnected. Remove its DNS records at the DNS provider.", + }; + } + + const result = await checkDomain(context); + const appRecordOk = + result.domain !== null && + result.domain.records.some( + (row) => row.purpose === "app" && row.status === "ok", + ); + let switched = false; + if (appRecordOk && result.domain !== null) { + const variables = gh.variables(); + if (variables.get("APP_HOST") !== result.domain.hostname) { + gh.setVariable("APP_HOST", result.domain.hostname); + switched = true; + } + } + return { + ...result, + app_host_changed: switched, + next: domainNext(result.domain, switched), + }; +} + +/** + * @param {string | undefined} sub + * @param {HostContext} context + * @param {HostOptions} options + * @param {import("../host-tools.js").ToolRunner} tools + */ +async function email(sub, context, options, tools) { + if (sub === undefined) { + const result = await readEmail(context); + return { ...result, next: emailNext(result.email.state) }; + } + + const gh = github(tools, options.cwd); + gh.repository(); + const { environment, smtp, password } = await createSmtpCredentials(context); + gh.setSecret("SMTP_PASSWORD", password); + gh.setVariable("SMTP_ADDRESS", String(smtp.host)); + gh.setVariable("SMTP_PORT", String(smtp.port)); + gh.setVariable("SMTP_USERNAME", String(smtp.username)); + gh.setVariable("SMTP_HEADERS", JSON.stringify(smtp.headers)); + return { + environment, + smtp, + github: { + secrets: ["SMTP_PASSWORD"], + variables: ["SMTP_ADDRESS", "SMTP_PORT", "SMTP_USERNAME", "SMTP_HEADERS"], + }, + next: "The earlier SMTP password no longer works. The app sends email after the next deploy: push to the default branch, or rerun its newest CI run with 'gh run rerun '.", + }; +} + +/** @param {HostContext} context */ +async function readExistingHost(context) { + try { + return await readHost(context); + } catch (error) { + if ( + error instanceof HostRejectedError && + error.status === 404 && + error.response.code === "host_not_found" + ) { + return null; + } + throw error; + } +} + +/** @param {HostContext} context */ +async function readOptionalDomain(context) { + try { + return (await readDomain(context)).domain; + } catch (error) { + if ( + error instanceof HostRejectedError && + error.status === 404 && + error.response.code === "domain_not_found" + ) { + return null; + } + throw error; + } +} + +/** + * Reads cloud-init's state on the Droplet: `done`, `running`, or `error`. + * A Droplet that does not answer yet is still `running`. + * + * @param {import("../host-tools.js").ToolRunner} tools + * @param {{privateKey: string, knownHosts: string}} key + * @param {{ssh_user: unknown, ipv4: unknown}} host + * @param {string} cwd + */ +function setupState(tools, key, host, cwd) { + const result = ssh( + tools, + key, + { user: String(host.ssh_user), ipv4: String(host.ipv4) }, + "cloud-init status", + cwd, + ); + // ssh exits 255 for its own failures, such as a Droplet still booting. + if (result.status === 255) { + if (/host key/i.test(result.stderr)) throw new SshCommandError(result); + return "running"; + } + const match = /^status:\s*(\w+)/m.exec(result.stdout); + if (match?.[1] === "done") return "done"; + if (match?.[1] === "error") return "error"; + return "running"; +} + +/** + * @param {ReturnType} gh + * @param {string} branch + */ +function readChecks(gh, branch) { + const run = gh.latestRun(branch); + if (run === null) return { branch, run: null, failed_jobs: [], deploy: null }; + + const deploy = run.jobs.find((job) => job.name === DEPLOY_JOB) ?? null; + return { + branch, + run: { + id: run.id, + url: run.url, + head_sha: run.head_sha, + status: run.status, + conclusion: run.conclusion, + }, + failed_jobs: run.jobs + .filter( + (job) => + job.name !== DEPLOY_JOB && + ["failure", "timed_out", "cancelled"].includes(job.conclusion), + ) + .map((job) => job.name), + deploy: + deploy === null + ? null + : { status: deploy.status, conclusion: deploy.conclusion }, + }; +} + +/** + * @param {typeof globalThis.fetch} fetchFunction + * @param {string} hostname + */ +async function probe(fetchFunction, hostname) { + // A plain request to the app itself: no First Draft token or header. + try { + const response = await fetchFunction(`https://${hostname}/up`, { + redirect: "manual", + signal: AbortSignal.timeout(UP_TIMEOUT_MS), + }); + return { hostname, status: response.status, ok: response.status === 200 }; + } catch (error) { + if (!(error instanceof Error)) throw error; + return { hostname, status: null, ok: false }; + } +} + +/** + * The one sentence that says what stands between the owner and a live app. + * + * @param {{host: Record, step: string, checks: ReturnType | null, up: {ok: boolean} | null, defaultBranch: string, command: string}} state + */ +export function nextStep({ host, step, checks, up, defaultBranch, command }) { + const again = "run 'firstdraft host create' again"; + if (host.state === "failed") { + return "The host failed; host.failure says why. Tell the owner."; + } + if (host.state === "resizing") { + return "The Droplet is resizing and the app is down. Run 'firstdraft host status --wait'."; + } + if (host.state === "destroying") return "The Droplet is being removed."; + if (step === "provisioning") { + return `DigitalOcean is still creating the Droplet. In a minute, ${again}; it continues where it stopped.`; + } + if (step === "setting_up") { + return command === "create" + ? `The Droplet is still setting itself up (about 15 minutes after it starts). In a few minutes, ${again} to connect the repository.` + : `The repository is not connected to the Droplet yet: ${again}.`; + } + + const release = host.release?.state; + const run = checks?.run ?? null; + const deploy = checks?.deploy ?? null; + if (release === "live" || deploy?.conclusion === "success") { + if (up !== null && !up.ok) { + return "The last deploy succeeded, but /up does not answer. Read the app's log and tell the owner."; + } + return "The app is live. Every push to the default branch whose checks all pass deploys it."; + } + if (deploy?.conclusion === "failure" || release === "failed") { + return `The last deploy failed${run ? ` (${run.url})` : ""}. Read the deploy job's log, fix the cause, and push; an earlier release, if any, keeps serving.`; + } + if (run === null) { + return `Nothing is deployed yet. Push to ${defaultBranch}: when every check passes, that push deploys.`; + } + if (run.status !== "completed") { + return `CI is running on ${defaultBranch}. When every check passes, the deploy job runs; run 'firstdraft host status --wait'.`; + } + if (run.conclusion !== "success") { + const jobs = checks?.failed_jobs.length + ? ` (${checks.failed_jobs.join(", ")})` + : ""; + return `Nothing is deployed: CI failed on ${defaultBranch}${jobs}, and the deploy job runs only when every check passes. Write what the README's Behavior to write lists until bin/ci passes, then push to ${defaultBranch}.`; + } + return `The checks on ${defaultBranch} passed before the repository was connected, so nothing deployed. Push to ${defaultBranch}, or rerun that run with 'gh run rerun ${run.id}'.`; +} + +/** + * @param {{state: unknown, hostname: unknown, records: {required: unknown, status: unknown}[]} | null} domain + * @param {boolean} switched + */ +function domainNext(domain, switched) { + if (domain === null) { + return "No domain is connected. Run 'firstdraft host domain connect ' with the owner's domain."; + } + if (switched) { + return `APP_HOST is now ${domain.hostname}. The next deploy serves it and gets its certificate: push to the default branch, or rerun its newest CI run with 'gh run rerun '.`; + } + if (domain.state === "connected") { + return "Every required record is right."; + } + return "Some required records are missing or wrong; records says which. Ask the owner to fix them at their DNS provider, then run 'firstdraft host domain check' again. First Draft also rechecks every 10 minutes for 72 hours."; +} + +/** @param {unknown} state */ +function emailNext(state) { + if (state === "waiting_for_domain") { + return "Email starts after a domain is connected: run 'firstdraft host domain connect '."; + } + if (state === "verifying") { + return "Amazon SES has not seen the email records yet. Run 'firstdraft host domain check' to see which are missing."; + } + if (state === "paused") { + return "Sending is paused; email.paused_reason says why. Tell the owner."; + } + return "Email is ready. If the app has no SMTP credentials yet, run 'firstdraft host email connect'."; +} + +class HostKeyMissingError extends Error { + /** @param {string} keyDirectory */ + constructor(keyDirectory) { + super("This computer has no key for the host."); + this.keyDirectory = keyDirectory; + } +} + +class HostFailedError extends Error { + /** @param {Record} host */ + constructor(host) { + super("The host failed."); + this.host = host; + } +} + +class HostSetupFailedError extends Error {} + +/** + * @param {HostOptions} options + * @param {unknown} error + */ +function writeHostError(options, error) { + const { stderr } = options; + const shared = options.shared.writeSharedError(stderr, error); + if (shared !== null) return shared; + + if (error instanceof HostRejectedError) { + if (isAuthenticationProblem(error.status, error.response)) { + options.shared.writeAuthenticationRequired( + stderr, + error.status, + error.response, + ); + return 1; + } + writeJson(stderr, { + error: "host_rejected", + detail: DETAILS.rejected, + status: error.status, + response: error.response, + }); + return 1; + } + if (error instanceof HostUnavailableError) { + writeJson(stderr, { + error: "host_unavailable", + detail: DETAILS.unavailable, + ...(typeof error.status === "number" ? { status: error.status } : {}), + ...(error.response ? { response: error.response } : {}), + }); + return 1; + } + if (error instanceof HostResponseInvalidError) { + writeJson(stderr, { + error: "invalid_host_response", + detail: DETAILS.invalidResponse, + status: error.status, + }); + return 1; + } + if (error instanceof ToolUnavailableError) { + writeJson(stderr, { + error: "tool_unavailable", + detail: DETAILS.toolUnavailable(error.tool), + tool: error.tool, + }); + return 1; + } + if (error instanceof GithubCommandError) { + writeJson(stderr, { + error: "github_failed", + detail: DETAILS.githubFailed, + command: error.command, + exit_status: error.exitStatus, + message: error.reason, + }); + return 1; + } + if (error instanceof SshCommandError) { + writeJson(stderr, { + error: "ssh_failed", + detail: DETAILS.sshFailed, + exit_status: error.exitStatus, + message: error.reason, + }); + return 1; + } + if (error instanceof HostKeyMissingError) { + writeJson(stderr, { + error: "host_key_missing", + detail: DETAILS.hostKeyMissing, + key_directory: error.keyDirectory, + }); + return 1; + } + if (error instanceof HostFailedError) { + writeJson(stderr, { + error: "host_failed", + detail: DETAILS.hostFailed, + host: error.host, + }); + return 1; + } + if (error instanceof HostSetupFailedError) { + writeJson(stderr, { + error: "host_setup_failed", + detail: DETAILS.setupFailed, + }); + return 1; + } + throw error; +} + +/** @param {{write(text: string): unknown}} writer @param {unknown} value */ +function writeJson(writer, value) { + writer.write(`${JSON.stringify(value, null, 2)}\n`); +} diff --git a/src/commands/host.js b/src/commands/host.js new file mode 100644 index 0000000..9741be6 --- /dev/null +++ b/src/commands/host.js @@ -0,0 +1,701 @@ +import { + FirstDraftNetworkError, + FirstDraftProtocolError, + SERVICE_ROUTES, + isProblemBody, + readResponseBody, + responseMediaType, + sendRequest, + serviceEndpoint, +} from "../api-response.js"; + +const REQUEST_TIMEOUT_MS = 30_000; +export const DEFAULT_ENVIRONMENT = "production"; +// The Service's Project::Environment::NAME_PATTERN. Checking it locally also +// keeps a name from adding path segments to the request URL. +const ENVIRONMENT_NAME_PATTERN = /^[a-z][a-z0-9-]{0,62}$/; +const SLUG_PATTERN = /^[a-z0-9][a-z0-9-]{0,62}$/; +const HOSTNAME_PATTERN = + /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/; +const IPV4_PATTERN = + /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/; +const SHA_PATTERN = /^[0-9a-f]{7,64}$/; +const HOST_STATES = new Set([ + "provisioning", + "ready", + "resizing", + "destroying", + "failed", +]); +const RELEASE_STATES = new Set(["none_yet", "live", "failed"]); +const DOMAIN_STATES = new Set(["checking", "connected"]); +const RECORD_STATUSES = new Set(["unchecked", "ok", "missing", "wrong"]); +const EMAIL_STATES = new Set([ + "waiting_for_domain", + "verifying", + "ready", + "paused", +]); +const PAUSED_REASONS = new Set(["allowance", "reputation", "operator"]); +const BACKUP_STATES = new Set(["ok", "incomplete", "stale"]); +const RESTORE_CHECK_STATES = new Set(["passed", "failed"]); +const TIMESTAMP_PATTERN = + /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/; +const DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/; + +/** + * @typedef {object} HostRecord + * @property {"provisioning" | "ready" | "resizing" | "destroying" | "failed"} state + * @property {string} region + * @property {string} size + * @property {string | null} ipv4 + * @property {string} ssh_user + * @property {string} ssh_key_fingerprint + * @property {string} created_at + * @property {string | null} ready_at + * @property {{code: string, detail: string} | null} failure + * @property {{state: "none_yet" | "live" | "failed", version: string | null, changed_at: string | null}} release + */ + +/** + * @typedef {object} DomainRow + * @property {string} purpose + * @property {string} type + * @property {string} name + * @property {string} value + * @property {boolean} required + * @property {"unchecked" | "ok" | "missing" | "wrong"} status + * @property {string[]} found + */ + +/** + * @typedef {object} DomainRecord + * @property {string} hostname + * @property {"checking" | "connected"} state + * @property {string | null} checked_at + * @property {DomainRow[]} records + */ + +/** + * @typedef {object} SmtpRecord + * @property {string} host + * @property {number} port + * @property {string} username + * @property {Record} headers + */ + +export class HostRejectedError extends Error { + /** + * @param {number} status + * @param {Record} response + */ + constructor(status, response) { + super("First Draft rejected the hosting request."); + this.status = status; + this.response = response; + /** @type {unknown} The host a 409 host_exists names beside its problem. */ + this.existingHost = undefined; + } +} + +export class HostUnavailableError extends Error { + /** + * @param {number | undefined} status + * @param {Record | null} [response] + */ + constructor(status, response = null) { + super("The hosting request could not be completed."); + this.status = status; + this.response = response; + } +} + +export class HostResponseInvalidError extends Error { + /** @param {number} status */ + constructor(status) { + super("The hosting response is invalid."); + this.status = status; + } +} + +/** @param {unknown} value @returns {value is string} */ +export function isEnvironmentName(value) { + return typeof value === "string" && ENVIRONMENT_NAME_PATTERN.test(value); +} + +/** @param {unknown} value @returns {value is string} */ +export function isSlug(value) { + return typeof value === "string" && SLUG_PATTERN.test(value); +} + +/** @param {unknown} value @returns {value is string} */ +export function isHostname(value) { + return typeof value === "string" && HOSTNAME_PATTERN.test(value); +} + +/** + * The sslip.io name that resolves to a Droplet's IPv4, which serves the app + * until the owner connects a domain. + * + * @param {string} ipv4 + */ +export function defaultHostname(ipv4) { + return `${ipv4.replaceAll(".", "-")}.sslip.io`; +} + +/** + * @typedef {object} HostContext + * @property {string} apiUrl + * @property {string} projectId + * @property {string} environment + * @property {typeof globalThis.fetch} fetchFunction + * @property {(timeoutMs: number) => AbortSignal} [createRequestSignal] + */ + +/** + * Asks First Draft to create the Environment's Droplet with the owner's SSH + * public key. An Environment that already has a host answers 409 + * `host_exists` with that host, which is returned with `existing: true`. + * + * @param {HostContext & {region?: string, size?: string, sshPublicKey: string}} options + */ +export async function createHost({ region, size, sshPublicKey, ...context }) { + const host = { + ...(region === undefined ? {} : { region }), + ...(size === undefined ? {} : { size }), + ssh_public_key: sshPublicKey, + }; + try { + const { status, body } = await request(context, SERVICE_ROUTES.createHost, { + json: { host }, + expected: 202, + }); + return { existing: false, ...hostResponse(status, body, context) }; + } catch (error) { + if ( + error instanceof HostRejectedError && + error.status === 409 && + error.response.code === "host_exists" && + isHost(error.existingHost) + ) { + return { + existing: true, + environment: environmentOf(context), + host: copyHost(error.existingHost), + }; + } + throw error; + } +} + +/** @param {HostContext} context */ +export async function readHost(context) { + const { status, body } = await request(context, SERVICE_ROUTES.readHost); + return hostResponse(status, body, context); +} + +/** @param {HostContext & {size: string}} options */ +export async function resizeHost({ size, ...context }) { + const { status, body } = await request(context, SERVICE_ROUTES.resizeHost, { + json: { host: { size } }, + expected: 202, + }); + return hostResponse(status, body, context); +} + +/** @param {HostContext & {confirm: string}} options */ +export async function destroyHost({ confirm, ...context }) { + const { status, body } = await request(context, SERVICE_ROUTES.destroyHost, { + json: { confirm }, + expected: 202, + }); + return hostResponse(status, body, context); +} + +/** @param {HostContext} context */ +export async function readBackups(context) { + const { status, body } = await request(context, SERVICE_ROUTES.readBackups); + if (!isRecord(body) || !isBackups(body.backups)) { + throw new HostResponseInvalidError(status); + } + assertEnvironment(status, body, context); + return { + environment: environmentOf(context), + backups: copyBackups(body.backups), + }; +} + +/** @param {HostContext & {hostname: string}} options */ +export async function connectDomain({ hostname, ...context }) { + const { status, body } = await request( + context, + SERVICE_ROUTES.connectDomain, + { json: { domain: { hostname } } }, + ); + const response = domainResponse(status, body, context); + if (response.domain?.hostname !== hostname) { + throw new HostResponseInvalidError(status); + } + return response; +} + +/** @param {HostContext} context */ +export async function readDomain(context) { + const { status, body } = await request(context, SERVICE_ROUTES.readDomain); + return domainResponse(status, body, context); +} + +/** @param {HostContext} context */ +export async function checkDomain(context) { + const { status, body } = await request(context, SERVICE_ROUTES.checkDomain); + return domainResponse(status, body, context); +} + +/** @param {HostContext} context */ +export async function disconnectDomain(context) { + const { status, body } = await request( + context, + SERVICE_ROUTES.disconnectDomain, + ); + const response = domainResponse(status, body, context, { nullable: true }); + if (response.domain !== null) throw new HostResponseInvalidError(status); + return response; +} + +/** @param {HostContext} context */ +export async function readEmail(context) { + const { status, body } = await request(context, SERVICE_ROUTES.readEmail); + if (!isRecord(body) || !isEmail(body.email)) { + throw new HostResponseInvalidError(status); + } + assertEnvironment(status, body, context); + return { + environment: environmentOf(context), + email: copyEmail(body.email), + }; +} + +/** + * Asks First Draft for a new SMTP credential, which revokes the earlier one. + * The password is returned once; the caller stores it and never prints it. + * + * @param {HostContext} context + */ +export async function createSmtpCredentials(context) { + const { status, body } = await request( + context, + SERVICE_ROUTES.createSmtpCredentials, + { expected: 201 }, + ); + if ( + !isRecord(body) || + !isSmtp(body.smtp) || + typeof body.smtp.password !== "string" || + body.smtp.password.length === 0 + ) { + throw new HostResponseInvalidError(status); + } + assertEnvironment(status, body, context); + return { + environment: environmentOf(context), + smtp: copySmtp(body.smtp), + password: body.smtp.password, + }; +} + +/** + * @param {HostContext} context + * @param {{method: string, path: string}} route + * @param {{json?: unknown, expected?: number}} [options] + */ +async function request( + { + apiUrl, + projectId, + environment, + fetchFunction, + createRequestSignal = (timeoutMs) => AbortSignal.timeout(timeoutMs), + }, + route, + { json, expected = 200 } = {}, +) { + const endpoint = serviceEndpoint(route, apiUrl, { + project_id: projectId, + environment_name: environment, + }); + let response; + let body; + try { + response = await sendRequest(fetchFunction, endpoint, { + headers: { + Accept: "application/json, application/problem+json", + ...(json === undefined ? {} : { "Content-Type": "application/json" }), + }, + ...(json === undefined ? {} : { body: JSON.stringify(json) }), + redirect: "error", + signal: createRequestSignal(REQUEST_TIMEOUT_MS), + }); + body = await readResponseBody(response); + } catch (error) { + if (error instanceof FirstDraftNetworkError) { + throw new HostUnavailableError(error.status); + } + if (error instanceof FirstDraftProtocolError) { + throw error.status >= 200 && error.status < 300 + ? new HostResponseInvalidError(error.status) + : new HostUnavailableError(error.status); + } + throw error; + } + + if (response.status !== expected) { + if (response.ok) throw new HostResponseInvalidError(response.status); + + const problem = safeProblem(response, body); + if (problem !== null && response.status !== 408 && response.status < 500) { + const rejected = new HostRejectedError(response.status, problem); + if (isRecord(body)) rejected.existingHost = body.host; + throw rejected; + } + throw new HostUnavailableError(response.status, problem); + } + + if (responseMediaType(response) !== "application/json") { + throw new HostResponseInvalidError(response.status); + } + + return { status: response.status, body }; +} + +/** + * @param {number} status + * @param {unknown} body + * @param {HostContext} context + */ +function hostResponse(status, body, context) { + if (!isRecord(body) || !isHost(body.host)) { + throw new HostResponseInvalidError(status); + } + assertEnvironment(status, body, context); + return { environment: environmentOf(context), host: copyHost(body.host) }; +} + +/** + * @param {number} status + * @param {unknown} body + * @param {HostContext} context + * @param {{nullable?: boolean}} [options] + */ +function domainResponse(status, body, context, { nullable = false } = {}) { + if ( + !isRecord(body) || + !(isDomain(body.domain) || (nullable && body.domain === null)) + ) { + throw new HostResponseInvalidError(status); + } + assertEnvironment(status, body, context); + return { + environment: environmentOf(context), + domain: body.domain === null ? null : copyDomain(body.domain), + }; +} + +/** + * @param {number} status + * @param {Record} body + * @param {HostContext} context + */ +function assertEnvironment(status, body, { projectId, environment }) { + const value = body.environment; + if ( + !isRecord(value) || + value.project_id !== projectId || + value.name !== environment + ) { + throw new HostResponseInvalidError(status); + } +} + +/** @param {HostContext} context */ +function environmentOf({ projectId, environment }) { + return { project_id: projectId, name: environment }; +} + +/** @param {unknown} value @returns {value is Record} */ +function isHost(value) { + if (!isRecord(value)) return false; + + const failure = value.failure; + const release = value.release; + return ( + typeof value.state === "string" && + HOST_STATES.has(value.state) && + isSlug(value.region) && + isSlug(value.size) && + (value.ipv4 === null || + (typeof value.ipv4 === "string" && IPV4_PATTERN.test(value.ipv4))) && + (value.state !== "ready" || value.ipv4 !== null) && + typeof value.ssh_user === "string" && + /^[a-z_][a-z0-9_-]{0,31}$/.test(value.ssh_user) && + typeof value.ssh_key_fingerprint === "string" && + value.ssh_key_fingerprint.startsWith("SHA256:") && + isTimestamp(value.created_at) && + (value.ready_at === null || isTimestamp(value.ready_at)) && + (value.state === "failed" + ? isRecord(failure) && + typeof failure.code === "string" && + typeof failure.detail === "string" + : failure === null) && + isRecord(release) && + typeof release.state === "string" && + RELEASE_STATES.has(release.state) && + (release.version === null || + (typeof release.version === "string" && + SHA_PATTERN.test(release.version))) && + (release.state !== "live" || release.version !== null) && + (release.changed_at === null || isTimestamp(release.changed_at)) + ); +} + +/** + * @param {Record} host + * @returns {HostRecord} + */ +function copyHost(host) { + const failure = /** @type {Record | null} */ (host.failure); + const release = /** @type {Record} */ (host.release); + return /** @type {HostRecord} */ ({ + state: host.state, + region: host.region, + size: host.size, + ipv4: host.ipv4, + ssh_user: host.ssh_user, + ssh_key_fingerprint: host.ssh_key_fingerprint, + created_at: host.created_at, + ready_at: host.ready_at, + failure: + failure === null ? null : { code: failure.code, detail: failure.detail }, + release: { + state: release.state, + version: release.version, + changed_at: release.changed_at, + }, + }); +} + +/** @param {unknown} value @returns {value is Record} */ +function isDomain(value) { + return ( + isRecord(value) && + isHostname(value.hostname) && + typeof value.state === "string" && + DOMAIN_STATES.has(value.state) && + (value.checked_at === null || isTimestamp(value.checked_at)) && + Array.isArray(value.records) && + value.records.every(isRecordRow) + ); +} + +/** @param {unknown} value */ +function isRecordRow(value) { + return ( + isRecord(value) && + typeof value.purpose === "string" && + typeof value.type === "string" && + /^[A-Z]{1,10}$/.test(value.type) && + typeof value.name === "string" && + typeof value.value === "string" && + typeof value.required === "boolean" && + typeof value.status === "string" && + RECORD_STATUSES.has(value.status) && + Array.isArray(value.found) && + value.found.every((found) => typeof found === "string") + ); +} + +/** + * @param {Record} domain + * @returns {DomainRecord} + */ +function copyDomain(domain) { + return /** @type {DomainRecord} */ ({ + hostname: domain.hostname, + state: domain.state, + checked_at: domain.checked_at, + records: /** @type {Record[]} */ (domain.records).map( + (row) => ({ + purpose: row.purpose, + type: row.type, + name: row.name, + value: row.value, + required: row.required, + status: row.status, + found: [.../** @type {string[]} */ (row.found)], + }), + ), + }); +} + +/** @param {unknown} value @returns {value is Record} */ +function isEmail(value) { + if (!isRecord(value)) return false; + + const allowance = value.allowance; + return ( + typeof value.state === "string" && + EMAIL_STATES.has(value.state) && + (value.sending_domain === null || isHostname(value.sending_domain)) && + (value.paused_reason === null || + (typeof value.paused_reason === "string" && + PAUSED_REASONS.has(value.paused_reason))) && + (value.state === "paused") === (value.paused_reason !== null) && + isRecord(allowance) && + isCount(allowance.limit) && + isCount(allowance.used) && + typeof allowance.period_start === "string" && + DATE_PATTERN.test(allowance.period_start) && + isTimestamp(allowance.resets_at) && + (value.smtp === null || isSmtp(value.smtp)) + ); +} + +/** @param {Record} email */ +function copyEmail(email) { + const allowance = /** @type {Record} */ (email.allowance); + return { + state: email.state, + sending_domain: email.sending_domain, + paused_reason: email.paused_reason, + allowance: { + limit: allowance.limit, + used: allowance.used, + period_start: allowance.period_start, + resets_at: allowance.resets_at, + }, + smtp: + email.smtp === null + ? null + : copySmtp(/** @type {Record} */ (email.smtp)), + }; +} + +/** @param {unknown} value @returns {value is Record} */ +function isSmtp(value) { + return ( + isRecord(value) && + isHostname(value.host) && + Number.isSafeInteger(value.port) && + Number(value.port) > 0 && + Number(value.port) < 65_536 && + typeof value.username === "string" && + value.username.length > 0 && + isRecord(value.headers) && + Object.entries(value.headers).every( + ([name, header]) => + /^[A-Za-z0-9-]{1,64}$/.test(name) && typeof header === "string", + ) + ); +} + +/** + * @param {Record} smtp + * @returns {SmtpRecord} + */ +function copySmtp(smtp) { + return /** @type {SmtpRecord} */ ({ + host: smtp.host, + port: smtp.port, + username: smtp.username, + headers: { .../** @type {Record} */ (smtp.headers) }, + }); +} + +/** @param {unknown} value @returns {value is Record} */ +function isBackups(value) { + if (!isRecord(value)) return false; + + const latest = value.latest; + const restore = value.latest_restore_check; + return ( + typeof value.schedule === "string" && + isCount(value.retention_days) && + (latest === null || + (isRecord(latest) && + isTimestamp(latest.taken_at) && + isCount(latest.database_bytes) && + isCount(latest.uploads_bytes) && + typeof latest.state === "string" && + BACKUP_STATES.has(latest.state))) && + (value.checked_at === null || isTimestamp(value.checked_at)) && + (restore === null || + (isRecord(restore) && + typeof restore.state === "string" && + RESTORE_CHECK_STATES.has(restore.state) && + isTimestamp(restore.checked_at) && + isTimestamp(restore.backup_taken_at) && + typeof restore.detail === "string")) + ); +} + +/** @param {Record} backups */ +function copyBackups(backups) { + const latest = /** @type {Record | null} */ (backups.latest); + const restore = /** @type {Record | null} */ ( + backups.latest_restore_check + ); + return { + schedule: backups.schedule, + retention_days: backups.retention_days, + latest: + latest === null + ? null + : { + taken_at: latest.taken_at, + database_bytes: latest.database_bytes, + uploads_bytes: latest.uploads_bytes, + state: latest.state, + }, + checked_at: backups.checked_at, + latest_restore_check: + restore === null + ? null + : { + state: restore.state, + checked_at: restore.checked_at, + backup_taken_at: restore.backup_taken_at, + detail: restore.detail, + }, + }; +} + +/** @param {Response} response @param {unknown} body */ +function safeProblem(response, body) { + if (!isRecord(body) || !isProblemBody(response, body)) return null; + + return { + ...(body.type === "about:blank" ? { type: body.type } : {}), + title: body.title, + status: body.status, + code: body.code, + detail: body.detail, + }; +} + +/** @param {unknown} value */ +function isCount(value) { + return Number.isSafeInteger(value) && Number(value) >= 0; +} + +/** @param {unknown} value */ +function isTimestamp(value) { + return ( + typeof value === "string" && + TIMESTAMP_PATTERN.test(value) && + !Number.isNaN(Date.parse(value)) + ); +} + +/** @param {unknown} value @returns {value is Record} */ +function isRecord(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} diff --git a/src/host-tools.js b/src/host-tools.js new file mode 100644 index 0000000..22cea8f --- /dev/null +++ b/src/host-tools.js @@ -0,0 +1,359 @@ +import { createHash } from "node:crypto"; +import { spawnSync } from "node:child_process"; +import { existsSync, mkdirSync, readFileSync, rmSync, statSync } from "node:fs"; +import path from "node:path"; + +import { credentialsPath } from "./credentials.js"; + +const MAX_OUTPUT_BYTES = 4 * 1024 * 1024; +const TOOL_TIMEOUT_MS = 60_000; +const KEY_FILE = "id_ed25519"; +const MESSAGE_LIMIT = 300; + +/** + * @typedef {object} ToolResult + * @property {number} status + * @property {string} stdout + * @property {string} stderr + */ + +/** + * Runs one program on the owner's machine. Tests replace it. + * + * @typedef {(command: string, args: readonly string[], options: {cwd: string, input?: string, timeoutMs?: number}) => ToolResult} ToolRunner + */ + +export class ToolUnavailableError extends Error { + /** @param {string} tool @param {{cause?: unknown}} [options] */ + constructor(tool, options = {}) { + super(`${tool} is unavailable.`, options); + this.tool = tool; + } +} + +export class GithubCommandError extends Error { + /** @param {string} command @param {ToolResult} result */ + constructor(command, result) { + super("A gh command failed."); + this.command = command; + this.exitStatus = result.status; + this.reason = firstLine(result.stderr) || firstLine(result.stdout); + } +} + +export class SshCommandError extends Error { + /** @param {ToolResult} result */ + constructor(result) { + super("An ssh command failed."); + this.exitStatus = result.status; + this.reason = firstLine(result.stderr); + } +} + +/** @type {ToolRunner} */ +export function runTool(command, args, { cwd, input, timeoutMs }) { + const result = spawnSync(command, [...args], { + cwd, + input, + encoding: "utf8", + maxBuffer: MAX_OUTPUT_BYTES, + timeout: timeoutMs ?? TOOL_TIMEOUT_MS, + // Keep gh from opening a pager or prompting. + env: { + ...process.env, + GH_PROMPT_DISABLED: "1", + GH_PAGER: "", + NO_COLOR: "1", + }, + }); + if (result.error !== undefined || result.status === null) { + throw new ToolUnavailableError(command, { cause: result.error }); + } + return { + status: result.status, + stdout: result.stdout ?? "", + stderr: result.stderr ?? "", + }; +} + +/** + * The GitHub side of a host, through the owner's own `gh` login. + * + * @param {ToolRunner} run + * @param {string} cwd + */ +export function github(run, cwd) { + /** @param {string} name @param {readonly string[]} args @param {string} [input] */ + const gh = (name, args, input) => { + const result = run("gh", args, { cwd, input }); + if (result.status !== 0) throw new GithubCommandError(`gh ${name}`, result); + return result.stdout; + }; + /** @param {string} name @param {readonly string[]} args */ + const json = (name, args) => { + const output = gh(name, args); + try { + return JSON.parse(output); + } catch { + throw new GithubCommandError(`gh ${name}`, { + status: 0, + stdout: "", + stderr: "gh printed output that is not JSON.", + }); + } + }; + + return { + /** @returns {{repository: string, defaultBranch: string}} */ + repository() { + const value = json("repo view", [ + "repo", + "view", + "--json", + "nameWithOwner,defaultBranchRef", + ]); + const repository = value?.nameWithOwner; + const defaultBranch = value?.defaultBranchRef?.name; + if (typeof repository !== "string" || typeof defaultBranch !== "string") { + throw new GithubCommandError("gh repo view", { + status: 0, + stdout: "", + stderr: "gh did not name the repository and its default branch.", + }); + } + return { repository, defaultBranch }; + }, + /** @returns {string[]} */ + secretNames() { + const value = json("secret list", ["secret", "list", "--json", "name"]); + return Array.isArray(value) + ? value + .map((secret) => secret?.name) + .filter((name) => typeof name === "string") + : []; + }, + /** @returns {Map} */ + variables() { + const value = json("variable list", [ + "variable", + "list", + "--json", + "name,value", + ]); + return new Map( + Array.isArray(value) + ? value + .filter( + (variable) => + typeof variable?.name === "string" && + typeof variable?.value === "string", + ) + .map((variable) => [variable.name, variable.value]) + : [], + ); + }, + // The value goes through standard input, so it never appears in an + // argument list that other processes on the machine can read. + /** @param {string} name @param {string} value */ + setSecret(name, value) { + gh("secret set", ["secret", "set", name], value); + }, + /** @param {string} name */ + deleteSecret(name) { + gh("secret delete", ["secret", "delete", name]); + }, + /** @param {string} name @param {string} value */ + setVariable(name, value) { + gh("variable set", ["variable", "set", name, "--body", value]); + }, + /** @param {string} name */ + deleteVariable(name) { + gh("variable delete", ["variable", "delete", name]); + }, + /** + * The newest CI run from a push to `branch`, with its jobs. + * + * @param {string} branch + * @returns {{id: number, url: string, head_sha: string, status: string, conclusion: string, jobs: {name: string, status: string, conclusion: string}[]} | null} + */ + latestRun(branch) { + const runs = json("run list", [ + "run", + "list", + "--workflow", + "ci.yml", + "--branch", + branch, + "--event", + "push", + "--limit", + "1", + "--json", + "databaseId,headSha,status,conclusion,url", + ]); + const latest = Array.isArray(runs) ? runs[0] : undefined; + if (latest === undefined) return null; + if (!Number.isSafeInteger(latest?.databaseId)) { + throw new GithubCommandError("gh run list", { + status: 0, + stdout: "", + stderr: "gh named a run without an id.", + }); + } + const view = json("run view", [ + "run", + "view", + String(latest.databaseId), + "--json", + "jobs", + ]); + const jobs = Array.isArray(view?.jobs) ? view.jobs : []; + return { + id: latest.databaseId, + url: String(latest.url ?? ""), + head_sha: String(latest.headSha ?? ""), + status: String(latest.status ?? ""), + conclusion: String(latest.conclusion ?? ""), + jobs: jobs.map((/** @type {Record} */ job) => ({ + name: String(job?.name ?? ""), + status: String(job?.status ?? ""), + conclusion: String(job?.conclusion ?? ""), + })), + }; + }, + }; +} + +/** + * The directory that holds the owner's SSH key for one host, beside the CLI's + * saved credentials. + * + * @param {import("./credentials.js").CredentialStore} store + * @param {string} projectId + * @param {string} environment + */ +export function hostKeyDirectory(store, projectId, environment) { + return path.join( + path.dirname(credentialsPath(store)), + "hosts", + projectId, + environment, + ); +} + +/** + * The owner's key for one host: its private key path, public line, and + * fingerprint, or null when this machine has none. + * + * @param {string} directory + */ +export function readHostKey(directory) { + const privateKey = path.join(directory, KEY_FILE); + const publicKey = `${privateKey}.pub`; + if (!existsSync(privateKey) || !existsSync(publicKey)) return null; + if (!statSync(privateKey).isFile()) return null; + + const line = readFileSync(publicKey, "utf8").trim(); + return { + privateKey, + knownHosts: path.join(directory, "known_hosts"), + publicKey: line, + fingerprint: fingerprint(line), + }; +} + +/** @param {string} directory */ +export function readPrivateKey(directory) { + return readFileSync(path.join(directory, KEY_FILE), "utf8"); +} + +/** + * Generates an Ed25519 key pair with no passphrase, readable only by the + * owner, so `ssh` and the deploy job can use it unattended. + * + * @param {ToolRunner} run + * @param {string} directory + * @param {string} comment + */ +export function generateHostKey(run, directory, comment) { + mkdirSync(directory, { recursive: true, mode: 0o700 }); + const result = run( + "ssh-keygen", + [ + "-q", + "-t", + "ed25519", + "-N", + "", + "-C", + comment, + "-f", + path.join(directory, KEY_FILE), + ], + { cwd: directory }, + ); + if (result.status !== 0) throw new SshCommandError(result); + + const key = readHostKey(directory); + if (key === null) throw new ToolUnavailableError("ssh-keygen"); + return key; +} + +/** @param {string} directory */ +export function removeHostKey(directory) { + rmSync(directory, { recursive: true, force: true }); +} + +/** + * Runs one command on the host as its SSH user, with only this host's key and + * known_hosts file. The first connection records the host's key; later ones + * refuse a different key. + * + * @param {ToolRunner} run + * @param {{privateKey: string, knownHosts: string}} key + * @param {{user: string, ipv4: string}} host + * @param {string} remoteCommand + * @param {string} cwd + */ +export function ssh(run, key, host, remoteCommand, cwd) { + return run( + "ssh", + [ + "-i", + key.privateKey, + "-o", + "IdentitiesOnly=yes", + "-o", + "BatchMode=yes", + "-o", + "StrictHostKeyChecking=accept-new", + "-o", + `UserKnownHostsFile=${key.knownHosts}`, + "-o", + "ConnectTimeout=10", + `${host.user}@${host.ipv4}`, + remoteCommand, + ], + { cwd, timeoutMs: 30_000 }, + ); +} + +/** + * OpenSSH's SHA256 fingerprint of a public key line. + * + * @param {string} line + */ +export function fingerprint(line) { + const blob = line.split(/\s+/)[1] ?? ""; + const digest = createHash("sha256") + .update(Buffer.from(blob, "base64")) + .digest("base64") + .replace(/=+$/, ""); + return `SHA256:${digest}`; +} + +/** @param {string} text */ +function firstLine(text) { + const line = text.split("\n").find((candidate) => candidate.trim() !== ""); + return (line ?? "").trim().slice(0, MESSAGE_LIMIT); +} diff --git a/test/api-environments.test.js b/test/api-environments.test.js index 07cd5ee..bb188cc 100644 --- a/test/api-environments.test.js +++ b/test/api-environments.test.js @@ -47,6 +47,7 @@ const REMOTE_COMMANDS = [ "--actual", "Anyone edits", ], + ["host", "email"], ]; test("production and staging credentials follow the pinned origin on every remote command", async (context) => { diff --git a/test/cli.test.js b/test/cli.test.js index 39c78ef..9e6c8fd 100644 --- a/test/cli.test.js +++ b/test/cli.test.js @@ -18,6 +18,7 @@ Commands: account Show whether this account sends reports compilation Inspect, download, and cancel Compilations generate Generate local values + host Create and operate the application's First Draft host login Log in to First Draft and save a token logout Revoke and remove the saved token note Send a note about a problem with First Draft diff --git a/test/host.test.js b/test/host.test.js new file mode 100644 index 0000000..062600a --- /dev/null +++ b/test/host.test.js @@ -0,0 +1,901 @@ +import assert from "node:assert/strict"; +import { + existsSync, + 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 { ToolUnavailableError, fingerprint } from "../src/host-tools.js"; + +const PROJECT_ID = "01900000-0000-7000-8000-000000009001"; +const API_TOKEN = `fd_canary${"h".repeat(37)}`; +const API_URL = "https://api.example.test"; +const BASE = `/v1/projects/${PROJECT_ID}/environments/production/host`; +const PUBLIC_KEY = + "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGNhbmFyeS1ub3QtYS1yZWFsLWtleS0wMDAwMDAw firstdraft-test"; +const PRIVATE_KEY = "-----BEGIN OPENSSH PRIVATE KEY-----\ncanary-private\n"; +const IPV4 = "203.0.113.10"; +const SSLIP = "203-0-113-10.sslip.io"; +const CREATED_AT = "2026-11-24T12:00:00Z"; +const ENVIRONMENT = { project_id: PROJECT_ID, name: "production" }; +const WORKFLOW = `name: CI +jobs: + ci: + runs-on: ubuntu-latest + deploy: + needs: [ci] +`; + +test("host help lists its commands, and each command has help", async (context) => { + const cwd = appDirectory(context); + const group = await invoke(["host", "--help"], { cwd }); + assert.equal(group.status, 0); + for (const command of [ + "create", + "status", + "resize", + "destroy", + "domain", + "email", + ]) { + assert.match(group.stdout, new RegExp(`^ {2}${command} `, "m")); + const help = await invoke(["host", command, "--help"], { cwd }); + assert.equal(help.status, 0); + assert.match(help.stdout, new RegExp(`firstdraft host ${command}`)); + } + + const root = await invoke(["--help"], { cwd }); + assert.match(root.stdout, /^ {2}host {9}Create and operate/m); + + const bare = await invoke(["host"], { cwd }); + assert.deepEqual(bare, group); +}); + +test("invalid host arguments exit 2 before any request", async (context) => { + const cwd = appDirectory(context); + for (const argv of [ + ["host", "unknown"], + ["host", "status", "--environment", "Production"], + ["host", "status", "extra"], + ["host", "status", "--wait", "--wait"], + ["host", "resize", "--yes"], + ["host", "create", "--size", "../x"], + ["host", "domain", "connect"], + ["host", "domain", "connect", "not a host"], + ["host", "domain", "renew"], + ["host", "email", "rotate"], + ]) { + const result = await invoke(argv, { cwd }); + assertHandledFailure(result, "invalid_arguments", 2); + } +}); + +test("resize and destroy need the owner's confirmation before any request", async (context) => { + const cwd = appDirectory(context); + for (const argv of [ + ["host", "resize", "--size", "s-1vcpu-2gb"], + ["host", "destroy"], + ["host", "destroy", "--confirm", "staging"], + ]) { + const result = await invoke(argv, { cwd }); + assertHandledFailure(result, "confirmation_required", 2); + assert.match(JSON.parse(result.stderr).detail, /Ask the owner/); + } +}); + +test("create refuses an app without Kamal deploy files", async (context) => { + const cwd = appDirectory(context, { deployFiles: false }); + const result = await invoke(["host", "create"], { cwd }); + assertHandledFailure(result, "deploy_files_missing"); + assert.deepEqual(JSON.parse(result.stderr).missing, [ + "config/deploy.yml", + ".github/workflows/ci.yml", + ]); + + const noJob = appDirectory(context, { workflow: "jobs:\n ci:\n" }); + const second = await invoke(["host", "create"], { cwd: noJob }); + assertHandledFailure(second, "deploy_files_missing"); + assert.deepEqual(JSON.parse(second.stderr).missing, [ + ".github/workflows/ci.yml job deploy", + ]); +}); + +test("create generates the key, creates the host, stores secrets, and connects the repository", async (context) => { + const cwd = appDirectory(context); + const config = configDirectory(context); + const service = routes({ + [`GET ${BASE}`]: [ + problem(404, "host_not_found"), + json({ + environment: ENVIRONMENT, + host: host({ state: "ready", ipv4: IPV4 }), + }), + ], + [`POST ${BASE}`]: [json({ environment: ENVIRONMENT, host: host() }, 202)], + }); + const tools = toolRunner({ + variables: [], + secrets: [], + run: { + conclusion: "failure", + jobs: [job("ci", "failure"), job("deploy", "skipped")], + }, + }); + const result = await invoke(["host", "create"], { + cwd, + env: { XDG_CONFIG_HOME: config }, + fetchFunction: service.fetch, + hostTools: tools.run, + }); + + assert.equal(result.status, 0, result.stderr); + const output = JSON.parse(result.stdout); + assert.equal(output.step, "connected"); + assert.equal(output.host.state, "ready"); + assert.equal(output.url, `https://${SSLIP}`); + assert.deepEqual(output.github, { + repository: "owner/app", + secrets: ["SSH_PRIVATE_KEY", "SECRET_KEY_BASE", "POSTGRES_PASSWORD"], + variables: ["DEPLOY_HOST", "APP_HOST"], + }); + assert.deepEqual(output.checks.failed_jobs, ["ci"]); + assert.match(output.next, /Nothing is deployed: CI failed on main \(ci\)/); + assert.match(output.next, /Behavior to write/); + + const create = service.calls.find((call) => call.method === "POST"); + assert.deepEqual(JSON.parse(String(create?.body)), { + host: { ssh_public_key: PUBLIC_KEY }, + }); + assert.equal(create?.authorization, `Bearer ${API_TOKEN}`); + + const secretCalls = tools.calls.filter( + (call) => + call.command === "gh" && + call.args[0] === "secret" && + call.args[1] === "set", + ); + assert.deepEqual( + secretCalls.map((call) => call.args), + [ + ["secret", "set", "SSH_PRIVATE_KEY"], + ["secret", "set", "SECRET_KEY_BASE"], + ["secret", "set", "POSTGRES_PASSWORD"], + ], + ); + assert.equal(secretCalls[0]?.input, PRIVATE_KEY); + assert.match(String(secretCalls[1]?.input), /^[0-9a-f]{128}$/); + assert.match(String(secretCalls[2]?.input), /^[0-9a-f]{48}$/); + assert.deepEqual( + tools.calls + .filter((call) => call.args[0] === "variable" && call.args[1] === "set") + .map((call) => call.args), + [ + ["variable", "set", "APP_HOST", "--body", SSLIP], + ["variable", "set", "DEPLOY_HOST", "--body", IPV4], + ], + ); + const sshCall = tools.calls.find((call) => call.command === "ssh"); + assert.equal(sshCall?.args.at(-2), `root@${IPV4}`); + assert.equal(sshCall?.args.at(-1), "cloud-init status"); + assert.ok(sshCall?.args.includes("StrictHostKeyChecking=accept-new")); + + for (const secret of secretCalls) { + assert.ok(!result.stdout.includes(String(secret.input))); + assert.ok(!result.stderr.includes(String(secret.input))); + } + assertNoSecrets(result); +}); + +test("create resumes without a second host and keeps existing generated secrets", async (context) => { + const cwd = appDirectory(context); + const config = configDirectory(context, { key: true }); + const service = routes({ + [`GET ${BASE}`]: [ + json({ + environment: ENVIRONMENT, + host: host({ state: "ready", ipv4: IPV4 }), + }), + ], + }); + const tools = toolRunner({ + variables: [ + { name: "DEPLOY_HOST", value: IPV4 }, + { name: "APP_HOST", value: SSLIP }, + ], + secrets: ["SSH_PRIVATE_KEY", "SECRET_KEY_BASE", "POSTGRES_PASSWORD"], + run: null, + }); + const result = await invoke(["host", "create"], { + cwd, + env: { XDG_CONFIG_HOME: config }, + fetchFunction: service.fetch, + hostTools: tools.run, + }); + + assert.equal(result.status, 0, result.stderr); + const output = JSON.parse(result.stdout); + assert.equal(output.step, "connected"); + assert.match(output.next, /Push to main/); + assert.equal( + service.calls.filter((call) => call.method === "POST").length, + 0, + ); + assert.deepEqual( + tools.calls + .filter((call) => call.args[1] === "set") + .map((call) => call.args.slice(0, 3)), + [["secret", "set", "SSH_PRIVATE_KEY"]], + ); + assert.equal(tools.calls.filter((call) => call.command === "ssh").length, 0); + assert.equal( + tools.calls.filter((call) => call.command === "ssh-keygen").length, + 0, + ); +}); + +test("create stops at the wait limit while the Droplet sets itself up", async (context) => { + const cwd = appDirectory(context); + const config = configDirectory(context, { key: true }); + let clock = 0; + const service = routes({ + [`GET ${BASE}`]: [ + json({ + environment: ENVIRONMENT, + host: host({ state: "ready", ipv4: IPV4 }), + }), + ], + }); + const tools = toolRunner({ + variables: [], + secrets: [], + run: null, + cloudInit: "status: running", + }); + const result = await invoke(["host", "create"], { + cwd, + env: { XDG_CONFIG_HOME: config }, + fetchFunction: service.fetch, + hostTools: tools.run, + hostNow: () => clock, + hostSleep: async (/** @type {number} */ ms) => { + clock += ms; + }, + }); + + assert.equal(result.status, 0, result.stderr); + const output = JSON.parse(result.stdout); + assert.equal(output.step, "setting_up"); + assert.equal(output.checks, null); + assert.match(output.next, /run 'firstdraft host create' again/); + assert.equal( + tools.calls.filter( + (call) => call.args[0] === "variable" && call.args[1] === "set", + ).length, + 0, + ); +}); + +test("create refuses a host whose key this computer does not hold", async (context) => { + const cwd = appDirectory(context); + const config = configDirectory(context); + const service = routes({ + [`GET ${BASE}`]: [ + json({ + environment: ENVIRONMENT, + host: host({ state: "ready", ipv4: IPV4 }), + }), + ], + }); + const tools = toolRunner({ variables: [], secrets: [], run: null }); + const result = await invoke(["host", "create"], { + cwd, + env: { XDG_CONFIG_HOME: config }, + fetchFunction: service.fetch, + hostTools: tools.run, + }); + + assertHandledFailure(result, "host_key_missing"); + assert.equal( + tools.calls.filter( + (call) => call.args[0] === "secret" && call.args[1] === "set", + ).length, + 0, + ); +}); + +test("create reports a missing gh and a failed gh command", async (context) => { + const cwd = appDirectory(context); + const missing = await invoke(["host", "create"], { + cwd, + env: { XDG_CONFIG_HOME: configDirectory(context) }, + hostTools: () => { + throw new ToolUnavailableError("gh"); + }, + }); + assertHandledFailure(missing, "tool_unavailable"); + assert.equal(JSON.parse(missing.stderr).tool, "gh"); + + const failed = await invoke(["host", "create"], { + cwd, + env: { XDG_CONFIG_HOME: configDirectory(context) }, + hostTools: () => ({ + status: 1, + stdout: "", + stderr: "To get started with GitHub CLI, please run: gh auth login\n", + }), + }); + assertHandledFailure(failed, "github_failed"); + assert.deepEqual( + { + command: JSON.parse(failed.stderr).command, + message: JSON.parse(failed.stderr).message, + }, + { + command: "gh repo view", + message: "To get started with GitHub CLI, please run: gh auth login", + }, + ); +}); + +test("status says when there is no host", async (context) => { + const service = routes({ [`GET ${BASE}`]: [problem(404, "host_not_found")] }); + const result = await invoke(["host", "status"], { + cwd: appDirectory(context), + fetchFunction: service.fetch, + hostTools: toolRunner({ variables: [], secrets: [], run: null }).run, + }); + + assert.equal(result.status, 0, result.stderr); + const output = JSON.parse(result.stdout); + assert.equal(output.host, null); + assert.match(output.next, /firstdraft host create/); +}); + +test("status tells a live app from a failed deploy and from red checks", async (context) => { + const cases = [ + { + release: { + state: "live", + version: "a".repeat(40), + changed_at: CREATED_AT, + }, + run: { + conclusion: "success", + jobs: [job("ci", "success"), job("deploy", "success")], + }, + up: 200, + next: /The app is live/, + }, + { + release: { state: "none_yet", version: null, changed_at: null }, + run: { + conclusion: "failure", + jobs: [job("ci", "success"), job("deploy", "failure")], + }, + up: 502, + next: /The last deploy failed \(https:\/\/github.com\/owner\/app\/actions\/runs\/7\)/, + }, + { + release: { state: "none_yet", version: null, changed_at: null }, + run: { + conclusion: "failure", + jobs: [ + job("ci", "failure"), + job("production-smoke", "success"), + job("deploy", "skipped"), + ], + }, + up: 404, + next: /CI failed on main \(ci\)/, + }, + { + release: { state: "none_yet", version: null, changed_at: null }, + run: { status: "in_progress", conclusion: "", jobs: [job("ci", "")] }, + up: 404, + next: /CI is running on main/, + }, + { + release: { state: "none_yet", version: null, changed_at: null }, + run: { + conclusion: "success", + jobs: [job("ci", "success"), job("deploy", "skipped")], + }, + up: 404, + next: /gh run rerun 7/, + }, + ]; + for (const scenario of cases) { + const service = routes({ + [`GET ${BASE}`]: [ + json({ + environment: ENVIRONMENT, + host: host({ state: "ready", ipv4: IPV4, release: scenario.release }), + }), + ], + [`GET ${BASE}/backups`]: [ + json({ environment: ENVIRONMENT, backups: backups() }), + ], + [`GET ${BASE}/domain`]: [problem(404, "domain_not_found")], + [`GET https://${SSLIP}/up`]: [new Response("", { status: scenario.up })], + }); + const result = await invoke(["host", "status"], { + cwd: appDirectory(context), + fetchFunction: service.fetch, + hostTools: toolRunner({ + variables: [ + { name: "DEPLOY_HOST", value: IPV4 }, + { name: "APP_HOST", value: SSLIP }, + ], + secrets: [], + run: scenario.run, + }).run, + }); + + assert.equal(result.status, 0, result.stderr); + const output = JSON.parse(result.stdout); + assert.match(output.next, scenario.next); + assert.equal(output.up.ok, scenario.up === 200); + assert.equal(output.domain, null); + assert.equal(output.backups.latest.state, "ok"); + const probe = service.calls.find((call) => call.url.endsWith("/up")); + assert.equal(probe?.authorization, null); + } +}); + +test("resize sends the size once confirmed", async (context) => { + const service = routes({ + [`PATCH ${BASE}`]: [ + json( + { + environment: ENVIRONMENT, + host: host({ state: "resizing", ipv4: IPV4, size: "s-1vcpu-2gb" }), + }, + 202, + ), + ], + }); + const result = await invoke( + ["host", "resize", "--size", "s-1vcpu-2gb", "--yes"], + { cwd: appDirectory(context), fetchFunction: service.fetch }, + ); + + assert.equal(result.status, 0, result.stderr); + assert.equal(JSON.parse(result.stdout).host.state, "resizing"); + assert.deepEqual(JSON.parse(String(service.calls[0]?.body)), { + host: { size: "s-1vcpu-2gb" }, + }); +}); + +test("destroy confirms the Environment, then cleans up GitHub and the local key", async (context) => { + const config = configDirectory(context, { key: true }); + const service = routes({ + [`DELETE ${BASE}`]: [ + json( + { + environment: ENVIRONMENT, + host: host({ state: "destroying", ipv4: IPV4 }), + }, + 202, + ), + ], + }); + const tools = toolRunner({ + variables: [ + { name: "DEPLOY_HOST", value: IPV4 }, + { name: "APP_HOST", value: SSLIP }, + ], + secrets: ["SSH_PRIVATE_KEY", "SECRET_KEY_BASE"], + run: null, + }); + const result = await invoke(["host", "destroy", "--confirm", "production"], { + cwd: appDirectory(context), + env: { XDG_CONFIG_HOME: config }, + fetchFunction: service.fetch, + hostTools: tools.run, + }); + + assert.equal(result.status, 0, result.stderr); + const output = JSON.parse(result.stdout); + assert.deepEqual(output.github, { + deleted: ["DEPLOY_HOST", "APP_HOST", "SSH_PRIVATE_KEY"], + left: [], + }); + assert.deepEqual(JSON.parse(String(service.calls[0]?.body)), { + confirm: "production", + }); + assert.equal( + existsSync( + path.join(config, "firstdraft", "hosts", PROJECT_ID, "production"), + ), + false, + ); +}); + +test("domain connect returns the records, and check switches APP_HOST once the app record is right", async (context) => { + const cwd = appDirectory(context); + const connected = routes({ + [`PUT ${BASE}/domain`]: [ + json({ environment: ENVIRONMENT, domain: domain("unchecked") }), + ], + }); + const connect = await invoke( + ["host", "domain", "connect", "app.example.com"], + { + cwd, + fetchFunction: connected.fetch, + }, + ); + assert.equal(connect.status, 0, connect.stderr); + assert.equal(JSON.parse(connect.stdout).domain.records[0].type, "A"); + assert.deepEqual(JSON.parse(String(connected.calls[0]?.body)), { + domain: { hostname: "app.example.com" }, + }); + + const checked = routes({ + [`POST ${BASE}/domain/check`]: [ + json({ environment: ENVIRONMENT, domain: domain("ok") }), + ], + }); + const tools = toolRunner({ + variables: [{ name: "APP_HOST", value: SSLIP }], + secrets: [], + run: null, + }); + const check = await invoke(["host", "domain", "check"], { + cwd, + fetchFunction: checked.fetch, + hostTools: tools.run, + }); + assert.equal(check.status, 0, check.stderr); + const output = JSON.parse(check.stdout); + assert.equal(output.app_host_changed, true); + assert.match(output.next, /APP_HOST is now app.example.com/); + assert.deepEqual(tools.calls.find((call) => call.args[1] === "set")?.args, [ + "variable", + "set", + "APP_HOST", + "--body", + "app.example.com", + ]); +}); + +test("email connect stores the SMTP password through gh and never prints it", async (context) => { + const password = "canary-smtp-password"; + const smtp = { + host: "email-smtp.us-east-1.amazonaws.com", + port: 587, + username: "AKIAEXAMPLE", + headers: { "X-SES-TENANT": "fd-1" }, + }; + const service = routes({ + [`POST ${BASE}/email/smtp-credentials`]: [ + json({ environment: ENVIRONMENT, smtp: { ...smtp, password } }, 201), + ], + }); + const tools = toolRunner({ variables: [], secrets: [], run: null }); + const result = await invoke(["host", "email", "connect"], { + cwd: appDirectory(context), + fetchFunction: service.fetch, + hostTools: tools.run, + }); + + assert.equal(result.status, 0, result.stderr); + assert.deepEqual(JSON.parse(result.stdout).smtp, smtp); + const secret = tools.calls.find((call) => call.args[0] === "secret"); + assert.deepEqual(secret?.args, ["secret", "set", "SMTP_PASSWORD"]); + assert.equal(secret?.input, password); + assertNoSecrets(result); +}); + +test("email reads the state and the month's allowance", async (context) => { + const email = { + state: "waiting_for_domain", + sending_domain: null, + paused_reason: null, + allowance: { + limit: 2000, + used: 0, + period_start: "2026-11-01", + resets_at: "2026-12-01T00:00:00Z", + }, + smtp: null, + }; + const service = routes({ + [`GET ${BASE}/email`]: [json({ environment: ENVIRONMENT, email })], + }); + const result = await invoke(["host", "email"], { + cwd: appDirectory(context), + fetchFunction: service.fetch, + }); + + assert.equal(result.status, 0, result.stderr); + const output = JSON.parse(result.stdout); + assert.deepEqual(output.email, email); + assert.match(output.next, /domain connect/); +}); + +test("service refusals and failures map to handled errors", async (context) => { + const cwd = appDirectory(context); + for (const [response, error] of /** @type {const} */ ([ + [problem(409, "host_busy"), "host_rejected"], + [problem(503, "unavailable"), "host_unavailable"], + [ + json({ environment: ENVIRONMENT, host: { state: "unknown" } }), + "invalid_host_response", + ], + [ + json({ environment: { ...ENVIRONMENT, name: "staging" }, host: host() }), + "invalid_host_response", + ], + [problem(401, "authentication_required"), "authentication_required"], + ])) { + const service = routes({ [`GET ${BASE}/email`]: [response] }); + const result = await invoke(["host", "email"], { + cwd, + fetchFunction: service.fetch, + }); + assertHandledFailure(result, error); + } + + const noProject = mkdtempSync(path.join(tmpdir(), "firstdraft-host-")); + context.after(() => rmSync(noProject, { recursive: true, force: true })); + const unpinned = await invoke(["host", "email"], { cwd: noProject }); + assertHandledFailure(unpinned, "local_input_unreadable"); +}); + +/** + * @param {import("node:test").TestContext} context + * @param {{deployFiles?: boolean, workflow?: string}} [options] + */ +function appDirectory( + context, + { deployFiles = true, workflow = WORKFLOW } = {}, +) { + const cwd = mkdtempSync(path.join(tmpdir(), "firstdraft-host-")); + context.after(() => rmSync(cwd, { recursive: true, force: true })); + mkdirSync(path.join(cwd, ".firstdraft")); + writeFileSync( + path.join(cwd, ".firstdraft", "state.json"), + `${JSON.stringify({ + format: "firstdraft.cli-state/1", + project_id: PROJECT_ID, + api_url: API_URL, + foundation_plan_etag: `"sha256:${"9".repeat(64)}"`, + })}\n`, + { mode: 0o600 }, + ); + if (deployFiles) { + mkdirSync(path.join(cwd, "config")); + writeFileSync(path.join(cwd, "config", "deploy.yml"), "service: app\n"); + mkdirSync(path.join(cwd, ".github", "workflows"), { recursive: true }); + writeFileSync(path.join(cwd, ".github", "workflows", "ci.yml"), workflow); + } + return cwd; +} + +/** + * @param {import("node:test").TestContext} context + * @param {{key?: boolean}} [options] + */ +function configDirectory(context, { key = false } = {}) { + const directory = mkdtempSync(path.join(tmpdir(), "firstdraft-host-config-")); + context.after(() => rmSync(directory, { recursive: true, force: true })); + if (key) + writeKey( + path.join(directory, "firstdraft", "hosts", PROJECT_ID, "production"), + ); + return directory; +} + +/** @param {string} directory */ +function writeKey(directory) { + mkdirSync(directory, { recursive: true, mode: 0o700 }); + writeFileSync(path.join(directory, "id_ed25519"), PRIVATE_KEY, { + mode: 0o600, + }); + writeFileSync(path.join(directory, "id_ed25519.pub"), `${PUBLIC_KEY}\n`); +} + +/** @param {Record} [changes] */ +function host(changes = {}) { + return { + state: "provisioning", + region: "nyc1", + size: "s-1vcpu-1gb", + ipv4: null, + ssh_user: "root", + ssh_key_fingerprint: fingerprint(PUBLIC_KEY), + created_at: CREATED_AT, + ready_at: null, + failure: null, + release: { state: "none_yet", version: null, changed_at: null }, + ...changes, + }; +} + +function backups() { + return { + schedule: "daily, 03:00 to 04:00 UTC", + retention_days: 30, + latest: { + taken_at: "2026-11-24T03:12:09Z", + database_bytes: 1832190, + uploads_bytes: 52011200, + state: "ok", + }, + checked_at: "2026-11-24T06:00:00Z", + latest_restore_check: null, + }; +} + +/** @param {string} status */ +function domain(status) { + return { + hostname: "app.example.com", + state: "checking", + checked_at: status === "unchecked" ? null : CREATED_AT, + records: [ + { + purpose: "app", + type: "A", + name: "app.example.com", + value: IPV4, + required: true, + status, + found: status === "ok" ? [IPV4] : [], + }, + ], + }; +} + +/** @param {string} name @param {string} conclusion */ +function job(name, conclusion) { + return { + name, + status: conclusion === "" ? "in_progress" : "completed", + conclusion, + }; +} + +/** + * A fake gh, ssh-keygen, and ssh that record every call. + * + * @param {{variables: {name: string, value: string}[], secrets: string[], run: {status?: string, conclusion: string, jobs: unknown[]} | null, cloudInit?: string}} state + */ +function toolRunner(state) { + /** @type {{command: string, args: readonly string[], input?: string}[]} */ + const calls = []; + /** @type {import("../src/host-tools.js").ToolRunner} */ + const runner = (command, args, options) => { + calls.push({ command, args, input: options.input }); + const ok = (/** @type {unknown} */ value) => ({ + status: 0, + stdout: typeof value === "string" ? value : JSON.stringify(value), + stderr: "", + }); + if (command === "ssh-keygen") { + writeKey(path.dirname(String(args[args.indexOf("-f") + 1]))); + return ok(""); + } + if (command === "ssh") return ok(`${state.cloudInit ?? "status: done"}\n`); + const [group, action] = args; + if (group === "repo") { + return ok({ + nameWithOwner: "owner/app", + defaultBranchRef: { name: "main" }, + }); + } + if (group === "secret" && action === "list") { + return ok(state.secrets.map((name) => ({ name }))); + } + if (group === "variable" && action === "list") return ok(state.variables); + if (group === "run" && action === "list") { + return ok( + state.run === null + ? [] + : [ + { + databaseId: 7, + headSha: "b".repeat(40), + status: state.run.status ?? "completed", + conclusion: state.run.conclusion, + url: "https://github.com/owner/app/actions/runs/7", + }, + ], + ); + } + if (group === "run" && action === "view") + return ok({ jobs: state.run?.jobs ?? [] }); + return ok(""); + }; + return { run: runner, calls }; +} + +/** + * Answers each "METHOD path" (or full URL for other origins) from its queue, + * repeating the last response. + * + * @param {Record} table + */ +function routes(table) { + /** @type {{method: string, url: string, body: unknown, authorization: string | null}[]} */ + const calls = []; + /** @type {typeof globalThis.fetch} */ + const fetchFunction = async (input, init) => { + const url = new URL(String(input)); + const method = init?.method ?? "GET"; + calls.push({ + method, + url: String(url), + body: init?.body, + authorization: new Headers(init?.headers).get("authorization"), + }); + const key = + url.origin === API_URL + ? `${method} ${url.pathname}` + : `${method} ${url.origin}${url.pathname}`; + const queue = table[key]; + assert(queue && queue.length > 0, `unexpected request ${key}`); + const response = queue.length > 1 ? queue.shift() : queue[0]; + return /** @type {Response} */ (response).clone(); + }; + return { fetch: fetchFunction, calls }; +} + +/** @param {unknown} body @param {number} [status] */ +function json(body, status = 200) { + return new Response(JSON.stringify(body), { + status, + headers: { "Content-Type": "application/json" }, + }); +} + +/** @param {number} status @param {string} code */ +function problem(status, code) { + return new Response( + JSON.stringify({ + type: "about:blank", + title: "Problem", + status, + code, + detail: `The Service said ${code}.`, + }), + { status, headers: { "Content-Type": "application/problem+json" } }, + ); +} + +/** @param {readonly string[]} argv @param {Record} [options] */ +async function invoke(argv, options = {}) { + let stdout = ""; + let stderr = ""; + const status = await run({ + argv, + stdout: { write: (text) => (stdout += text) }, + stderr: { write: (text) => (stderr += text) }, + apiToken: API_TOKEN, + env: { XDG_CONFIG_HOME: "/nonexistent/firstdraft-test-config" }, + fetchFunction: async () => assert.fail("No network request was expected"), + hostTools: () => assert.fail("No program was expected to run"), + hostSleep: async () => {}, + ...options, + }); + return { status, stdout, stderr }; +} + +/** @param {{status: number, stdout: string, stderr: string}} result @param {string} error @param {number} [status] */ +function assertHandledFailure(result, error, status = 1) { + assert.equal(result.status, status, result.stderr); + assert.equal(result.stdout, ""); + assert.equal(JSON.parse(result.stderr).error, error); +} + +/** @param {{stdout: string, stderr: string}} result */ +function assertNoSecrets(result) { + assert.doesNotMatch(result.stdout + result.stderr, /canary/); +}