# Run your own Lettuce server

One `lettuce` binary is both the client and the server. `lettuce serve` turns a
store on a machine you own into an authenticated HTTP API, so agents on other
machines, or in several repositories, share one record. There is no container
image or chart to fetch and no account to create: install the binary, create a
store, give each person a token.

The steps below were run end to end on macOS and Linux. Paths are examples;
`~/lettuce-server` holds everything the server owns.

## 1. Install the binary on the server machine

```sh
curl -fsSL https://lettuce.work/install.sh | sh
lettuce version
```

## 2. Create the store

```sh site-journey=server
mkdir -p ~/lettuce-server && cd ~/lettuce-server
lettuce init --root store
```

The store is a directory. Only the server process should write it while it runs.
## 3. Create the first token

A token is a random secret in a file only its owner can read. The server reads
a `tokens.yaml` that names each token and points at its secret file; the secret
itself is never written into `tokens.yaml`, never put on a command line and
never committed. One command writes both:

```sh site-journey=server
lettuce serve token add alice --tokens-file tokens.yaml
```

It generates a 256-bit secret into a new file `secrets/alice` (mode 0600, in a
0700 `secrets/` directory), creates `tokens.yaml` (or adds the entry to the one
you have, keeping its other entries and comments) and prints the secret
nowhere. It checks the result with the same loader `lettuce serve` uses, so it
never writes a file the server would refuse. This first token is your admin:
a tokens-file token is unrestricted on a server without `--authz-policy`, and
it issues every later token through the API (§8).

One token per person (all of a person's agents share it; each agent still names
itself with `--author` / `LETTUCE_ACTOR`, so the record stays attributable).
Run the command again with another name for another person, before or after
the server starts (a running server picks the token up on `SIGHUP`, §8).
The file format (YAML or JSON) is in `lettuce usage serve` under `--tokens-file`:
`tokens: [{name, secret_file | secret_sha256, default_domain, domains, default_access}]`;
`lettuce usage serve token add` lists the options (domains, a secret printed
once and kept only as its hash).

## 4. Start the server

```sh
lettuce serve --root store --listen 127.0.0.1:8727 --tokens-file tokens.yaml \
  --auto-provision-actors --recover-on-start
```

- `--listen 127.0.0.1:8727` (the default) accepts connections from this machine
  only. A non-loopback address is refused unless authentication is configured
  (a tokens file counts), so the server never opens up by accident. If port
  8727 is taken (the server then fails to start and says the address is in
  use), choose any free port, e.g. `--listen 127.0.0.1:8728`, and use the same
  port in the clients' `.lettuce` pointer (§5).
- `--auto-provision-actors` registers an agent's name, and links it to the
  project, on its first write. Without it, each agent registers once with
  `lettuce author add <name> --idempotent` and
  `lettuce project author add <project> <name> --idempotent --author <name>`.
- `--recover-on-start` reclaims the write lock of a server that crashed, only
  when that process is provably gone.
- The server logs JSON lines on stderr. It refuses requests without a valid
  token (`FW-API-AUTH-BAD`); `GET /v1/health` is the credential-free liveness check.
  On first start it logs (`INFO`) that it serves no client binaries: normal for
  a personal server, see §10.

`lettuce serve` runs in the foreground. For a quick try from one terminal, run
it in the background with its log in a file, and stop it when you are done
(for a server that keeps running, use §7 instead):

```sh
lettuce serve --root store --listen 127.0.0.1:8727 --tokens-file tokens.yaml --auto-provision-actors > serve.log 2>&1 &
curl -fsS http://127.0.0.1:8727/v1/health        # answers once the server is up
kill %1                                          # stop it (or: kill <pid>)
```

Every flag: `lettuce usage serve`.

### In a Docker container

The Linux binaries run in any container. Docker on an Apple-silicon Mac runs
`linux/arm64` containers by default, and the installer picks the container's
binary (`lettuce-linux-arm64` there, `lettuce-linux-amd64` on an x86-64 host).
A minimal image (the installer needs `curl` and `sha256sum`):

```dockerfile
FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl \
    && rm -rf /var/lib/apt/lists/* \
    && curl -fsSL https://lettuce.work/install.sh | sh -s -- --dir /usr/local/bin
ENTRYPOINT ["lettuce"]
```

Build it, run steps 2 and 3 in it against the server directory mounted at
`/srv`, then start the server. Inside a container it must listen on all of the
container's interfaces; publish the port on the host's loopback only and keep
TLS in front of it (§6):

```sh
docker build -t my-lettuce .
docker run --rm -v ~/lettuce-server:/srv -w /srv my-lettuce init --root store
docker run --rm -v ~/lettuce-server:/srv -w /srv my-lettuce serve token add alice --tokens-file tokens.yaml
docker run -d --name lettuce -v ~/lettuce-server:/srv -w /srv -p 127.0.0.1:8727:8727 my-lettuce \
  serve --root store --listen 0.0.0.0:8727 --tokens-file tokens.yaml --auto-provision-actors --recover-on-start
curl -fsS http://127.0.0.1:8727/v1/health
```

To upgrade, rebuild the image with `--no-cache` (the installer takes the newest
release) and start a new container on the same directory.

## 5. Connect the first client and create a project

On any machine that can reach the server, in the repository the work belongs
to. The pointer file carries no secret; commit it.

```sh site-journey=client
printf '%s\n' 'http://127.0.0.1:8727/' 'project: demo' 'domain: default' > .lettuce
export LETTUCE_BEARER_FILE=$HOME/lettuce-server/secrets/alice   # copy the token file to the client, mode 0600
# (or one line in ~/.config/lettuce/credentials: http://127.0.0.1:8727/ token-file=alice actor=alice)
export LETTUCE_ACTOR=alice
lettuce status
lettuce project create demo --bootstrap-author --author alice
lettuce task create --next DEMO --title "First task" --no-milestone
lettuce task list
```

`lettuce status` prints the server, its release, the domain and the project, and
warns when the project does not exist yet. Each agent then uses the token file
of the person it works for (exported, or named for this server in its credentials
file: [/agent.md](https://lettuce.work/agent.md)) and its own `LETTUCE_ACTOR`,
and runs the same commands. The agent guide: [/agent.md](https://lettuce.work/agent.md).

## 6. Reach it from other machines: TLS

Tokens travel in a header, so use HTTPS for anything beyond loopback. Keep
`lettuce serve` on `127.0.0.1` and put a TLS reverse proxy in front of it, for
example Caddy (automatic certificates):

```text
lettuce.example.com {
    reverse_proxy 127.0.0.1:8727
}
```

Clients then use `https://lettuce.example.com/` in their `.lettuce` pointer.
nginx or any other proxy works the same way. If the proxy runs on another host,
tell the server which addresses may forward client addresses with
`--trusted-proxy-cidr`, and restrict callers with `--allow-ip` if you want.

## 7. Keep it running

Linux, a systemd user service (`~/.config/systemd/user/lettuce.service`):

```ini
[Unit]
Description=Lettuce server
After=network-online.target

[Service]
WorkingDirectory=%h/lettuce-server
ExecStart=%h/.local/bin/lettuce serve --root %h/lettuce-server/store --listen 127.0.0.1:8727 --tokens-file %h/lettuce-server/tokens.yaml --auto-provision-actors --recover-on-start
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure

[Install]
WantedBy=default.target
```

```sh
systemctl --user daemon-reload && systemctl --user enable --now lettuce
loginctl enable-linger "$USER"     # keep it running after you log out
journalctl --user -u lettuce -f    # the log
```

macOS, a launchd agent (`~/Library/LaunchAgents/work.lettuce.serve.plist`;
launchd does not expand `~`, so write your home directory out):

```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key><string>work.lettuce.serve</string>
  <key>WorkingDirectory</key><string>/Users/YOU/lettuce-server</string>
  <key>ProgramArguments</key>
  <array>
    <string>/Users/YOU/.local/bin/lettuce</string><string>serve</string>
    <string>--root</string><string>/Users/YOU/lettuce-server/store</string>
    <string>--listen</string><string>127.0.0.1:8727</string>
    <string>--tokens-file</string><string>/Users/YOU/lettuce-server/tokens.yaml</string>
    <string>--auto-provision-actors</string>
    <string>--recover-on-start</string>
  </array>
  <key>RunAtLoad</key><true/>
  <key>KeepAlive</key><true/>
  <key>StandardErrorPath</key><string>/Users/YOU/lettuce-server/serve.log</string>
</dict>
</plist>
```

```sh
launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/work.lettuce.serve.plist
```

## 8. Add or revoke a token

**Without editing anything:** holding the admin token from step 3 (`alice`
here; a tokens-file token is unrestricted on a server without
`--authz-policy`), mint one per agent from any client. The server keeps only
the secret's hash, prints the secret once (here into a new 0600 file) and serves
the token from the next request, with no restart:

```sh
mkdir -p -m 700 ~/.config/lettuce   # outside any checkout: a secret is never one `add -A` from a commit
lettuce token create bob --roles reader,writer --scopes project:demo --actors bob --expires 90d --secret-file ~/.config/lettuce/bob.token
lettuce token list
lettuce token rotate bob --grace 1h --secret-file ~/.config/lettuce/bob.token.new   # the old secret works for 1h
lettuce token revoke bob --reason "left the team"                 # refused from the next request
```

The token reaches only the domain it was issued on and only what its grant
names (`--scopes project:demo`, `--actors bob`); a token cannot issue anything
wider than itself. Issued tokens live in the store's `.runtime/issued-tokens/`
(hashes only; never exported). Details: `lettuce usage token create`.

**In the tokens file:** on the server machine, `lettuce serve token add bob --tokens-file tokens.yaml` (or edit `tokens.yaml` and the secret files by hand), then send the server `SIGHUP`:
`systemctl --user reload lettuce`, `launchctl kill HUP gui/$(id -u)/work.lettuce.serve`,
or `kill -HUP <pid>`. The server re-reads and re-validates the file and swaps the
whole token set at once; a broken file is refused, the previous tokens keep
working, and the log says why. The same signal reloads `--authz-policy` and the
issued tokens. Revoking a token cuts off its holder; an author
name stays in the record (`lettuce author deactivate <name> --reason "..."`
stops it from writing).

## 9. Back up

```sh site-journey=backup
mkdir -p ~/lettuce-backups
lettuce export --root ~/lettuce-server/store --bundle ~/lettuce-backups/lettuce.json
```

`export` writes a consistent, deterministic bundle while the server runs (name
the file `lettuce-$(date +%Y%m%d).json` to keep several). To restore, import the
bundle into a new, empty store as one of its authors, then point `serve --root`
at it:

```sh site-journey=backup
lettuce import --root ~/lettuce-restored --bundle ~/lettuce-backups/lettuce.json --author alice
```

Alternatively, stop the server and copy the whole `~/lettuce-server` directory,
or snapshot the volume. Keep the `secrets/` directory out of shared backups.

## 10. Upgrade

Clients and server should run the same release: every client command warns
`FW-CLIENT-VERSION-SKEW` when they differ.

**Back up before every upgrade** (step 9, with the release you are leaving). Some
releases change the store format (v0.26.0 does): once one writes the store, an older `lettuce`
refuses every write to it (`FW-STORE-REQUIRES-RELEASE`, whose first suggestion is
`lettuce self-update`) and only reads still work. There is no downgrade: going
back means restoring the backup you made before the upgrade (step 9, run with the
old release), and losing what was written since.

```sh
curl -fsSL https://lettuce.work/install.sh | sh     # on the server machine
systemctl --user restart lettuce                      # or: launchctl kickstart -k gui/$(id -u)/work.lettuce.serve
```

Then on each client, run the installer again. A bound client's
`lettuce self-update` installs the server's own release when the server serves
its client binaries: put the `lettuce-<os>-<arch>` file of each published
platform (`darwin-arm64`, `darwin-amd64`, `linux-amd64`, `linux-arm64`) of the server's
release, their `.sha256` files and a `VERSION` file holding the tag (e.g.
`v0.25.0`) into a directory and start the server with
`--client-binaries-dir DIR`. Without that (the server says so at start, as an
`INFO` line), `self-update` in a bound repository reports
`FW-CLIENT-BINARY-UNAVAILABLE`, naming the installer for the server's release
when lettuce.work keeps it. lettuce.work keeps the last few releases (the
`kept=` line of `https://lettuce.work/download/latest.txt`), so the installer
matches a server on one of them with `--version` (e.g.
`curl -fsSL https://lettuce.work/install.sh | sh -s -- --version v0.25.0`); for a
server on an older release it refuses, naming the kept ones: upgrade the server
first, then the clients.

## 11. More than one store

One server can host several independent stores ("domains"), each with its own
projects and authors, and give each token access to some of them:
`lettuce usage serve` (`--domains-root`), `lettuce usage domain create`.

Lettuce is free to use under the
[Lettuce Binary License](https://lettuce.work/BINARY-LICENSE). Questions:
info@huru.io.
