# Sifur CLI

Connect Sifur's agents to your own test server, apply a ticket's work to your checkout, and record
a case in your browser.

Use it when your app only runs on your team's servers, behind a firewall or VPN that Sifur can't
reach. Sifur never deploys to your server, never holds VPN or server credentials, and never connects
into your network: you deploy the ticket's branch, and `sifur serve`, running on your test server,
connects out to Sifur so its agents can use the app there and run the acceptance cases.

## Requirements

- Node.js 20 or newer
- Google Chrome or Microsoft Edge (the tool drives the browser you already have; it downloads none).
  On a server, the `sifurai/serve` image carries its own (see [Run it on a server](#run-it-on-a-server))
- A machine that can reach your test server (the test server itself, or a laptop on your company VPN)

## Install

Install it once to get the `sifur` command:

```sh
npm install -g @sifurai/cli
sifur --version
```

Update it with:

```sh
npm install -g @sifurai/cli@latest
```

(`npx @sifurai/cli …` works too, but npx can keep running an older version it has cached, so an
installed `sifur` is the reliable way.)

## Sign in

```sh
sifur login
```

This prints a code and opens Sifur in your browser. Check that the code matches, approve it, and
the CLI is signed in. The sign-in is listed with your other sessions in Sifur, where you can revoke it.
It follows your organization's single sign-on and MFA rules, like the console.

The token is saved with owner-only permissions (0600) in:

- macOS and Linux: `~/.config/sifur/credentials.json` (or `$XDG_CONFIG_HOME/sifur`)
- Windows: `%APPDATA%\sifur\credentials.json`

To sign out (and revoke the session):

```sh
sifur logout
```

## Apply Sifur's work before you deploy

Your test server needs the ticket's code, one of two ways:

- **Push the branch** from the ticket's Overview (Before you run), and pull it down on your test
  server or let your CI/CD deploy it. Nothing needs applying.
- **Don't push:** apply Sifur's changes to your checkout and deploy that. Sifur pushes the branch
  itself once you approve it after acceptance testing, so your CI isn't set off by every change
  along the way.

`sifur apply` puts Sifur's changes in your checkout:

```sh
cd ~/src/azalea
sifur apply AZA-12
```

It works on the checkout you're in when it's the ticket's repository (the ticket names only that
one, or the checkout's folder has its name), or on `--workdir <repository>=<dir>` for each
repository. The checkout needs no uncommitted changes (commit or stash them first) and must have the
commit Sifur's work starts from; if it doesn't, the CLI tells you to `git fetch` and check out the ticket's branch. The changes are
applied with `git apply --3way` and left uncommitted (staged); the CLI prints how many files each
repository's changes touch.

To take them back out:

```sh
sifur apply AZA-12 --revert
```

`apply` keeps a copy of the patch in a cache folder per user, outside your checkout, for
`--revert`, which deletes it once the changes are out. It saves the patch before it changes a
checkout, so if `apply` fails partway, `--revert` still takes out what went in. It stops at a
repository the patch left with conflicts, after taking out the ones applied before it: run
`git reset --merge` there (it undoes only what the patch staged), then `--revert` again.
Changes you took out yourself (a `git reset --hard`, a clean checkout) are noticed: `apply`
forgets them and goes on, and `--revert` only forgets them. Ones still in the checkout have to
come out with `--revert` before a newer version goes in.
The patch is kept in:

- macOS and Linux: `~/.cache/sifur/AZA-12/applied/` (or `$XDG_CACHE_HOME/sifur/AZA-12/applied/`)
- Windows: `%LOCALAPPDATA%\sifur\AZA-12\applied\`

The CLI never reads or writes a `.sifur` folder in your checkout. Version 0.1.0 kept its files
there; if one is left over, the CLI says so, and you can delete it.

Once your test server runs the ticket's code, press **Deployed** on the ticket: Sifur runs the
acceptance cases there through `sifur serve` (below).

## Record a case

To show Sifur a flow yourself, record the case in a browser:

```sh
sifur record AZA-12 TC-3                                  # record TC-3's steps again
sifur record AZA-12 --new "The filter keeps the choice"   # add a case
sifur record AZA-12 --new "…" --repository web            # when the project has more than one repository
```

It uses the project's test server unless `--url` names another. The CLI:

1. Downloads the ticket's cases and signs in to your test server with Sifur's sign-in (the steps
   every UI case starts with), in a browser you can watch (`--headless` hides it). The sign-in's
   secrets come from `SIFUR_SECRET_<NAME>`, or are asked for (see Secrets).
2. Opens Playwright's recorder in Chrome (or Edge), already signed in, on the page the sign-in
   left it at. Do the case's steps, then check the result with the toolbar's **Assert text** or
   **Assert visibility** on what the change shows. Close the window, or press Ctrl-C in the terminal, when you're done.
3. Turns the recording into Sifur's steps and shows them. The sign-in isn't part of them: Sifur
   puts it in front of every UI case.
4. Asks `Upload these N steps? [y/N]`, and uploads them as the case's new version (or as a new
   case). Sifur refuses a recording made against an older version of the case, or after the
   ticket has moved on; record it again.

A recording needs at least one check: what proves the case is yours to choose, so the CLI never
adds one. Sifur replays opening a page, clicks (a double-click, check or uncheck counts as a
click), typing into a field, key presses and choosing an option, on elements found by role, text,
label, placeholder, test id or CSS, in the page or one of its frames. Anything else (hovering,
uploading a file, dragging, the keyboard or mouse on their own, dialogs, popups and new tabs, a
value or snapshot check) is refused, with each line and the reason, and nothing is uploaded.

**Credentials.** What you type is never uploaded as typed where it's a credential. A value that
matches a secret the CLI knows (the sign-in's, or any `SIFUR_SECRET_<NAME>`) becomes its
placeholder, `{{NAME}}`. Anything else typed into a field whose selector or label looks like a
password, email or username field, the CLI asks you to name a placeholder for (like
`APP_PASSWORD`); when the case runs, it comes from `SIFUR_SECRET_<NAME>` or is asked for.
The recorder only sees the field's selector, not its type, so check the steps it shows you before
you upload them.

The signed-in session and the recorder's raw output (which holds everything you typed) are kept in
a private temporary folder (the session file with owner-only permissions, 0600) and deleted as
soon as the recorder closes, whatever happens, Ctrl-C included.

The session carries into the recorder through its cookies and storage (`localStorage` and
IndexedDB). An app that keeps it only in `sessionStorage` opens signed out there, and can't be
recorded this way yet.

## Let Sifur's agents use your test server: `sifur serve`

`sifur serve` runs on your team's test server (or on a laptop on the VPN) and lets Sifur's agents
use the running app and its database through it. It connects out to Sifur and long-polls for the
next thing an agent asks; nothing connects in, so no port is opened and Sifur holds no VPN or
server credentials. One `serve` per project: the last one to start takes over, with the same token
or a new one, and the one before stops with "Another test server took over this project." A new
token also revokes the old one.

Make a token in the project's settings (Test server), then write `serve.json` in the config folder
(`~/.config/sifur/serve.json`, or `%APPDATA%\sifur\serve.json` on Windows; `--config <file>` for
another):

```json
{
  "appUrl": "https://test.example.internal/app/",
  "database": {
    "client": "mysql",
    "url": "mysql://app_login:…@127.0.0.1:3306/app"
  },
  "logs": ["/var/www/app/storage/logs/laravel.log"],
  "checkout": "/srv/app",
  "automated": { "command": ["npx", "playwright", "test"] },
  "accounts": {
    "PRACTICE_ADMIN": { "username": "admin@example.com", "password": "…", "role": "Practice administrator, can manage billing" },
    "FRONT_DESK": { "username": "desk@example.com", "password": "…", "role": "Front desk, can book visits" }
  },
  "secrets": { "CLINIC_CODE": "…" }
}
```

**Test accounts.** Each entry in `accounts` is a user of the app the agents may sign in as. Its name
(upper case, `[A-Z][A-Z0-9_]*`) gives the placeholders `{{PRACTICE_ADMIN_USERNAME}}` and
`{{PRACTICE_ADMIN_PASSWORD}}`, and its `role` says who that user is in the app. `serve` tells Sifur
the names and roles, and the names of the `secrets`, never a value: the agents write cases only for
those accounts, and a case that needs a role none of them has is flagged before it runs. `secrets`
fill any other `{{NAME}}`. Before it runs a case or replays steps, `serve` checks every placeholder
they use: one with no value here refuses them, before anything runs ("This case needs
`{{NURSE_PASSWORD}}`, which this test server doesn't have."), after reading `serve.json` and the
`SIFUR_*_FILE` files again in case the account was just added. A case whose step right after its
sign-in's submit fails with a password field still showing is reported as "The test account
couldn't sign in", so Sifur sends it to you rather than calling the case wrong; a failure at the
sign-in's own steps (a selector, a page that errors) is the case's, like any other. `serve` reads
its accounts and secrets again before every case and replay and every minute while it waits for
work, and tells Sifur the names and roles on its next ping (within a minute), so an account added or
a password changed takes effect without a restart. The database's user and host are no secret:
they're taken out only of database errors, while its passwords and URLs are redacted everywhere.

```sh
SIFUR_SERVE_TOKEN='…' sifur serve          # or --token, or "token" in serve.json
sifur serve --headed                       # on a laptop: watch the agents in the browser
```

Everything in `serve.json` stays on this machine. It can come from the environment instead (see
[Configuration from the environment](#configuration-from-the-environment)).

**Checking the database and the app.** Before it says hello, `serve` runs `SELECT 1` on
`database.url`. If the database refuses the sign-in, refuses the user its
database (or it doesn't exist), or can't be reached, `serve` says which, without the password ("The database refused the sign-in for
app_login@db.example.internal:3306: check serve.json's database.url (or SIFUR_DATABASE_URL).") and
exits 2; in the image it says so and waits to be stopped, as after a takeover. Neither is sent to
Sifur as an error. Once serving, it tells Sifur at hello and every minute (and with each ping while
it works) how the database (`ok`, `sign_in_failed`, `unreachable` or `not_configured`) and the app
(`ok` or `unreachable`: any HTTP answer at `appUrl` counts) are, which the project's Test server
settings show, and the project's leads are told when either goes wrong. A connection whose sign-in
fails is thrown away, and the next query signs in afresh with `serve.json` and the `SIFUR_*_FILE`
files read again, so a password changed in a mounted secret takes effect without a restart.

What the agents can do through it:

- **The browser** (headless unless `--headed`): open pages, run and replay steps, inspect a
  selector, look at the page. The browser stays on `appUrl`'s origin: a link, script, form, popup or
  new tab that would take it elsewhere is stopped (popups and new tabs are closed), and nothing is
  shown of a page off it. A page on the app is fetched by `serve` itself before the browser gets it,
  so a redirect to another site is stopped before anything, a form's data included, reaches it; a
  redirect within the app is followed, cookies and all; a download or export is fetched by the
  browser itself. Chrome can't tell where a page handed over that way came from, so the app's origin
  is allowed what Chrome would allow a page from its address: the machine's other ports for an app on
  `localhost`, the private network for an app on a private address, nothing for a public one. A frame your app embeds may
  load another site (a map, a payment form) and move around within it, but a frame showing your
  app's own content (loaded from it, `srcdoc`, written by a script, `data:` or `blob:`) can't be
  taken to one. Another site's frame is never shown to the agents: inspect skips it and screenshots
  paint over it. A popup or new tab is closed as it opens; one going to another site fails the step. Screenshots mask password fields and anything showing a secret, the token or
  the database's password, in the page and in every frame showing your app, and those are `[secret]`
  in any text sent back.
- **`query`**: one read-only statement (`SELECT`, `SHOW`, `EXPLAIN`, `DESCRIBE`, `WITH`), always
  inside a read-only transaction that's rolled back, at most 200 rows and 256 KB (the rest is never
  fetched), stopped after 30 s. More than one
  statement, `INTO OUTFILE`/`INTO DUMPFILE`, `EXPLAIN ANALYZE` and comments the database runs as
  code (`/*! … */`) are refused, even inside a string.
- **`write`**: one `INSERT`, `UPDATE` or `DELETE`, run in a transaction only once someone approves
  it, in the console or, when `serve` runs in a terminal, at its `Approve? (y/N)` prompt; the first
  answer wins, and the terminal says who answered in the console. Unanswered after 30 minutes, it's
  denied. Schema changes are never run. Just before it runs an approved write, `serve` tells Sifur;
  if Sifur has already given up on it (this machine was asleep, or offline), the write isn't run.
- **`log`**: the last lines of the files in `logs`.
- Addresses on the app's origin reach Sifur relative to `appUrl` (`orders?id=7`), never the app's
  own address. While it works, `serve` pings Sifur every 20 s so a long case doesn't make it look
  disconnected, and a result that doesn't reach Sifur is retried until the action's deadline. An
  action that runs past its deadline is failed ("ran past its time on the test server"), its pings
  stop and `serve` takes the next: an automated runner is killed then, with everything it started
  (its whole process group, so a watch mode dies too), a UI case's browser is closed, and the
  agents' browser starts afresh, so nothing left of that action can touch the next one's page or
  the accounts it uses. Stopping `serve` kills a running automated test's process group the same way.
- **Cases**: UI cases run in the browser with the `accounts` and `secrets` above. Automated cases run in
  `checkout` with the runner in `"automated": { "command": [...] }`, started without a shell; a case
  adds only its test, which must be a file in the checkout (`tests/visits.spec.ts`, optionally
  `:line`). Anything else is refused, and with no `automated.command` no automated case runs here.
  The runner gets this machine's environment without any `SIFUR_*` variable.

A write is stopped after 30 s too. On MySQL that means killing its session from a second
connection, which rolls it back; the database user needs no extra privilege to end its own.

**One database login.** Queries run read-only on the same login that approved changes use, so the
login needs `INSERT`, `UPDATE` and `DELETE` only for approved changes. A read-only transaction stops
writes to tables but not everything (a Postgres superuser can still end other sessions with
`pg_terminate_backend`, and a MySQL user with the `FILE` privilege can read the server's files), so
give the login no more than the app's database needs. A `readUrl` (`SIFUR_DATABASE_READ_URL`) left
over from an earlier version is ignored, with one line at startup: "readUrl is no longer used:
queries use database.url inside a read-only transaction."

Supported databases: MySQL (`"client": "mysql"`) and PostgreSQL (`"client": "postgres"`).

**Error reports.** When something breaks unexpectedly (a crash, a browser that won't start, a lost
database connection), `serve` sends Sifur the error, its stack, the CLI's version and which action
failed, with your secrets and the database's credentials taken out; never the action's input, query
rows or screenshots. Other commands do the same when you're signed in. A report that fails is
dropped. `"reportErrors": false` in `serve.json` turns them all off.

Ctrl-C (or `SIGTERM`, as `docker stop` sends) stops `serve` (exit 0). It exits 1 when another
`serve` takes over, its token is revoked, or Sifur won't serve its project (the project is inactive
or deleted, or its organization is suspended or closed: `serve` says which), and 2 when its database refuses the sign-in or can't be
reached at start; in the image it waits instead (see
[Run it on a server](#run-it-on-a-server)).

### Configuration from the environment

`serve` also reads its configuration from environment variables, which is how a container is
usually configured. They're used when there's no `serve.json`, or merged over it, the environment
winning:

| Variable | Sets |
|---|---|
| `SIFUR_SERVE_CONFIG` | The whole of a `serve.json`, as JSON |
| `SIFUR_APP_URL` | `appUrl` |
| `SIFUR_DATABASE_CLIENT` | `database.client` (`mysql` or `postgres`) |
| `SIFUR_DATABASE_URL` | `database.url` |
| `SIFUR_LOGS` | `logs`, comma separated |
| `SIFUR_CHECKOUT` | `checkout` |
| `SIFUR_REPORT_ERRORS` | `reportErrors` (`true` or `false`) |
| `SIFUR_SECRET_<NAME>` | `secrets.<NAME>`, as `record` reads them |
| `SIFUR_ACCOUNT_<NAME>_USERNAME`, `_PASSWORD`, `_ROLE` | `accounts.<NAME>`'s `username`, `password` and `role` |
| `SIFUR_SERVE_TOKEN` | The token, as always |
| `SIFUR_<NAME>_FILE` | Any of these, read from a file (a mounted Docker or Kubernetes secret) |
| `SIFUR_SERVE_ON_STOP` | `wait`: on a takeover, a revoked token or an inactive project or organization, wait to be stopped instead of exiting 1 (the image sets it) |

The single variables win over `SIFUR_SERVE_CONFIG`. The runner for automated cases
(`automated.command`) has no variable of its own: set it in `SIFUR_SERVE_CONFIG` or `serve.json`.
None of these variables reaches the automated test runner. A value that's wrong is refused at start,
naming the variable.

## Run it on a server

The `sifurai/serve` image is the recommended way to run `serve` on a server: plain Docker on a VM, a
Compose service beside the app, ECS or Kubernetes. It carries Node and a headless Chromium, runs as
a non-root user, and starts `sifur serve`, so nothing is installed on the host. (`npm install -g`
stays the way on a laptop.) It reads `/config/serve.json` when one is mounted there, and the
environment over it.

Run exactly one. On ECS or Kubernetes, `serve` is its own one-replica service in the app's network,
not a sidecar in the app's task or pod: an app with several replicas would start several `serve`s.

### Before you start

Every option below begins here. Run it on a machine or network that can reach three things: your
app, your test database, and Sifur over the internet (outbound HTTPS only; nothing connects in).
Have ready the token from the project's settings (Test server, Create token) and a test login of
your app the agents may use. MySQL and PostgreSQL are supported. Everything you fill in stays on
your side: Sifur sees only the account names and roles, never a password.

The database needs one login. The agents' queries use it inside a read-only transaction that is
always rolled back, and approved changes use it to write, so it needs `INSERT`, `UPDATE` and
`DELETE` only for those approved changes.

| Value | What it is | Needed |
|---|---|---|
| `SIFUR_SERVE_TOKEN` | The token from Create token. It ties this test server to this project. | Yes |
| `SIFUR_APP_URL` | Your app's address as the test server reaches it: the page a person would open. | Yes |
| `SIFUR_DATABASE_CLIENT` | Which database: `mysql` for MySQL, `postgres` for PostgreSQL. | With a database |
| `SIFUR_DATABASE_URL` | The test database. Queries run read-only through it; changes run only after someone approves them. | With a database |
| `SIFUR_ACCOUNT_USER_USERNAME` | The email or username of a test login on your app, e.g. `qa@example.com`. The agents sign in with it. | Recommended |
| `SIFUR_ACCOUNT_USER_PASSWORD` | That login's password. It stays on your test server; Sifur never sees it. | With a username |
| `SIFUR_ACCOUNT_USER_ROLE` | A few words on who that login is, e.g. `Regular user`, so the agents pick the right one. | Recommended |
| `SIFUR_LOGS` | Your app's log files, as the container sees them, for the agents to read. | No |

`USER` is a name you choose. For another kind of user, add another set with its own name, e.g.
`SIFUR_ACCOUNT_ADMIN_USERNAME`, `SIFUR_ACCOUNT_ADMIN_PASSWORD` and `SIFUR_ACCOUNT_ADMIN_ROLE`.

Each option's step 1 is this section.

**Taking over.** Each `serve` starts a session when it says hello, and Sifur takes calls only from
the latest one. So starting `serve` on a laptop takes over from the server's container, and the
container's `serve` stops. On a laptop, a `serve` that's taken over (or whose token is revoked, or
whose project or organization can't be used) exits 1. In the image it says why once and then waits, calling Sifur no more, until the container is
stopped or restarted: every orchestrator restarts a container that exits, and a restarted `serve`
would take the project straight back. Restarting the container on purpose takes the project back
(with a new token, if the old one was revoked). `SIFUR_SERVE_ON_STOP=wait`, which the image sets, is
what makes it wait.

**Deploys.** A new container that starts before the old one stops takes over from it, which is
harmless, but an action the old one had taken is lost and times out. Run one at a time: on
Kubernetes use `strategy: { type: Recreate }`; on ECS set `minimumHealthyPercent: 0` and
`maximumPercent: 100`. `serve` stops at once on `SIGTERM`, as `docker stop` and both orchestrators
send, and exits 0.

**Reaching the app.** `localhost` inside the container is the container, not the host. Use
`--network host` (Linux), `host.docker.internal`, or the app's Compose service name on a shared
network; on ECS, the app's internal load balancer or its service discovery name; on Kubernetes,
its Service name. The same goes for the database's host in `SIFUR_DATABASE_URL`. Don't call the
app's service `app`: `.app` is a domain browsers force onto HTTPS, so Chromium refuses
`http://app:8080/`.

**Logs.** Mount the app's log folder read-only (`-v /var/log/app:/logs:ro`) and list the files as
the container sees them (`SIFUR_LOGS=/logs/app.log`, or `"logs": ["/logs/app.log"]`).

**Automated cases.** Mount the repository's checkout (`-v /srv/app:/checkout:ro`), set
`SIFUR_CHECKOUT=/checkout` and give `automated.command`. With none, they run in Sifur's sandbox
instead. With the checkout read-only, point the runner's output elsewhere (for Playwright,
`["npx", "playwright", "test", "--output", "/tmp/test-results"]`); its dependencies must already
be installed in the checkout, and a Playwright test runner finds the image's Chromium only when its
version matches the image's.

**Secrets.** The token, the database URL and the case secrets go in environment variables, or in
files: any `SIFUR_<NAME>_FILE` is read into `SIFUR_<NAME>`, so Docker and Kubernetes secrets
mounted as files work (`SIFUR_SERVE_TOKEN_FILE=/run/secrets/sifur_token`). On ECS, use Secrets
Manager. Never bake them into an image.

### Docker

The simplest way on a server you run.

1. **Before you start.** See [Before you start](#before-you-start).
2. **Start the container.** Replace each `…` and example value with yours, then run it on the
   server. Drop the database lines to run without one, and the log lines without log files.

   ```sh
   docker run -d --name sifur-serve --restart unless-stopped \
     -e SIFUR_SERVE_TOKEN='…' \
     -e SIFUR_APP_URL=https://test.example.internal/app/ \
     -e SIFUR_DATABASE_CLIENT=mysql \
     -e SIFUR_DATABASE_URL='mysql://app_login:…@db.example.internal:3306/app' \
     -e SIFUR_LOGS=/logs/laravel.log \
     -v /var/www/app/storage/logs:/logs:ro \
     -e SIFUR_ACCOUNT_USER_USERNAME='qa@example.com' \
     -e SIFUR_ACCOUNT_USER_PASSWORD='…' \
     -e SIFUR_ACCOUNT_USER_ROLE='Regular user' \
     sifurai/serve
   ```

3. **Check it worked.** Within a minute the project's Test server settings show **Connected**,
   with the database and the app reachable and your test accounts listed. If it says the database
   sign-in failed or the app is unreachable, fix that value and restart it. `docker logs -f
   sifur-serve` shows what the agents do.

A database change is answered in the console (there's no terminal to type `y` in). To use a
`serve.json` instead, mount it: `-v /etc/sifur/serve.json:/config/serve.json:ro`. Options go after
the image name (`sifurai/serve --timeout 120`). The notes under [Before you start](#before-you-start)
(taking over, reaching the app, automated cases, secrets) apply.

### Docker Compose

For an app you already run with Docker Compose: the test server joins it as one more service on the
same network, the app reached by its service name.

1. **Before you start.** See [Before you start](#before-you-start).
2. **Put the private values in `.env`.** Beside your `compose.yaml`, in a file kept out of the
   repository (or use Compose's `secrets:`).

   ```sh
   SIFUR_SERVE_TOKEN='…'
   SIFUR_DATABASE_URL='postgres://app_login:…@db:5432/app'
   SIFUR_ACCOUNT_USER_PASSWORD='…'
   ```

3. **Add the service to `compose.yaml`.** Replace `web` and its port with your app's service, and
   the example values with yours.

   ```yaml
   services:
     web:
       # …your app, listening on 8080
     sifur-serve:
       image: sifurai/serve
       restart: unless-stopped
       environment:
         SIFUR_APP_URL: http://web:8080/
         SIFUR_DATABASE_CLIENT: postgres
         SIFUR_DATABASE_URL: ${SIFUR_DATABASE_URL}
         SIFUR_LOGS: /logs/app.log
         SIFUR_CHECKOUT: /checkout
         SIFUR_SERVE_CONFIG: '{"automated": {"command": ["npx", "playwright", "test", "--output", "/tmp/test-results"]}}'
         SIFUR_SERVE_TOKEN: ${SIFUR_SERVE_TOKEN}
         SIFUR_ACCOUNT_USER_USERNAME: qa@example.com
         SIFUR_ACCOUNT_USER_PASSWORD: ${SIFUR_ACCOUNT_USER_PASSWORD}
         SIFUR_ACCOUNT_USER_ROLE: Regular user
       volumes:
         - ./storage/logs:/logs:ro
         - .:/checkout:ro
   ```

4. **Start it.**

   ```sh
   docker compose up -d sifur-serve
   ```

5. **Check it worked.** Within a minute the project's Test server settings show **Connected**,
   with the database and the app reachable and your test accounts listed. If it says the database
   sign-in failed or the app is unreachable, fix that value and restart it. `docker compose logs -f
   sifur-serve` shows what the agents do.

The `${…}` values come from the shell or the `.env` file; a token can instead come from a Compose
secret file (`SIFUR_SERVE_TOKEN_FILE: /run/secrets/sifur_token`, with `secrets: [sifur_token]` on
the service and `sifur_token: { file: ./sifur_token.txt }` at the top level), kept out of the
repository too. The notes under [Before you start](#before-you-start) apply.

### ECS

For an app on AWS. The test server runs as its own small Fargate service, with one task, in the
same VPC as your app. Never add it as a second container in your app's task: an app with several
tasks would start several.

1. **Before you start.** See [Before you start](#before-you-start).
2. **Store the private values in Secrets Manager.** One secret holding each value as a key,
   including your test login's `SIFUR_ACCOUNT_…` keys. Note the secret's full ARN: it ends in a
   random suffix (`sifur/serve-AbCdEf`), which you copy from the console or the `create-secret`
   output.

   ```sh
   aws secretsmanager create-secret --name sifur/serve \
     --secret-string '{"SIFUR_SERVE_TOKEN": "…", "SIFUR_DATABASE_URL": "mysql://app_login:…@db.internal:3306/app", "SIFUR_ACCOUNT_USER_USERNAME": "qa@example.com", "SIFUR_ACCOUNT_USER_PASSWORD": "…", "SIFUR_ACCOUNT_USER_ROLE": "Regular user"}'
   ```

3. **Let the task read the secret.** Give the task execution role (often `ecsTaskExecutionRole`)
   this policy, with your secret's ARN. If the role can't create log groups
   (`logs:CreateLogGroup`), create `/ecs/sifur-serve` in CloudWatch first and drop
   `awslogs-create-group` from the task definition.

   ```json
   {
     "Version": "2012-10-17",
     "Statement": [{
       "Effect": "Allow",
       "Action": "secretsmanager:GetSecretValue",
       "Resource": "arn:aws:secretsmanager:<region>:<account>:secret:sifur/serve-<suffix>"
     }]
   }
   ```

4. **Make a security group for it.** In your app's VPC: no inbound rules, outbound allowed. Then
   allow this group into your database's security group (its port, e.g. 3306), and into the
   app's if it isn't reached through a public address. It must reach the app (its internal load
   balancer or service discovery name in `SIFUR_APP_URL`) and the database, and reach Sifur over
   outbound HTTPS. Nothing inbound.
5. **Save the task definition.** Save this as `sifur-serve.json`, with your region, account,
   secret ARN and your app's address. Chromium needs at least 1 GB of memory.

   ```json
   {
     "family": "sifur-serve",
     "requiresCompatibilities": ["FARGATE"],
     "networkMode": "awsvpc",
     "cpu": "1024",
     "memory": "2048",
     "executionRoleArn": "arn:aws:iam::<account>:role/ecsTaskExecutionRole",
     "containerDefinitions": [
       {
         "name": "sifur-serve",
         "image": "sifurai/serve",
         "essential": true,
         "environment": [
           { "name": "SIFUR_APP_URL", "value": "http://web.internal.example:8080/" },
           { "name": "SIFUR_DATABASE_CLIENT", "value": "mysql" }
         ],
         "secrets": [
           { "name": "SIFUR_SERVE_TOKEN", "valueFrom": "arn:aws:secretsmanager:<region>:<account>:secret:sifur/serve:SIFUR_SERVE_TOKEN::" },
           { "name": "SIFUR_DATABASE_URL", "valueFrom": "arn:aws:secretsmanager:<region>:<account>:secret:sifur/serve:SIFUR_DATABASE_URL::" },
           { "name": "SIFUR_ACCOUNT_USER_USERNAME", "valueFrom": "arn:aws:secretsmanager:<region>:<account>:secret:sifur/serve:SIFUR_ACCOUNT_USER_USERNAME::" },
           { "name": "SIFUR_ACCOUNT_USER_PASSWORD", "valueFrom": "arn:aws:secretsmanager:<region>:<account>:secret:sifur/serve:SIFUR_ACCOUNT_USER_PASSWORD::" },
           { "name": "SIFUR_ACCOUNT_USER_ROLE", "valueFrom": "arn:aws:secretsmanager:<region>:<account>:secret:sifur/serve:SIFUR_ACCOUNT_USER_ROLE::" }
         ],
         "logConfiguration": {
           "logDriver": "awslogs",
           "options": {
             "awslogs-group": "/ecs/sifur-serve",
             "awslogs-region": "<region>",
             "awslogs-stream-prefix": "serve",
             "awslogs-create-group": "true"
           }
         }
       }
     ]
   }
   ```

6. **Register it and create the service.** Use your app's subnets and the security group from
   step 4. In a public subnet keep `assignPublicIp=ENABLED`; in a private one, drop it: the task
   then reaches Sifur and Docker Hub through your NAT gateway. Without either, the image pull and
   the calls to Sifur fail.

   ```sh
   aws ecs register-task-definition --cli-input-json file://sifur-serve.json
   aws ecs create-service --service-name sifur-serve --cluster <your cluster> \
     --task-definition sifur-serve --desired-count 1 --launch-type FARGATE \
     --deployment-configuration minimumHealthyPercent=0,maximumPercent=100 \
     --network-configuration 'awsvpcConfiguration={subnets=[<app subnets>],securityGroups=[<sifur-serve group>],assignPublicIp=ENABLED}'
   ```

7. **Check it worked.** Within a minute the project's Test server settings show **Connected**,
   with the database and the app reachable and your test accounts listed. If it says the database
   sign-in failed or the app is unreachable, fix that value and restart it. The task's output is
   in CloudWatch under `/ecs/sifur-serve`.

Notes:

- **Deploys.** `desiredCount: 1`, with `minimumHealthyPercent: 0` and `maximumPercent: 100`, so a
  deploy stops the old task before starting the new one. To upgrade, register the task definition
  with a newer image tag and update the service.
- **Secrets.** `SIFUR_SERVE_TOKEN`, the database URL and any `SIFUR_ACCOUNT_*` or `SIFUR_SECRET_*`
  go in the task definition's `secrets`, from Secrets Manager or Parameter Store; the execution
  role must be allowed to read them. The rest are plain `environment`.
- **Logs.** The app's logs are in CloudWatch, which `serve` can't read yet, so leave `SIFUR_LOGS`
  unset and `log` says none are configured. `serve`'s own output goes to CloudWatch through the
  `awslogs` configuration above, which creates its log group only when the execution role has
  `logs:CreateLogGroup`.
- **Automated cases.** Without a checkout, they run in Sifur's sandbox.

### Kubernetes

For an app on Kubernetes: its own Deployment with one replica in the app's namespace. Never add it
to your app's pod: an app with several replicas would start several.

1. **Before you start.** See [Before you start](#before-you-start).
2. **Store the private values in a Secret.**

   ```sh
   kubectl create secret generic sifur-serve --namespace <app namespace> \
     --from-literal=SIFUR_SERVE_TOKEN='…' \
     --from-literal=SIFUR_DATABASE_URL='mysql://app_login:…@mysql:3306/app' \
     --from-literal=SIFUR_ACCOUNT_USER_USERNAME='qa@example.com' \
     --from-literal=SIFUR_ACCOUNT_USER_PASSWORD='…' \
     --from-literal=SIFUR_ACCOUNT_USER_ROLE='Regular user'
   ```

3. **Apply the Deployment.** Save it as `sifur-serve.yaml` with your namespace and your app's
   Service address, then `kubectl apply -f sifur-serve.yaml`.

   ```yaml
   apiVersion: apps/v1
   kind: Deployment
   metadata:
     name: sifur-serve
     namespace: <app namespace>
   spec:
     replicas: 1
     strategy: { type: Recreate }
     selector:
       matchLabels: { app: sifur-serve }
     template:
       metadata:
         labels: { app: sifur-serve }
       spec:
         containers:
           - name: sifur-serve
             image: sifurai/serve
             env:
               - { name: SIFUR_APP_URL, value: "http://web.<app namespace>.svc.cluster.local:8080/" }
               - { name: SIFUR_DATABASE_CLIENT, value: mysql }
             envFrom:
               - secretRef: { name: sifur-serve }
   ```

4. **Check it worked.** Within a minute the project's Test server settings show **Connected**,
   with the database and the app reachable and your test accounts listed. If it says the database
   sign-in failed or the app is unreachable, fix that value and restart it. `kubectl logs -f
   deploy/sifur-serve` shows what the agents do.

Notes:

- **Deploys.** `replicas: 1` and `strategy: { type: Recreate }`, so a rollout stops the old pod
  before starting the new one.
- **Reaching the app.** Its Service name in the namespace; the database likewise. A network
  policy, if any, lets `serve` reach the app and the database, and HTTPS out to Sifur.
- **Secrets.** From a Secret, through `envFrom` or `secretKeyRef` (or mounted as files, with
  `SIFUR_<NAME>_FILE`); never in the Deployment.
- **Logs.** When the app writes log files to a volume, mount it read-only and set `SIFUR_LOGS`;
  otherwise `log` says none are configured.
- **Automated cases.** Without a checkout mounted at `SIFUR_CHECKOUT`, they run in Sifur's sandbox.

### Laptop

For a try-out, or when only your laptop can reach the app, for example over a VPN.

1. **Install the CLI.** `npm install -g @sifurai/cli`
2. **Say what it can use.** Save the `serve.json` shown [above](#let-sifurs-agents-use-your-test-server-sifur-serve)
   as `~/.config/sifur/serve.json` (`%APPDATA%\sifur\serve.json` on Windows), with your values.
   Everything in it stays on that machine. Each of the `accounts` is a test login of your app, with
   who it is: the agents see only its name and role, and use `{{ADMIN_USERNAME}}` and
   `{{ADMIN_PASSWORD}}`, which `serve` fills in.
3. **Start it.**

   ```sh
   SIFUR_SERVE_TOKEN='…' sifur serve --headed
   ```

   `--headed` shows the browser the agents work in, and database changes can be approved at its
   prompt as well as in the console. Starting it takes over from a server's `serve`, which waits
   until it's restarted; stop the laptop's when you're done.
4. **Check it worked.** Within a minute the project's Test server settings show **Connected**,
   with the database and the app reachable and your test accounts listed. If it says the database
   sign-in failed or the app is unreachable, fix that value and restart it; `serve` prints what it
   does in the terminal.

## Secrets

A UI case can use a placeholder such as `{{APP_USERNAME}}` or `{{APP_PASSWORD}}` for a test
account's sign-in, in what it types, the page it opens, and the text or URL it checks for. `serve`
fills them in from `"accounts"` (`{{<NAME>_USERNAME}}`, `{{<NAME>_PASSWORD}}`) and `"secrets"` in
`serve.json`, or from `SIFUR_ACCOUNT_<NAME>_*` and `SIFUR_SECRET_<NAME>`. `record` takes each from the environment variable `SIFUR_SECRET_<NAME>` (for example
`SIFUR_SECRET_APP_PASSWORD`) or, when that isn't set, asks you for it once per run, after saying
which case and step needs it. A name with `USER`, `EMAIL` or `LOGIN` in it shows what you type;
any other, and always one with `PASSWORD`, `TOKEN` or `SECRET`, doesn't. Secrets stay on your
machine: they are never written to disk, never sent to Sifur, and are replaced with `[secret]` in
any error message.

`{{RUN}}` isn't a secret and is never asked for: it's replaced with a short token, new for each
run and the same in every case and step of it, so a case can create data that's unique each time
(`qa-{{RUN}}@example.com`) and check for it afterwards.

```sh
SIFUR_SECRET_ADMIN_PASSWORD='…' sifur record AZA-12 TC-3
```

## Options

| Option | |
|---|---|
| `--url <url>` | With `record`: your test server, where the ticket's branch is deployed |
| `--headless` | With `record`: run the browser without showing it; it shows by default |
| `--timeout <seconds>` | How long each browser step may take, page loads included (default 60). Raise it when the test server is slow, for example over a VPN |
| `--workdir <repository>=<dir>` | With `apply`: apply that repository's changes in `<dir>`; repeatable. Default: the checkout you're in, when it's that repository's |
| `--revert` | With `apply`: take the changes back out |
| `--new <title>` | With `record`: record a new case with this title |
| `--repository <name>` | With `record --new`: the case's repository, when the project has more than one |
| `--token <token>` | With `serve`: the project's test server token (or `SIFUR_SERVE_TOKEN`, or `"token"` in `serve.json`) |
| `--config <file>` | With `serve`: its configuration, instead of `serve.json` in the config folder |
| `--headed` | With `serve`: show the browser the agents work in; `serve` is headless by default |
| `--api <url>` | Sifur's API, for `login` (default `https://api.sifur.ai`, or `SIFUR_API_URL`). Not your test server: that's `appUrl` in `serve.json` |

## Troubleshooting

**`<url> isn't Sifur's API`** from `sifur login --api <url>`: `--api` is Sifur's own address (for
example `https://api.sifur.ai`), and is only needed for a Sifur other than the default. Your test
server goes in `"appUrl"` in `serve.json`, or `sifur record --url`.

**`unable to get local issuer certificate`** or **`self-signed certificate`**: Node doesn't trust the
certificate of the Sifur it's talking to. If this is a local or company Sifur with its own
certificate, run with `NODE_OPTIONS=--use-system-ca` (Node 22.15+), or point Node at the root
certificate with `NODE_EXTRA_CA_CERTS=<root cert>`.

## Exit codes

| Code | Meaning |
|---|---|
| 0 | Done (`record` uploaded the steps; `serve` stopped with Ctrl-C) |
| 1 | You chose not to upload a recording, or another `serve` took over, its token was revoked, or its project or organization can't be used |
| 2 | An error: not signed in, the ticket isn't in acceptance testing, Sifur unreachable, no Chrome or Edge, … |
