Files
ShellBook/apps/server/README.md
T

97 lines
6.3 KiB
Markdown

# Server execution and artifacts (M2/M3, issues #3/#4)
`buildApp({ config: { workspaceDir, dataDir, sshKeyPath }, events })` accepts
overrides for tests and embedding. Defaults come from `SHELLBOOK_WORKSPACE`
(`workspace`), `SHELLBOOK_DATA_DIR` (`data`), and `SHELLBOOK_SSH_KEY`
(`data/id_ed25519`). Paths resolve against the service working directory.
The workspace contains `notebooks/**/*.md`, `hosts.yaml`, and `known_hosts`.
Inventory accepts either a YAML list or `{ hosts: [...] }`; every entry requires
`name`, `address`, and `user`. Port defaults to 22, tags to an empty list.
Nested notebook and artifact route parameters must be URL-encoded as a single
parameter. Saves require an existing notebook and its SHA256 content version;
concurrent saves in this process are serialized and stale versions return 409.
Filesystem symlinks, traversal, Windows drive paths and non-Markdown notebooks
are rejected. The workspace is trusted local storage; external editors must not
replace directories with symlinks concurrently with requests.
Pass a shared `EventsHub` from `src/runs/events.ts` as `events` to publish watcher
events using `hub.publish(event)`. Each connected `/api/events` WebSocket receives
the shared events. There is no replay buffer. Subscribe before POSTing a run.
Run execution is FIFO per SSH address/port (including different inventory aliases),
with a separate local queue. Different endpoints can execute concurrently.
SSH uses the configured private key without a PTY. Host keys are pinned in
OpenSSH's plain `host key-type base64-key` format (bracketed host/port for non-22
ports). Hashed hostnames, wildcard entries, certificates and marker directives
are not supported. Existing plain keys are checked strictly. Unknown or changed
keys abort before exec; `acceptHostKey` must equal the observed SHA256 fingerprint
before a pin is written or replaced. Failed authentication never writes a pin.
The script passed to bash is the core-rendered script. Execution setup selects a
fresh workdir, and prepends `export NAME=<core shellQuote(value)>` lines on stdin
for secrets. This avoids sshd `AcceptEnv` and sudo environment filtering and also
works with Windows WSL bash. Secret values are never placed in exec argv. Neither
the transport prelude nor raw SSH errors are logged. Local runs use the same
stdin transport. Streamed output and captures redact exact secret values across
chunk boundaries; encoded or transformed secret output cannot be detected.
Audit records store only the rendered script, with defensive secret redaction.
Local working files are in `data/runs/<uuid>/work/`. Declared successful artifacts
are copied to a separate `artifacts/` tree and listed as `{name, sensitive}` entries
in `artifacts.json`; only
listed files can be downloaded or used as upload sources, including after a
restart. Local upload destinations must be relative to the fresh workdir. Remote
uploads may use absolute destinations (the notebook format intentionally permits
`/tmp/new_key.pub`). Remote artifact realpaths must remain inside the fresh
`mktemp -d` directory. Cleanup is attempted before closing SSH; connection loss
or forced timeout can leave remote temporary files behind.
Execution timeouts close the channel and connection; Unix local runs kill the
process group. Windows process-tree termination depends on the installed bash
implementation. SFTP establishment and transfers have a 30-second limit. Capture
is limited to 1 MiB. Failures emit short, specific `run.error` reasons (timeout,
authentication, connection, missing upload/artifact, or nonzero script exit),
with secret redaction and no raw transport errors or stack traces.
The service has root-equivalent access and must be
deployed with the authentication plugin and trusted workspace permissions.
Dependencies: `ssh2` supplies SSH/SFTP and strict host verification, `yaml` parses
the inventory. `@types/ssh2` and `@types/ws` are compile-time declarations only.
Tests use an in-process SSH/SFTP server that never invokes a real shell. Local
bash tests skip only when bash cannot successfully execute a probe.
## Sensitive artifacts and retention
Collection inspects only the first 512 bytes for PEM private-key headers, including
OpenSSH, RSA, EC, DSA, encrypted and generic private keys. Sensitivity is persisted
without file contents and reported in `run.finished.sensitiveArtifacts`. A local
sensitive file is removed from `work/` after collection so it has no spare copy.
Public files remain repeatable downloads and upload sources. Legacy name-only
metadata remains readable; sensitivity is detected from the file on access.
A sensitive download takes an exclusive filesystem claim before streaming. Parallel
requests cannot both succeed. Only after the HTTP response finishes does cleanup
delete the artifact; an interrupted response releases the claim for retry. Downloads
use `Cache-Control: no-store`. Once deleted, subsequent downloads return 410 and
upload attempts fail with a specific `run.error`. An undeclared name in an existing
run returns 404; a valid unknown run, expired run, or missing declared file returns
410. Invalid run IDs/paths return 400. A crash during a claimed download leaves a
fail-closed claim until retention removes the run; it does not allow a second copy.
`ServerConfig.artifactTtlHours` / `SHELLBOOK_ARTIFACT_TTL_HOURS` sets a positive,
finite TTL in hours (default **24**, fractional hours supported). Whole run directories
under `data/runs/` expire based on their directory modification time (normally last
collection/metadata write). Expiration is enforced at download/upload lookup; physical
cleanup runs on startup and hourly. Queued/executing runs are protected from the
sweep. The interval is unref'd, cleared on app close, and outstanding sweeps finish
before shutdown. The service owns this data directory; do not share it between
independent server processes with different run queues.
The HTTP tests in `test/m3.test.ts` use real core parsing/rendering and an in-process
SSH/SFTP server. A portable seeded-artifact flow covers sensitivity, downloads,
uploads, and capture/runtime rendering without bash. The full shipped `ssh-key.md`
flow generates real keys and skips cleanly when bash or ssh-keygen is unavailable;
it runs in CI/Linux, and also on Windows when a working bash with ssh-keygen is
installed. No real target host is modified by these tests.