stratum-node-cli 0.1.0-alpha.2

The `stratum` client for Stratum pod nodes: operator key files, bootstrap, config, backup, invitations and members over the loopback API; join, pod access and export for tenants through the gate
Documentation
# stratum-node-cli

> [!WARNING]
> **Pre-release (`0.1.0-alpha`).** Commands, output, exit codes and the
> library API may change before 0.1.0. Nothing built on it has been deployed
> yet. The client has no TLS: it talks to loopback addresses only, and
> reaches a node's public origin through a local address (`--connect`) until
> the remote transport arrives with the public origin.

`stratum` is the client for a [Stratum](https://github.com/DreamLab-AI/stratum)
node. The administrator uses it on the node's loopback administrative API,
over plain HTTP, with the operator's own Nostr key: setup, configuration,
backups, invitations and members. A tenant uses it with their own key to join
a node and to read, write and export their pod through the node's gate. It
never sees the node key or the node's state volume; `stratum setup` reads the
bootstrap token file only because the operator points it there.

It depends only on the published `stratum-node-core` and
`stratum-node-config` crates, so it installs on any Unix machine.

## Install

```sh
cargo install stratum-node-cli
```

This installs the `stratum` binary. Minimum supported Rust version: 1.89.

## Global options

| Option | Environment | Default | Meaning |
|---|---|---|---|
| `--url <URL>` | `STRATUM_URL` | `http://127.0.0.1:7460` | The node API. The host must be an IPv4 address in `127.0.0.0/8` in canonical dotted-decimal form (`127.0.0.1`, `127.0.0.2`, …; not `127.1` or zero-padded forms), `[::1]` or `localhost`; anything else, `https://`, user information, queries and fragments are refused. |
| `--key-file <FILE>` | `STRATUM_KEY_FILE` | none | The signing key: one `nsec1…` line in a regular file with no access for group or others (`0600`). Symbolic links are refused. The operator's key for administrator commands; the tenant's own key for `join`, `pod` and `export`. |
| `--json` | | off | Machine-readable output: one JSON value on standard output; run-time errors as one JSON object on standard error. Command-line usage errors are plain text with exit status 64. |

Tenant commands (`join`, `pod …`, `export`) take two more options:

| Option | Environment | Meaning |
|---|---|---|
| `--origin <ORIGIN>` | `STRATUM_ORIGIN` | The node's canonical origin, such as `https://stratum.visionclaw.pro`: `https://` or `http://`, a lowercase host, no default port, no path. Every request names its authority in `Host` and is signed over `<origin><path>`. |
| `--connect <HOST:PORT>` | `STRATUM_CONNECT` | The gate's loopback address, such as `127.0.0.1:7461`: an address in `127.0.0.0/8`, `[::1]` or `localhost`, with a port. Requests go there over plain HTTP. Required for an `https://` origin, which is otherwise refused with a message that the remote transport arrives with the public origin. An `http://` origin without it is reached at its own host and port, which must then be a loopback address. |

Proxy environment variables are ignored and redirects are never followed:
a signed request goes only to the URL it was signed for. `localhost` is
never looked up: `stratum` connects to `127.0.0.1` and still sends
`Host: localhost:<port>` and signs the `localhost` URL, so neither
`/etc/hosts` nor a resolver can send a request off the machine. A node that
listens only on IPv6 must be addressed as `[::1]`.

## Commands

| Command | What it does |
|---|---|
| `stratum key generate --out <file>` | Creates an operator key from the system random source, written as one `nsec1…` line to a new file with mode `0600` set at creation. Refuses to overwrite anything. Prints only the `did:nostr:…` and `npub`. |
| `stratum key show` | Prints the DID and `npub` of `--key-file`. |
| `stratum status` | `GET /readyz` and a summary. Exit 0 ready, 3 unconfigured, 4 degraded, 2 unreachable. |
| `stratum config schema` | The configuration schema: every field's path, type, default, apply class and description. |
| `stratum config show` | The effective configuration, head and active revisions and public-config hash (signed). |
| `stratum config preview --set path=value …` | The diff, the change list, each change's apply class and the strictest class, without changing anything. Signed when a key file is given (the node requires it once bound). |
| `stratum config apply --set path=value … [--base-revision n] [--operation-id id] [--yes]` | Previews, prints the diff and the strictest apply class, then applies on the same base revision after confirmation: `--yes`, or an answer on the terminal. Without either it applies nothing and exits 6. A random operation ID is generated when none is given and printed so a retry can reuse it. |
| `stratum setup --token-file <path> [--set path=value …] [--expect-node <did>] [--show-text] [--resume-file <file>] [--yes]` | The bootstrap claim; see below. Without `--set`, the node is claimed with its seed configuration unchanged. |
| `stratum sign-challenge --claim-body-file <file> --expect-node <did> [--url <claim url>]` | Offline signing: prints the `Authorization` header value for the claim body and URL. Refuses a body for another claimant or another node than `--expect-node`, or an expired one. No network. |
| `stratum audit checkpoint` | Prints the audit checkpoint `<seq>:<hex>` and the node DID (signed). |
| `stratum backup [--operation-id id] [--expect-node <did>]` | Asks the node for a backup and prints the directory, checkpoint and configuration revision (signed). Before printing, the returned manifest event must be validly signed, of NIP-78 kind 30078 and authored by the node DID from `/readyz` (and that DID must be `--expect-node` when given); its content must be a `stratum-backup` version 1 manifest naming that node and listing `stratum.db`, `stratum.toml` and `node-key.age`; and its signed `audit_checkpoint` must equal the printed checkpoint. |
| `stratum invite create <did> [--expires-in <duration>] [--connect <host:port>] [--operation-id id] [--expect-node <did>]` | Issues an invitation for one `did:nostr` (signed). The lifetime is seconds or a number with `s`, `m`, `h` or `d`, at most `30d`; without it, the node's `membership.invitation_ttl_secs`, read from its effective configuration. Prints the invitation identifier, subject, expiry, canonical origin and node DID, and the exact `stratum join …` line the invitee runs; `--connect` sets the gate address in that line (default `127.0.0.1:7461`). |
| `stratum invite list` | Lists invitations with their state: `issued`, `redeemed`, `expired` or `revoked` (signed). |
| `stratum invite revoke <invitation> [--operation-id id]` | Revokes an invitation that is still `issued` (signed). |
| `stratum member list` | Lists members with their state, pod URL, operation and last provisioning error, and the capacity in use (signed). |
| `stratum member repair <did> [--operation-id id] [--yes]` | Runs provisioning again for a member: restores a missing root ACL and leaves an existing one alone (signed). Asks first. |
| `stratum member cancel <did> [--operation-id id] [--yes]` | Cancels a `reserved` member, releasing its slot; the invitation stays used (signed). Asks first. |

### Tenant commands

Each is signed with the tenant's key over the canonical URL, with a fresh
event every time (the one exception is the single `join` resend below). An
event is identified by its content to the second, so every signed request
carries a `nonce` tag of 16 random bytes: two identical requests signed in
the same second, by one command or by two run back to back, are still
distinct events, and the node does not refuse the second as a replay.
Nothing waits for the clock.

| Command | What it does |
|---|---|
| `stratum join --invitation <id> --node <did> --origin … [--connect …] [--wait-secs n] [--yes]` | Redeems an invitation and activates the pod; see the walk-through. |
| `stratum pod ls [<path>]` | Lists a container (the pod root by default). Each child the listing names is resolved against the listing's address and shown only if it lies under the container; anything else is reported as refused. |
| `stratum pod get <path> [-o <file>]` | Reads a resource. With `-o`, writes the bytes to a new file (mode `0600`; an existing file is never overwritten); otherwise to standard output, unchanged into a pipe and with control characters escaped on a terminal. `--json` needs `-o`. |
| `stratum pod put <path> <file> [--content-type …] [--if-match <etag> \| --create-only]` | Writes a file (at most 1 GiB) to a resource. The content type is guessed from the file name unless given. `--if-match` writes only over that entity tag; `--create-only` only where nothing is (`If-None-Match: *`). |
| `stratum pod rm <path> [--yes]` | Deletes a resource or an empty container. Asks first. The root ACL is never deleted: that would lock everyone out, the owner included. |
| `stratum pod acl get [<path>] [-o <file>]` | Reads the ACL beside a resource or container: `x.txt.acl` for `x.txt`, `docs.acl` for `docs/`, and the root ACL `/pods/<pk>.acl` for the pod root. |
| `stratum pod acl put <path> <file> [--content-type …] [--if-match … \| --create-only]` | Writes the ACL beside a resource or container (`text/turtle` unless given; `""` is the pod root). |
| `stratum export -o <archive.tar.zst> [--force]` | Exports your own pod; see below. |

A `<path>` is relative to your own pod root (`private/x.txt`), or absolute
(`/pods/<64 lowercase hex>/…` or `/pods/<64 lowercase hex>.acl`) to address
another member's pod, which works only where they have granted you access.
Every path is checked before anything is sent. Step 2 allows only the
unreserved characters `A–Z a–z 0–9 - . _ ~` in names, with `/` between
segments: no spaces, no percent-encoding, no `.` or `..` segment and no empty
segment. A refused path says which rule refused it and exits 64.

### Values for `--set`

Values are typed by the schema compiled into `stratum-node-config`:

- booleans are `true` or `false`;
- integers are decimal (the node checks the range);
- strings, enums and secret references are taken as written, and may be empty;
- lists of strings are comma-separated (`--set backup.age_recipients=age1pq1…,age1pq1…`),
  or the same path repeated (`--set backup.age_recipients=a --set backup.age_recipients=b`).
  `path=` is the empty list. Elements cannot be empty or contain a comma.

## Bootstrap walk-through

A fresh node boots `unconfigured` and writes a single-use token to
`<state_dir>/bootstrap-token` (mode `0600`). Whoever can read that file is
the owner.

1. Create the operator key on the machine that will administer the node:

   ```sh
   mkdir -p ~/.config/stratum
   stratum key generate --out ~/.config/stratum/operator.nsec
   export STRATUM_KEY_FILE=~/.config/stratum/operator.nsec
   ```

2. Check the node is waiting to be set up (exit code 3):

   ```sh
   stratum status
   ```

3. Claim it, with any initial configuration (or none: without `--set` the
   seed configuration is committed unchanged). `stratumd` logs its node DID
   when it starts listening (`stratumd listening … node=did:nostr:…`); pass
   it as `--expect-node`:

   ```sh
   sudo -E stratum setup --token-file /var/lib/stratum/state/bootstrap-token \
       --expect-node did:nostr:<node hex> --set node.name=alpha
   ```

   With `--expect-node`, `stratum` sends nothing but `GET /readyz` until
   the node reports that DID, so the bootstrap token never goes to another
   node. **Without it, setup trusts whatever answers on the loopback port**:
   a local process that holds the port while `stratumd` is down would
   receive the token. `/readyz` is not signed, so the pin stops a wrong URL
   or a responder that does not know the DID, not an impostor that has
   learned it; Step 1 has no TLS.

   `stratum` derives the initial configuration itself: the seed text of
   `stratum-node-config` (the text of revision 0) with the `--set` changes
   applied. It asks the node for a preview of the same changes and stops
   unless the node's text and diff equal its own byte for byte, then shows
   its own diff and change list. `--show-text` also prints the whole text.
   It then asks the node for a challenge and checks the claim body before
   signing anything: it must name this key as claimant and the node DID
   reported by `/readyz`, must not have expired, must answer the challenge,
   must be based on revision 0, and its `config_sha256` must be the SHA-256
   of exactly that locally derived text, the text shown. The claim URL
   must be this client's own `/api/v1/bootstrap/claim` with method `POST`.
   It then shows the claim fields and asks for confirmation (or takes
   `--yes`). Because the text comes from the client's own copy of
   `stratum-node-config`, the client and `stratumd` must be built on the
   same version of it; if they differ, setup stops with exit 7 and signs
   nothing.

   The signed request, the claim body and the token are saved to the resume
   file (default `<key file>.setup-resume`, mode `0600`, created exclusively)
   before anything is sent. On success, `stratum` prints the administrator
   DID, the revision and the public-config hash, and deletes the resume file.

4. If the response is lost (a timeout, a dropped connection, a 5xx), rerun the
   same command. Because the resume file exists, `stratum` resends the
   identical signed request byte for byte, and a node that already committed
   the claim returns its stored result. The token is taken from the resume
   file, since the node deletes its token file once the claim commits. A 4xx
   answer deletes the resume file: the identical request can never succeed.
   With `--expect-node`, the saved claim must name that node and `/readyz`
   must report it before the saved request is resent.

5. Keep `stratum audit checkpoint` output somewhere the node cannot write.

### Key on another machine

If the operator key never touches the node's host, request the challenge
yourself and sign offline:

```sh
# On the node host: ask for a challenge for the operator's DID.
curl -s http://127.0.0.1:7460/api/v1/bootstrap/challenge \
    -H 'Content-Type: application/json' \
    -d '{"did":"did:nostr:<operator hex>","base_revision":0,"changes":[]}' \
    | jq -j .claim_body > claim.json

# On the key's machine: sign the exact bytes for the claim URL.
stratum sign-challenge --claim-body-file claim.json \
    --expect-node did:nostr:<node hex> \
    --url http://127.0.0.1:7460/api/v1/bootstrap/claim
```

`sign-challenge` refuses a body that names another claimant, a node other
than `--expect-node` (taken from `stratumd`'s start-up log, never from the
file), or has expired, and it signs only for `/api/v1/bootstrap/claim`. It
cannot check the configuration hash or base revision offline: those are
signed as the node issued them, so review the challenge response before
signing, or use `stratum setup`, which checks them.

Then send `claim.json` verbatim to the claim URL with the printed
`Authorization` header, `Content-Type: application/json` and the token in
`Stratum-Bootstrap-Token`. The header is valid for 60 seconds around its
creation time. The claim body must not gain a trailing newline (`jq -j`
writes none); `sign-challenge` warns if the file ends in whitespace.

## Tenant walk-through

The administrator issues the invitation and passes on the printed line:

```sh
stratum invite create did:nostr:<tenant hex> --expires-in 7d
```

The tenant creates a key once, then joins with the identifier, node DID and
origin from that line:

```sh
stratum key generate --out ~/.config/stratum/me.nsec
export STRATUM_KEY_FILE=~/.config/stratum/me.nsec
export STRATUM_ORIGIN=https://stratum.visionclaw.pro STRATUM_CONNECT=127.0.0.1:7461
stratum join --invitation <id> --node did:nostr:<node hex>
```

`join` fetches the node's admission notice and stops, signing nothing,
unless the node it reached reports the DID the invitation names, the origin
given, and a notice whose SHA-256 (computed over the text received) equals
both the hash the node reports and the hash of the notice this client was
built with. It shows the notice and asks for confirmation (a terminal is
required unless `--yes`), redeems the invitation with an admission claim
signed by the tenant's key, waits up to `--wait-secs` (default 120) for the
pod to be provisioned, showing the node's last error if it reports one, then
writes a probe resource in the pod, reads it back, deletes it, and confirms.
It prints the pod URL, `<origin>/pods/<tenant hex>/`.

If the connection fails after the redemption was sent, `join` resends the
identical signed request once, and the node returns the response it stored.
Rerunning `join` after any partial run is safe: it asks the node for the
tenant's operation first, and a tenant who is already a member continues
from where the last run stopped without redeeming again. Exit 8 means the pod
was not provisioned in time; rerun the same command.

Then write, read and export:

```sh
printf 'hello\n' > note.txt
stratum pod put private/note.txt note.txt
stratum pod get private/note.txt -o copy.txt
stratum pod acl get                # the root ACL
stratum export -o pod.tar.zst
```

### Export

`stratum export` walks your own pod from `/pods/<pk>/` and fetches the root
ACL `/pods/<pk>.acl`. Each child a listing names is resolved against the
listing's own address and followed only if it is on the canonical origin,
passes the path rules above, is in your own pod and lies under the container
listed; anything else (another pod, another origin, a `.` or `..` segment)
is skipped and reported. Redirects are never followed. For every container
and resource it asks for the ACL beside it (a 404 means there is none) and
records which exist. Nothing is fetched twice.

It writes a tar archive compressed with zstd that unpacks to
`pods/<pk>/…` (containers as directories) and `pods/<pk>.acl`, byte for byte
as stored, and beside it `<archive>.manifest.json`: every entry's path,
kind, size, SHA-256 and content type, the ACLs that exist, the archive's own
size and SHA-256, and what changed, vanished or was skipped. The export is not
a snapshot: after the walk it asks again for each resource's entity tag and
each container's listing and reports what changed or vanished meanwhile
(exit 9; both files are still written). The walk stops with an error at
100,000 entries or 64 GiB.

Both files are written under temporary names beside the target (mode
`0600`) and moved into place when complete: the archive first, then the
manifest. The manifest is the commit point, so a manifest beside an archive
always describes that archive. An archive with no manifest beside it is an
export that did not finish; run it again. Without `--force` nothing is ever
replaced, not even a file that appears at either name while the export runs
(another export to the same name, say): the export fails, and an archive it
had already placed is withdrawn. With `--force`, the old manifest is set
aside before the archive is replaced and put back if the archive cannot be
moved. Two files cannot be replaced in one atomic step, so a failure or a
crash between the two moves leaves an archive with no manifest (and perhaps
a hidden `.<archive>.manifest-old-…` file), never an archive beside a
manifest that describes something else. Forced exports run at the same time
to the same name are not coordinated. `stratum` does not read the manifest
back; to check an archive against it, compare `sha256sum <archive>` with the
manifest's `archive.sha256`.

## Exit codes

| Code | Meaning |
|---|---|
| 0 | Success; for `status`, the node is `ready` |
| 1 | Local failure: a key, token or resume file, the clock, or writing output |
| 2 | The node could not be reached |
| 3 | `status`: the node is `unconfigured` |
| 4 | `status`: the node is `degraded` |
| 5 | The node's response does not follow the API contract (including an oversized body) |
| 6 | Previewed but not applied: no confirmation |
| 7 | A local check refused the node's answer (claim body, backup manifest, admission notice, join probe) |
| 8 | `join`: the pod was not provisioned within `--wait-secs`; rerun to continue |
| 9 | `export`: the archive was written, but entries changed, vanished or were skipped |
| 10 | `bad_request` |
| 11 | `unauthorized` |
| 12 | `forbidden` |
| 13 | `not_found` |
| 14 | `conflict` (stale revision, already bound, operation conflict) |
| 15 | `payload_too_large` |
| 16 | `unsupported_media_type` |
| 17 | `invalid`, or a preview with validation errors |
| 18 | `too_many_challenges` |
| 19 | `backup_refused` |
| 20 | `internal` |
| 21 | A server error code this client does not know |
| 22 | `request_timeout` |
| 23 | `capacity_exhausted` |
| 24 | `invitation_refused` |
| 25 | `invitations_disabled` |
| 26 | `gate_unavailable` |
| 27 | `too_many_requests` |
| 28 | `misdirected_request` (the `--origin` is not the node's) |
| 29 | `method_not_allowed` |
| 30 | `insufficient_storage` |
| 31 | `precondition_failed` (`--if-match` or `--create-only` did not hold) |
| 64 | Invalid command line |

Codes 0 to 22 and 64 are as published in Step 1; 8, 9 and 23 to 31 were added
in Step 2. Server errors are printed as `code: message`, with any validation
errors listed below. Text from the node has control characters escaped. On a
pod route the pod server's own error bodies are not in the error envelope;
they are named after their HTTP status (`not_found: HTTP 404 from the pod
server`) and never echoed.

## Secrets

The operator secret is read into memory that is zeroised afterwards and is
never printed, logged or put in an error, in any encoding; it is never sent
to the node either. The bootstrap token is never printed: once read, every
line `stratum` writes, including error text and JSON that came from the
node, has the token (in either letter case, and its base64 forms) replaced
by `<redacted>`, so a node that echoes it back cannot make the CLI show it.
The claim result is printed from its checked fields only. Every
`Authorization` value `stratum` signs is redacted in the same way (the token
after the `Nostr` scheme word becomes `<redacted>`, in any letter case and
wherever it starts), so a server that echoes one back cannot make the CLI
print it. Every signature stays registered until the process exits, so a
header quoted much later, such as a provisioning error shown after many
polls, is still caught. Both are checked
by the test suite, which runs every command, including failures and nodes
that reflect the token, and searches the captured output for the secret in
hex, `nsec`, bech32 payload and base64 forms, and for the token.

Key, resume, token and claim body files are opened once with `O_NOFOLLOW`
and `O_NONBLOCK`, and their type, mode and (for the key and resume files)
owner are checked on the open descriptor, so a symbolic link or a FIFO
swapped in at the path is refused without blocking. The key and resume
files must belong to the user running `stratum`, except under root, so
`sudo -E stratum setup` works with the operator's own key file. A resume
file written under `sudo` belongs to root: rerun the resend with `sudo` too.

Key and resume files are written to a hidden temporary file in the same
directory (`.<name>.tmp-…`, mode `0600`), synced, and only then moved to
their final name with a move that never replaces an existing file
(`renameat2(RENAME_NOREPLACE)`, or a hard link where that is unsupported).
An existing file is never overwritten, and a process killed mid-write leaves
at most the hidden temporary file, never a partial key or resume file.

## Library

The binary is a thin `clap` front end over the `stratum_node_cli` library,
which exposes the commands (`Session`), key files, `--set` parsing and the
exit codes so they can be tested and reused:

```rust
use stratum_node_cli::{exit, parse_changes, LoopbackUrl};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let url: LoopbackUrl = "http://[::1]:7460".parse()?;
    assert_eq!(url.join("/readyz"), "http://[::1]:7460/readyz");

    let changes = parse_changes(["node.name=alpha", "federation.egress_enabled=false"])?;
    assert_eq!(changes.len(), 2);

    assert_eq!(exit::for_server_code("conflict"), exit::CONFLICT);
    Ok(())
}
```

## Licence

AGPL-3.0-only. See [LICENSE](LICENSE).