Files
ShellBook/apps/server
Florian Schmidt eb31de7120 feat(server): refuse runs only for values the step uses (#16)
Drop the scope-wide required-parameter check in prepareRun; renderStep's
missing and invalid lists are the single gate, matching the UI.
2026-11-16 16:49:47 +01:00
..

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.

Setup and settings (#10)

On first startup, dataDir/setup-token is created privately (0600). The startup message names its path, never the token. Read it locally and finish setup in the browser. GET /api/auth/setup returns {required}; POST accepts {token,newPassword,confirmPassword}, consumes the token, and returns 204 with a session cookie (409 once configured). Setup/login share a per-IP limiter and the origin check. Keep the data directory private and owned by the service user.

Authenticated routes: POST /api/settings/password accepts {currentPassword,newPassword,confirmPassword}; POST /api/settings/sessions/revoke rotates the signing key atomically. Both return 204 with a replacement cookie and close existing WebSockets. Passwords need 12 characters and at most 4096 bytes. Hash-bound session signatures invalidate cookies after CLI password changes too. Previously issued cookies from before this feature require a fresh login once. GET /api/settings/session returns {lifetimeSeconds}; GET /api/settings/system returns package version, workspace/data paths, and Node version. GET /api/settings/claude runs claude --version with no shell, a 3-second timeout and 4096-byte output limit. loginAppearsPresent checks existence only of the service user's ~/.claude/.credentials.json; it cannot prove login validity (and does not inspect macOS Keychain credentials). All status responses are no-store.

Auth mutations are serialized within the single service process. Run one server per data directory. Already-running host jobs are not cancelled by revocation. Forward-auth access must be revoked at the upstream provider.