Compare commits
38
Commits
4fe7e4e376
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
04771b74a1 | ||
|
|
381c7f555e | ||
|
|
eb31de7120 | ||
|
|
bdbcd2dcd5 | ||
|
|
cae72c7f28 | ||
|
|
2025185489 | ||
|
|
936abbef9d | ||
|
|
2fc5f99f59 | ||
|
|
ebf8649ab6 | ||
|
|
6350f1e6f4 | ||
|
|
bcf392e95a | ||
|
|
57305a2dc6 | ||
|
|
6bfcc9d70d | ||
|
|
dd0af5d580 | ||
|
|
e38f9c453c | ||
|
|
16cfcd36ea | ||
|
|
382da1736f | ||
|
|
276d6ef3ca | ||
|
|
54115289cc | ||
|
|
85afd105f7 | ||
|
|
845d6c828e | ||
|
|
28e806d641 | ||
|
|
5e923b9c30 | ||
|
|
399628bf16 | ||
|
|
5e60973ebf | ||
|
|
4fe64ee110 | ||
|
|
27be03d79a | ||
|
|
324ad4b39a | ||
|
|
83e4e3f15e | ||
|
|
488f992bd3 | ||
|
|
63458dd3e4 | ||
|
|
df6698c67d | ||
|
|
4d9a632625 | ||
|
|
2e907b75f2 | ||
|
|
0055001abf | ||
|
|
911387264b | ||
|
|
7095842cf0 | ||
|
|
02a22bef40 |
@@ -2,10 +2,23 @@
|
||||
|
||||
- [2026-11-15] **Custom app instead of marimo/Atuin/Runme.** Need: literal, copyable shell + SSH run + checks + params + dynamic downloads + Claude Code CLI next to the notebook. No existing tool covers all; marimo hid commands behind Python.
|
||||
- [2026-11-15] **TypeScript monorepo** (core / server / web). One language; node-pty + xterm.js is the proven path for the embedded Claude terminal.
|
||||
- [2026-11-15] **AI = real `claude` CLI in a tmux-backed terminal panel.** Uses the user's subscription legitimately; marimo's ACP panel was deprecated and API-key chat is not wanted.
|
||||
- [2026-11-15] **AI = real `claude` CLI in chat or tmux terminal (#8).** Chat uses per-turn headless stream-json with explicit resume; restricted file tools, optional Bash, dedicated authenticated WebSocket. Subscription login stays with the CLI; no SDK/API-key chat.
|
||||
- [2026-11-15] **Workspace (notebooks, hosts.yaml) is a separate git repo** from the app code; the app ships a `CLAUDE.md` format guide into it.
|
||||
- [2026-11-16] **buildApp wiring:** auth registered first and on by default (`auth:false` only in tests); one EventsHub feeds /api/events from runs and the notebook watcher (`watchNotebooks`); terminal cwd = config.workspaceDir.
|
||||
- [2026-11-16] **Secrets on SSH:** exported via `export NAME=<shellQuote>` lines on stdin before the script (sshd AcceptEnv unreliable); redacted from streamed output, captures and audit.
|
||||
- [2026-11-16] **Deploy:** Node 22 from the official nodejs.org tarball verified against SHASUMS256; node-pty 1.1.0 has no Linux prebuilds, so the installer adds build-essential + python3.
|
||||
|
||||
- [2026-11-16] **Settings (#10):** browser setup consumes private setup-token; cookies are bound to the password hash, and sign-out-all atomically rotates the persisted secret. Browser auth mutations serialize and close active WebSockets.
|
||||
- [2026-11-16] **Notebook management (#9):** a shared mutation queue serializes saves/create/move/duplicate/delete. Exclusive hard-link publication prevents target replacement; saves use temp+rename. The recursive watcher updates lists; deleted open drafts are retained. Frontmatter helpers use YAML document nodes.
|
||||
- [2026-11-16] **Host credentials (#7):** write-only AES-256-GCM files under dataDir, host-name AAD; shared SSH connect selects per-host password/key. ssh2 1.17.0 has no client user-certificate pairing API. Hosts plugin owns management routes and preserves inventory comments/version checks.
|
||||
- [2026-11-16] **Deploy/update:** host one-liner `bootstrap.sh` (temp dir, nothing left on host); `install.sh` is install-or-update; root-owned `shellbook-update` fetches the installer over HTTPS because root must never run code from the service-user-writable `/opt/shellbook`.
|
||||
- [2026-11-16] **Chained notebooks (#11):** `::use` is flattened in core (`composeNotebook`): alias-prefixed params/ids/captures with `scope`, so render/run keep one notebook model and one substitution path. Server loads files and injects builtins (`shellbook.*`, server-only); `:::when` gates display and execution; `::host` adds to Hosts via the host-management API. Required params/secrets gate only their own scope, identically in core render and server `prepareRun`.
|
||||
- [2026-11-16] **Template delivery:** `install.sh` offers each shipped notebook template once (`/etc/shellbook/templates-offered`), copied as the service user, never overwriting or restoring deleted files.
|
||||
- [2026-11-16] **Web UI shell (#12):** top bar (tabs, live state, Chat/Terminal), notebook sidebar only on Notebooks, parameter panel beside the notebook via a container query (above it when narrow), dialogs/menus from `ui.tsx`. Page and notebook live in the URL hash (`route.ts`); typed non-secret values are remembered per notebook in localStorage (`paramMemory.ts`, secrets and undeclared names are dropped on read and write).
|
||||
- [2026-11-16] **Collapsible parameters (#13):** the form and each included group collapse (remembered via `uiPrefs.ts`). Collapsed, only missing required values and values changed from their default are listed as chips; untouched defaults are just counted, so the bar stays one line.
|
||||
- [2026-11-16] **Icon (#14):** `apps/web/public/shellbook.svg` (mint notebook with `>_` on a dark tile) is the single source for favicon, top bar, sign-in, setup and README. The PNGs (192, 512, 180 apple-touch on a full dark square) are rendered from it with headless Edge; give the SVG fixed px sizes, since headless Edge enforces a minimum viewport width and `100vw` overshoots.
|
||||
- [2026-11-16] **Self-update from Settings (#15):** the unprivileged service only writes `<data>/update-request`; root-owned `shellbook-update.path` (PathChanged) starts oneshot `shellbook-update.service` → fixed `/usr/local/sbin/shellbook-update`, output to `/var/log/shellbook-update.log`. Server reads `systemctl show --timestamp=unix` + log tail; UI polls through the restart and ignores runs that started before the request. Installs predating #15 need one CLI `shellbook-update` to get the units.
|
||||
- [2026-11-16] **Guided text and groups (#16):** `::param{name=x}` places a parameter's input in the text (same value as the panel); `:::group{title collapsed}` is a presentational container that never gates. Core `groupInputs` gives its outline status (missing=orange, filled=green, optional/none=grey) from its fields, the params its steps/hosts reference and, for `::use` sections, the included params. Collapse state is per `path:title` in localStorage.
|
||||
- [2026-11-16] **Step gating = values used (#16):** a step needs only its referenced params/runtime values, the required secrets its script reads (`$NAME`/`${NAME}`) and valid set secrets of its scope (all go to env). Unused required params no longer block it, so guided notebooks run step 1 before later values exist. `renderStep` is the only gate; server `prepareRun` dropped its scope-wide check.
|
||||
|
||||
## Archive
|
||||
|
||||
@@ -3,5 +3,7 @@
|
||||
- [2026-11-15] **Approach:** marimo in LXC 501 + Fabric/asyncssh helpers, Claude via marimo's ACP agent panel. **Outcome:** ACP panel superseded by marimo pair; sidebar chat is API-key only. **Now:** dropped.
|
||||
- [2026-11-15] **Approach:** marimo pair (Claude Code CLI in terminal) writing Python notebooks. **Outcome:** worked technically, but notebooks became Python wrappers; commands not readable/copyable, chat only in bottom terminal. **Now:** custom app (ShellBook) with shell-first format.
|
||||
- [2026-11-16] **Approach:** 5 parallel Codex agents in worktrees (core/server/web/terminal/auth) against fixed contracts, orchestrator merges. **Outcome:** worked; conflicts only in app.ts, server package.json, lockfile (regenerate with pnpm install). Integration bugs surfaced only across branches (event order, env var names, auth vs. other tests). **Now:** keep contracts-first + integration test after merge.
|
||||
- [2026-11-16] **Approach:** first spec delivered config-file-driven host setup (hosts.yaml) and terminal-only Claude. **Outcome:** user expected everything from the UI (servers, passwords/keys, chat, notebook management, setup). **Now:** UI-first invariant in AGENTS.md; #7–#10 delivered via 4 parallel Codex delegates + orchestrator review fixes.
|
||||
- [2026-11-16] **Approach:** reuse old marimo CT 501 for ShellBook, keeping the existing `claude` login (scratch `reuse-ct.sh`: snapshot `pre-shellbook`, copy ~/.claude to shellbook user). **Outcome:** two deploy bugs (TUN dev0 conflict, PATH/uid in pct exec) fixed in df489fa/4fe7e4e. **Now:** rerun update on CT 501.
|
||||
|
||||
## Archive
|
||||
|
||||
@@ -7,4 +7,17 @@
|
||||
- [2026-11-16] **Env names:** single data dir variable is `SHELLBOOK_DATA_DIR` (server config, auth, CLI, installer). SSH key: `SHELLBOOK_SSH_KEY`.
|
||||
- [2026-11-16] **Exit codes vs errors:** a non-zero script exit is a normal result (check ❌) and goes only in run.finished; run.error is for transport/setup failures.
|
||||
|
||||
- [2026-11-16] **Notebook root symlinks (#9):** validating only child components after realpath(root) permits a symlinked notebooks root. Notebook reads and mutations validate the root itself before walking children; regression-covered. Workspace CLI/filesystem writers remain trusted against concurrent path swaps.
|
||||
- [2026-11-16] **Chat CLI permissions (#8):** allowedTools only auto-approves; tools + restricted mode (2.1.248+) enforce the file/tool boundary. Synthetic fixture tests never invoke the real CLI; deployment must verify installed-version/login compatibility.
|
||||
- [2026-11-16] **`pct exec` PATH** is `/sbin:/bin:/usr/sbin:/usr/bin` (no /usr/local/bin) and root `tar` keeps archive uids; install/update scripts set PATH and use `tar --no-same-owner`. Deploy tests in `deploy/test/`.
|
||||
- [2026-11-16] **CT TUN passthrough:** a CT with manual `lxc.mount.entry` for /dev/net/tun fails to start if `devN: /dev/net/tun` is added too (autodev hook status 17); `ct-config.sh has_tun_passthrough` detects both forms.
|
||||
- [2026-11-16] **Path conventions:** web/API notebook paths are relative to `notebooks/`; chat protocol paths are workspace-relative (`notebooks/...`). Convert at the ChatPanel boundary.
|
||||
- [2026-11-16] **Watcher timing tests:** full parallel test run on Windows delays fs events >100 ms; keep watcher test debounce/quiet windows generous.
|
||||
- [2026-11-16] **HTTP errors:** server httpError messages (4xx/502/503) are user-facing and shown by the web client; 500 messages are not. Keep 4xx/502 messages free of secrets.
|
||||
- [2026-11-16] **CJS named imports in the bundle:** `import { utils } from "ssh2"` passes Vitest but crashes `node dist/main.js`; import CommonJS packages via default export. `test/bundle.test.ts` starts the real bundle.
|
||||
- [2026-11-16] **Capture defaults (resolved by #16):** a required param waiting for a capture of its own notebook used to block the step producing it. Since steps are gated only by values they use, this only bites if the producing step references that param.
|
||||
- [2026-11-16] **Bash tool heredocs with apostrophes fail** in this harness ("unexpected EOF"); write scripts to the scratchpad and run them instead.
|
||||
- [2026-11-16] **Commas in YAML flow-mapping labels:** `{ label: Key (optional, else x) }` splits at the comma into a valueless key; quote such values. The parser now says so at the parameter line.
|
||||
- [2026-11-16] **Stopping a background dev server task leaves its Node child running** on Windows (ports 8080/5173 stay taken); reuse it or kill the process.
|
||||
|
||||
## Archive
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
> Always-loaded. Everything else is on-demand. Update TOC when files change.
|
||||
|
||||
## Current Focus
|
||||
- [2026-11-16] M0–M3 done and closed (#1–#4); M4 (#5) and M5 (#6) code merged, issues open pending Linux verification.
|
||||
- [2026-11-16] Next: first deploy to CT 501 (deploy/README.md), then verify tmux + `claude` live-reload loop there and close #5/#6.
|
||||
- [2026-11-16] M0–M3 (#1–#4), UI-first follow-ups (#7–#10) and chained notebooks (#11: when/use/host, LXC + web-server templates) the UI/UX overhaul (#12) and collapsible parameters (#13) the app icon (#14) self-update from Settings (#15) and guided text with groups (#16) closed.
|
||||
- [2026-11-16] Open: #5/#6 need a real CT 501 deploy (bootstrap.sh one-liner, setup token, real SSH run, tmux terminal). Not yet verified in a real browser or against real OpenSSH.
|
||||
|
||||
## Invariants
|
||||
- Displayed script == executed script (one substitution path).
|
||||
@@ -12,9 +12,10 @@
|
||||
- Strict SSH host key checking with explicit TOFU.
|
||||
- `check` steps are side-effect free.
|
||||
- Notebooks stay plain, readable Markdown.
|
||||
- Everything doable from the web UI; files are storage, not the only way in.
|
||||
|
||||
## Table of Contents
|
||||
- `architecture.md` — 7 entries — why custom app, stack, AI integration, workspace split
|
||||
- `attempts.md` — 2 entries — marimo + marimo-pair trial and why it was dropped
|
||||
- `open.md` — 2 entries — open design questions
|
||||
- `gotchas.md` — 5 entries — integration foot-guns (CRLF scripts, host-key event order, tmux vs systemd, env names)
|
||||
- `architecture.md` — 19 entries — why custom app, stack, AI integration, workspace split, deploy/update, chained notebooks, template delivery, web UI shell, collapsible params, app icon, UI self-update, groups/inline fields, step gating by used values
|
||||
- `attempts.md` — 4 entries — marimo + marimo-pair trial and why it was dropped
|
||||
- `open.md` — 2 entries — open design questions (sudo password, chat history)
|
||||
- `gotchas.md` — 17 entries — integration foot-guns (CRLF, host-key events, tmux/systemd, env names, pct exec PATH, TUN, chat paths, watcher timing, capture defaults, heredocs, YAML flow commas, orphaned dev servers)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Open Questions
|
||||
|
||||
- [2026-11-15] Optional chat-style UI (stream-json headless `claude`) in addition to the terminal? Would bill to the Agent SDK credit on subscriptions — decide after M4.
|
||||
- [2026-11-16] Chat panel stores only conversation titles + CLI session ids; restore message history after reload (from CLI transcripts) or keep it ephemeral?
|
||||
- [2026-11-15] sudo with password (`type: secret` + `sudo -S`) or require NOPASSWD sudo only? Spec v0.1: `sudo -n` only.
|
||||
|
||||
## Archive
|
||||
|
||||
@@ -6,3 +6,4 @@ coverage/
|
||||
.env.*
|
||||
# runtime data when running from the repo
|
||||
data/
|
||||
apps/server/.bundle-test-*/
|
||||
|
||||
@@ -10,6 +10,10 @@ hosts over SSH. Spec: `docs/spec.md` — read it before any design change.
|
||||
|
||||
## Invariants
|
||||
|
||||
- **Everything is doable from the web UI**: servers and their SSH passwords/keys,
|
||||
notebooks, chatting with Claude, setup and password. Files (hosts.yaml, Markdown,
|
||||
git) remain the storage format, never the only way in.
|
||||
|
||||
- **The displayed script is the executed script.** Rendering and execution use the same
|
||||
substitution result; never build a second, hidden command string.
|
||||
- **All shell quoting goes through `packages/core` `shellQuote`.** No ad-hoc escaping anywhere.
|
||||
@@ -18,8 +22,9 @@ hosts over SSH. Spec: `docs/spec.md` — read it before any design change.
|
||||
- **Strict SSH host key checking.** Unknown keys require explicit user confirmation (TOFU).
|
||||
- **`check` steps must be side-effect free**; only `run` steps change hosts.
|
||||
- Notebooks stay valid, readable Markdown in any renderer (Gitea/GitHub).
|
||||
- AI integration uses the real Claude Code CLI in a terminal (user's own login). No
|
||||
embedding of subscription credentials, no SDK-based chat on subscription auth.
|
||||
- AI integration uses the real `claude` CLI with the user's own login: interactively
|
||||
in the terminal panel or headless (`-p`, stream-json) behind the chat panel. No
|
||||
embedding of subscription credentials, API-key requirement, or SDK-based chat.
|
||||
|
||||
## Stack and layout
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
<img src="apps/web/public/shellbook.svg" alt="" width="72" height="72">
|
||||
|
||||
# ShellBook
|
||||
|
||||
Notebook-style runbooks for Linux servers.
|
||||
@@ -8,4 +10,32 @@ Notebook-style runbooks for Linux servers.
|
||||
- Steps can produce files that appear as downloads, and reveal follow-up notes.
|
||||
- Claude Code (the real CLI) runs in a built-in terminal panel and edits notebooks live.
|
||||
|
||||
Status: design phase. See [docs/spec.md](docs/spec.md).
|
||||
Host and SSH credential management is available from **Servers & SSH** in the sidebar. See [docs/spec.md](docs/spec.md).
|
||||
|
||||
|
||||
## Manage servers in the browser
|
||||
|
||||
Open **Servers & SSH** to add, edit (including rename), or delete a server. Address
|
||||
accepts a hostname, IPv4 or IPv6; port defaults to 22. Tags remain in `hosts.yaml`.
|
||||
Disk edits reload live; stale edits return a conflict. Reload hosts explicitly to
|
||||
start again from the latest inventory.
|
||||
|
||||
Select **SSH credentials** for a host to choose the ShellBook key, a password, or a
|
||||
pasted/uploaded private key with an optional passphrase. Credentials are write-only:
|
||||
the browser sees their type, key fingerprint and save time, never saved secrets.
|
||||
Selecting ShellBook key removes the saved password/private key. OpenSSH user
|
||||
certificates are unavailable with ssh2 1.17.0 (no client certificate pairing API).
|
||||
|
||||
**Test connection** verifies SSH authentication with the same strict host-key
|
||||
confirmation as runbook execution. **Install ShellBook key** requires a saved
|
||||
password and previews the exact idempotent authorized_keys script before execution.
|
||||
After success, choose ShellBook key to remove the stored password. **Forget host
|
||||
key** asks for confirmation; the next connection requires fingerprint verification.
|
||||
The page also displays ShellBook's public key with a Copy button.
|
||||
|
||||
Secrets are AES-256-GCM encrypted in `SHELLBOOK_DATA_DIR/ssh-credentials/`; the
|
||||
random encryption key is `SHELLBOOK_DATA_DIR/ssh-credentials.key`. Both key and
|
||||
credential files use mode 0600 on POSIX. Keep this data directory outside the git
|
||||
workspace, back it up securely, and restore the key together with the ciphertext.
|
||||
Windows does not implement POSIX file modes; use an appropriately restricted data
|
||||
directory ACL there. Never put these files into the workspace repository.
|
||||
|
||||
@@ -94,3 +94,29 @@ uploads, and capture/runtime rendering without bash. The full shipped `ssh-key.m
|
||||
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.
|
||||
|
||||
+14
-3
@@ -1,3 +1,5 @@
|
||||
import { registerSettings } from "./settings";
|
||||
import { builtinValues, hostsPlugin } from "./hosts";
|
||||
import Fastify, { type FastifyInstance } from "fastify";
|
||||
import websocket from "@fastify/websocket";
|
||||
import { loadConfig, type ServerConfig } from "./config";
|
||||
@@ -7,6 +9,8 @@ import { terminalPlugin, type TerminalOptions } from "./terminal";
|
||||
import { createNotebookWatcher } from "./watch";
|
||||
import { registerAuth, type AuthOptions } from "./auth";
|
||||
import { registerStatic } from "./static";
|
||||
import { chatPlugin } from "./chat";
|
||||
import { defaultUpdateOptions, registerUpdate, type UpdateOptions } from "./update";
|
||||
|
||||
export interface AppOptions {
|
||||
logger?: boolean;
|
||||
@@ -23,6 +27,8 @@ export interface AppOptions {
|
||||
/** Watch workspace notebooks and publish file.changed/file.deleted on /api/events. */
|
||||
watchNotebooks?: boolean;
|
||||
terminal?: Omit<TerminalOptions, "workspaceDir">;
|
||||
/** Overrides for the self-update trigger (tests). */
|
||||
update?: Partial<UpdateOptions>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -30,17 +36,22 @@ export interface AppOptions {
|
||||
* src/auth/ login, persistent session secret (registered first: its hook guards every /api route)
|
||||
* src/workspace/ notebooks, hosts.yaml; src/ssh/, src/runs/ queue, audit, artifacts, /api/events
|
||||
* src/terminal/ node-pty + tmux, /api/terminal; src/watch/ file.changed events into the events hub
|
||||
* src/static/ built web app with SPA fallback
|
||||
* src/static/ built web app with SPA fallback; src/update/ self-update trigger (root runs it via systemd)
|
||||
*/
|
||||
export async function buildApp(options: AppOptions = {}): Promise<FastifyInstance> {
|
||||
const config = loadConfig(options.config);
|
||||
const hub = options.events ?? new EventsHub();
|
||||
const app = Fastify({ logger: options.logger ?? false, trustProxy: options.trustProxy ?? false });
|
||||
if (options.auth !== false) await registerAuth(app, { dataDir: config.dataDir, ...options.auth });
|
||||
await registerSettings(app, config);
|
||||
await registerUpdate(app, { ...defaultUpdateOptions(config.dataDir), ...options.update });
|
||||
await app.register(websocket);
|
||||
await app.register(workspacePlugin, { config });
|
||||
await app.register(runsPlugin, { config, hub });
|
||||
const builtins = () => builtinValues(config);
|
||||
await app.register(workspacePlugin, { config, builtins });
|
||||
await app.register(hostsPlugin, { config });
|
||||
await app.register(runsPlugin, { config, hub, builtins });
|
||||
await app.register(terminalPlugin, { ...options.terminal, workspaceDir: config.workspaceDir });
|
||||
await app.register(chatPlugin, { config });
|
||||
|
||||
if (options.watchNotebooks) {
|
||||
const watcher = createNotebookWatcher(config.workspaceDir, {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { createHmac } from "node:crypto";
|
||||
import { ensureSetupToken, matchesSetupToken, removeSetupToken, setupTokenPath, validNewPassword } from "./setup";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { readPasswordHash, verifyPassword } from "./credentials";
|
||||
import { loadSessionSecret, signSession, verifySession } from "./session";
|
||||
import { readPasswordHash, verifyPassword, setPassword } from "./credentials";
|
||||
import { loadSessionSecret, signSession, verifySession, rotateSessionSecret } from "./session";
|
||||
|
||||
export interface AuthOptions {
|
||||
dataDir: string;
|
||||
@@ -12,7 +14,17 @@ export interface AuthOptions {
|
||||
}
|
||||
const normalizeIp = (ip: string) => ip.replace(/^::ffff:/, "");
|
||||
export async function registerAuth(app: FastifyInstance, options: AuthOptions): Promise<void> {
|
||||
const secret = loadSessionSecret(options.dataDir);
|
||||
let secret = loadSessionSecret(options.dataDir);
|
||||
if (!await readPasswordHash(options.dataDir)) {
|
||||
await ensureSetupToken(options.dataDir);
|
||||
app.log.warn(`Set up ShellBook in the browser; read the one-time token at ${setupTokenPath(options.dataDir)}`);
|
||||
} else await removeSetupToken(options.dataDir);
|
||||
// Binding to the persisted hash also revokes sessions after CLI password changes.
|
||||
const sessionKey = async () => createHmac("sha256", secret).update(await readPasswordHash(options.dataDir) ?? "unconfigured").digest();
|
||||
let mutation: Promise<unknown> = Promise.resolve();
|
||||
const exclusive = <T,>(action: () => Promise<T>): Promise<T> => {
|
||||
const next = mutation.then(action); mutation = next.catch(() => {}); return next;
|
||||
};
|
||||
const maxAge = options.sessionMaxAgeSeconds ?? 30 * 86400;
|
||||
if (!Number.isSafeInteger(maxAge) || maxAge <= 0) throw new Error("Invalid session lifetime");
|
||||
const failures = new Map<string, { count: number; until: number }>();
|
||||
@@ -27,7 +39,7 @@ export async function registerAuth(app: FastifyInstance, options: AuthOptions):
|
||||
try { if (new URL(origin).host !== request.headers.host) return reply.code(403).send({ error: "Origin rejected" }); }
|
||||
catch { return reply.code(403).send({ error: "Origin rejected" }); }
|
||||
}
|
||||
if (path === "/api/health" || path === "/api/auth/login") return;
|
||||
if (path === "/api/health" || path === "/api/auth/login" || path === "/api/auth/setup") return;
|
||||
const forward = options.forwardAuth;
|
||||
const peer = normalizeIp(request.raw.socket?.remoteAddress ?? "");
|
||||
if (forward && forward.trustedProxyIps.some(ip => normalizeIp(ip) === peer)) {
|
||||
@@ -35,24 +47,60 @@ export async function registerAuth(app: FastifyInstance, options: AuthOptions):
|
||||
if (typeof user === "string" && user.trim()) return;
|
||||
}
|
||||
const token = request.headers.cookie?.split(";").map(part => part.trim()).find(part => part.startsWith("shellbook_session="))?.slice("shellbook_session=".length);
|
||||
if (!token || !verifySession(secret, token)) return reply.code(401).send({ error: "Authentication required" });
|
||||
if (!token || !verifySession(await sessionKey(), token)) return reply.code(401).send({ error: "Authentication required" });
|
||||
});
|
||||
app.post("/api/auth/login", { bodyLimit: 8192 }, async (request, reply) => {
|
||||
function reserveAttempt(ip: string, reply: import("fastify").FastifyReply) {
|
||||
const now = Date.now();
|
||||
for (const [key, value] of failures) if (value.until <= now) failures.delete(key);
|
||||
const ip = request.ip;
|
||||
|
||||
const entry = failures.get(ip);
|
||||
if ((entry?.count ?? 0) >= (options.maxAttempts ?? 5) || (!entry && failures.size >= 10000)) {
|
||||
return reply.header("Retry-After", String(Math.max(1, Math.ceil(((entry?.until ?? now + 60000) - now) / 1000)))).code(429).send({ error: "Try again later" });
|
||||
}
|
||||
// Reserve before scrypt awaits, so parallel attempts cannot bypass the limit.
|
||||
failures.set(ip, { count: (entry?.count ?? 0) + 1, until: entry?.until ?? now + (options.rateWindowMs ?? 60000) });
|
||||
return undefined;
|
||||
}
|
||||
const freshCookie = async (secure: boolean) => cookie(signSession(await sessionKey(), Date.now() + maxAge * 1000), secure, maxAge);
|
||||
app.get("/api/auth/setup", async (_request, reply) => reply.header("Cache-Control", "no-store").send({ required: !await readPasswordHash(options.dataDir) }));
|
||||
app.post("/api/auth/setup", { bodyLimit: 16384 }, async (request, reply) => exclusive(async () => {
|
||||
if (await readPasswordHash(options.dataDir)) return reply.code(409).send({ error: "Already configured" });
|
||||
const limited = reserveAttempt(request.ip, reply); if (limited) return limited;
|
||||
const body = request.body as { token?: unknown; newPassword?: unknown; confirmPassword?: unknown } | null;
|
||||
if (!await matchesSetupToken(options.dataDir, body?.token)) return reply.code(401).send({ error: "Invalid setup token" });
|
||||
if (!validNewPassword(body?.newPassword) || body.newPassword !== body.confirmPassword) return reply.code(400).send({ error: "Passwords must match and contain at least 12 characters (maximum 4096 bytes)" });
|
||||
await setPassword(options.dataDir, body.newPassword);
|
||||
await removeSetupToken(options.dataDir);
|
||||
failures.delete(request.ip);
|
||||
return reply.header("Set-Cookie", await freshCookie(request.protocol === "https")).code(204).send();
|
||||
}));
|
||||
app.post("/api/settings/password", { bodyLimit: 16384 }, async (request, reply) => exclusive(async () => {
|
||||
const limited = reserveAttempt(request.ip, reply); if (limited) return limited;
|
||||
const body = request.body as { currentPassword?: unknown; newPassword?: unknown; confirmPassword?: unknown } | null;
|
||||
const hash = await readPasswordHash(options.dataDir);
|
||||
if (typeof body?.currentPassword !== "string" || !hash || !await verifyPassword(body.currentPassword, hash)) return reply.code(401).send({ error: "Invalid current password" });
|
||||
if (!validNewPassword(body.newPassword) || body.newPassword !== body.confirmPassword) return reply.code(400).send({ error: "Passwords must match and contain at least 12 characters (maximum 4096 bytes)" });
|
||||
await setPassword(options.dataDir, body.newPassword);
|
||||
app.websocketServer?.clients.forEach(socket => socket.close(1008, "Sessions revoked"));
|
||||
failures.delete(request.ip);
|
||||
return reply.header("Set-Cookie", await freshCookie(request.protocol === "https")).code(204).send();
|
||||
}));
|
||||
app.post("/api/settings/sessions/revoke", async (request, reply) => exclusive(async () => {
|
||||
secret = rotateSessionSecret(options.dataDir);
|
||||
app.websocketServer?.clients.forEach(socket => socket.close(1008, "Sessions revoked"));
|
||||
return reply.header("Set-Cookie", await freshCookie(request.protocol === "https")).code(204).send();
|
||||
}));
|
||||
app.get("/api/settings/session", async () => ({ lifetimeSeconds: maxAge }));
|
||||
app.post("/api/auth/login", { bodyLimit: 8192 }, async (request, reply) => exclusive(async () => {
|
||||
const limited = reserveAttempt(request.ip, reply);
|
||||
if (limited) return limited;
|
||||
const now = Date.now();
|
||||
const password = (request.body as { password?: unknown } | null)?.password;
|
||||
const hash = await readPasswordHash(options.dataDir);
|
||||
if (typeof password !== "string" || !hash || !await verifyPassword(password, hash)) return reply.code(401).send({ error: "Invalid credentials" });
|
||||
failures.delete(ip);
|
||||
return reply.header("Cache-Control", "no-store").header("Set-Cookie", cookie(signSession(secret, now + maxAge * 1000), request.protocol === "https", maxAge)).code(204).send();
|
||||
});
|
||||
failures.delete(request.ip);
|
||||
return reply.header("Cache-Control", "no-store").header("Set-Cookie", cookie(signSession(await sessionKey(), now + maxAge * 1000), request.protocol === "https", maxAge)).code(204).send();
|
||||
}));
|
||||
app.post("/api/auth/logout", async (request, reply) => reply.header("Set-Cookie", cookie("", request.protocol === "https", 0)).code(204).send());
|
||||
app.get("/api/auth/me", async (_request, reply) => reply.header("Cache-Control", "no-store").send({ authenticated: true }));
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import { mkdirSync, readFileSync, writeFileSync, chmodSync } from "node:fs";
|
||||
import { mkdirSync, readFileSync, writeFileSync, chmodSync, renameSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
export function loadSessionSecret(dataDir: string): Buffer {
|
||||
@@ -22,3 +22,12 @@ export function verifySession(secret: Buffer, cookie: string, now = Date.now()):
|
||||
const expected = signSession(secret, Number(payload)).split(".")[1]!;
|
||||
return Number(payload) > now && timingSafeEqual(Buffer.from(mac!), Buffer.from(expected));
|
||||
}
|
||||
|
||||
/** Replace before publishing the new key to request handlers. */
|
||||
export function rotateSessionSecret(dataDir: string): Buffer {
|
||||
const secret = randomBytes(32);
|
||||
const temp = join(dataDir, `session-secret.${randomBytes(8).toString("hex")}.tmp`);
|
||||
writeFileSync(temp, secret, { mode: 0o600, flag: "wx" });
|
||||
renameSync(temp, join(dataDir, "session-secret"));
|
||||
return secret;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { randomBytes, createHash, timingSafeEqual } from "node:crypto";
|
||||
import { chmod, readFile, writeFile, unlink } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
export const setupTokenPath = (dataDir: string) => join(dataDir, "setup-token");
|
||||
export async function ensureSetupToken(dataDir: string): Promise<void> {
|
||||
const path = setupTokenPath(dataDir);
|
||||
try {
|
||||
await writeFile(path, randomBytes(32).toString("hex") + "\n", {
|
||||
flag: "wx",
|
||||
mode: 0o600,
|
||||
});
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
||||
}
|
||||
await chmod(path, 0o600);
|
||||
}
|
||||
export async function matchesSetupToken(
|
||||
dataDir: string,
|
||||
candidate: unknown,
|
||||
): Promise<boolean> {
|
||||
if (typeof candidate !== "string" || candidate.length > 4096) return false;
|
||||
try {
|
||||
const expected = (await readFile(setupTokenPath(dataDir), "utf8")).trim();
|
||||
const digest = (value: string) =>
|
||||
createHash("sha256").update(value).digest();
|
||||
return timingSafeEqual(digest(candidate), digest(expected));
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
export async function removeSetupToken(dataDir: string): Promise<void> {
|
||||
await unlink(setupTokenPath(dataDir)).catch((error) => {
|
||||
if (error.code !== "ENOENT") throw error;
|
||||
});
|
||||
}
|
||||
export function validNewPassword(value: unknown): value is string {
|
||||
return (
|
||||
typeof value === "string" &&
|
||||
value.length >= 12 &&
|
||||
Buffer.byteLength(value) <= 4096
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
# Chat transport and CLI contract (#8)
|
||||
|
||||
`/api/chat` is a dedicated JSON WebSocket protected by the existing auth and
|
||||
same-origin hook. Run events remain on `/api/events`. The socket owns its turn:
|
||||
disconnect, server shutdown, Stop, a five-minute timeout, malformed CLI output,
|
||||
or resource overflow terminates the child (SIGTERM, then SIGKILL after 1.5s).
|
||||
One turn per conversation, one per socket, at most four processes globally.
|
||||
The lock lasts until process close. Output is capped at 4 MiB per turn, records
|
||||
at 1 MiB, stderr at 8 KiB and outgoing socket buffering at 1 MiB.
|
||||
|
||||
Client frames: `send` with `message` (1–32000 characters), optional
|
||||
`conversationId`, optional workspace-relative `notebookPath`, and required
|
||||
`allowShell` boolean; or `cancel`. Server frames: `history`, `conversation`,
|
||||
`delta`, `tool` (name and optional notebook path only), `finished` (optional
|
||||
cancelled/costUsd/durationMs), and `error` (code and safe message). See core's
|
||||
additive Chat section. Tool activity describes requested operations, not proof
|
||||
that an edit succeeded. The existing watcher reloads actual changed files.
|
||||
|
||||
The data directory stores only a private, atomically replaced index of up to
|
||||
100 conversations: ID, first-message title (120 characters), CLI session ID,
|
||||
creation and update timestamps. Old inactive entries are evicted first.
|
||||
Shell permission is per-turn and never persisted. Messages/tool contents are
|
||||
not stored by ShellBook; Claude retains its own session files for `--resume`.
|
||||
The browser caches messages only while this panel is mounted. Do not enter
|
||||
secrets in chat: conversation titles and the CLI's own transcripts persist.
|
||||
|
||||
Verified against the official CLI reference and headless guide on 2026-11-16:
|
||||
- https://code.claude.com/docs/en/cli-reference
|
||||
- https://code.claude.com/docs/en/headless
|
||||
|
||||
Exact base argv: `-p --output-format stream-json --input-format stream-json
|
||||
--verbose --include-partial-messages --restricted --strict-mcp-config
|
||||
--disallowedTools mcp__* --tools Read,Glob,Grep,Edit,Write,MultiEdit
|
||||
--allowedTools Read,Glob,Grep,Edit,Write,MultiEdit --permission-mode acceptEdits
|
||||
--append-system-prompt <ShellBook context>`. Add `,Bash` to both tool lists only
|
||||
when the toggle is enabled; append `--resume <session_id>` on follow-ups.
|
||||
`--allowedTools` auto-approves; `--tools` actually restricts built-ins.
|
||||
`--restricted` confines file tools to working directories and ignores user/project
|
||||
settings (requires Claude Code **2.1.248+**). MCP is disabled. No bypass mode.
|
||||
Restricted mode still reads workspace CLAUDE.md. Unlike `--bare`, this preserves
|
||||
subscription authentication. The default CLI environment is inherited; no auth
|
||||
files or tokens are read or copied by ShellBook. Unsupported flags fail closed.
|
||||
Optional Bash has service-user authority; this toggle is not an OS sandbox.
|
||||
|
||||
The user prompt is a single newline-delimited user JSON record on stdin; never
|
||||
part of argv or a shell string. Init/result session IDs enable explicit resume.
|
||||
Only text deltas are rendered (assistant snapshots would duplicate them).
|
||||
Result errors and bounded stderr detect missing login without forwarding raw
|
||||
records or environment details. Cost is a CLI estimate and can be cumulative
|
||||
across a resumed session. Terminal recovery says to run `claude`, then `/login`.
|
||||
|
||||
Tests use a synthetic captured-format JSONL fixture and a small Node executable
|
||||
fixture, invoked through Node for portable Windows execution, including a fake
|
||||
`claude` launcher resolved through PATH (no real CLI or credentials).
|
||||
The fixture is representative protocol data, not a live recording.
|
||||
Real installed CLI compatibility, subscription login, Linux process trees and
|
||||
the visual layout still need deployment verification.
|
||||
@@ -0,0 +1,50 @@
|
||||
import type { ChatEvent } from "@shellbook/core";
|
||||
import { isAbsolute, relative, resolve } from "node:path";
|
||||
|
||||
export function notebookPath(value: unknown): value is string {
|
||||
return typeof value === "string" && /^notebooks\/(?:[^/\\\x00-\x1f]+\/)*[^/\\\x00-\x1f]+\.md$/.test(value)
|
||||
&& !value.split("/").some(part => part === "." || part === "..");
|
||||
}
|
||||
|
||||
export function buildClaudeArgs(options: { sessionId?: string; notebookPath?: string; allowShell: boolean }): string[] {
|
||||
const tools = "Read,Glob,Grep,Edit,Write,MultiEdit" + (options.allowShell ? ",Bash" : "");
|
||||
const args = ["-p", "--output-format", "stream-json", "--input-format", "stream-json", "--verbose",
|
||||
"--include-partial-messages", "--restricted", "--strict-mcp-config", "--disallowedTools", "mcp__*",
|
||||
"--tools", tools, "--allowedTools", tools, "--permission-mode", "acceptEdits",
|
||||
"--append-system-prompt", `You are inside ShellBook. Follow the workspace CLAUDE.md notebook format. Write notebooks in notebooks/**/*.md. Never include secrets in notebooks or responses. Open notebook: ${options.notebookPath ?? "none"}.`];
|
||||
if (options.sessionId) args.push("--resume", options.sessionId);
|
||||
return args;
|
||||
}
|
||||
|
||||
export type ParsedEvent = ChatEvent | { type: "session"; sessionId: string };
|
||||
const loginPattern = /not logged in|please (?:run|use).*\/login|authentication[_ ](?:error|required)|invalid.*(?:api key|oauth)|login required|failed to authenticate/i;
|
||||
export const needsLogin = (text: string) => loginPattern.test(text);
|
||||
|
||||
/** Whitelist fields: never forward full CLI records, tool inputs, or stderr. */
|
||||
export function parseClaudeLine(line: string, workspace: string): ParsedEvent[] {
|
||||
const m = JSON.parse(line);
|
||||
if (!m || typeof m !== "object") throw new Error("Invalid CLI record");
|
||||
const result: ParsedEvent[] = [];
|
||||
if (typeof m.session_id === "string" && /^[a-zA-Z0-9-]{1,128}$/.test(m.session_id)) result.push({ type: "session", sessionId: m.session_id });
|
||||
if (m.type === "stream_event" && m.event?.type === "content_block_delta" && m.event.delta?.type === "text_delta" && typeof m.event.delta.text === "string") {
|
||||
result.push({ type: "delta", text: m.event.delta.text });
|
||||
}
|
||||
if (m.type === "assistant" && Array.isArray(m.message?.content)) {
|
||||
for (const block of m.message.content) {
|
||||
if (block.type !== "tool_use" || typeof block.name !== "string") continue;
|
||||
let target: string | undefined;
|
||||
const file = block.input?.file_path ?? block.input?.path;
|
||||
if (typeof file === "string") {
|
||||
const local = relative(workspace, resolve(workspace, file)).replaceAll("\\", "/");
|
||||
if (!isAbsolute(local) && !local.startsWith("../") && notebookPath(local)) target = local;
|
||||
}
|
||||
result.push({ type: "tool", name: block.name.slice(0, 80), ...(target ? { path: target } : {}) });
|
||||
}
|
||||
}
|
||||
if (m.type === "result") {
|
||||
if (m.is_error || m.subtype !== "success") {
|
||||
result.push({ type: "error", code: needsLogin(JSON.stringify(m)) ? "login" : "cli", message: needsLogin(JSON.stringify(m)) ? "Claude needs a login. Open Terminal, run claude, then /login." : "Claude could not complete this turn." });
|
||||
} else result.push({ type: "finished", ...(typeof m.total_cost_usd === "number" ? { costUsd: m.total_cost_usd } : {}), ...(typeof m.duration_ms === "number" ? { durationMs: m.duration_ms } : {}) });
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { FastifyPluginAsync } from "fastify";
|
||||
import type { ChatClientMessage, ChatConversation, ChatEvent } from "@shellbook/core";
|
||||
import type { ServerConfig } from "../config";
|
||||
import { notebookPath } from "./cli";
|
||||
import { startTurn, type TurnOptions } from "./process";
|
||||
|
||||
export function parseChatMessage(text: string): ChatClientMessage | undefined {
|
||||
if (text.length > 70_000) return;
|
||||
let m; try { m = JSON.parse(text); } catch { return; }
|
||||
if (!m || typeof m !== "object") return;
|
||||
if (m.type === "cancel") return { type: "cancel" };
|
||||
if (m.type !== "send" || typeof m.message !== "string" || !m.message.trim() || m.message.length > 32_000
|
||||
|| typeof m.allowShell !== "boolean" || (m.notebookPath !== undefined && !notebookPath(m.notebookPath))
|
||||
|| (m.conversationId !== undefined && (typeof m.conversationId !== "string" || !/^[a-f0-9-]{36}$/.test(m.conversationId)))) return;
|
||||
return { type: "send", message: m.message, allowShell: m.allowShell, notebookPath: m.notebookPath, conversationId: m.conversationId };
|
||||
}
|
||||
|
||||
export const chatPlugin: FastifyPluginAsync<{ config: ServerConfig; processOptions?: Pick<TurnOptions, "executable" | "prefixArgs" | "timeoutMs"> }> = async (app, { config, processOptions }) => {
|
||||
mkdirSync(config.dataDir, { recursive: true, mode: 0o700 });
|
||||
const file = join(config.dataDir, "chat-conversations.json");
|
||||
let conversations: ChatConversation[] = [];
|
||||
try {
|
||||
const raw = readFileSync(file);
|
||||
if (raw.length > 512 * 1024) throw new Error("Conversation index exceeds limit");
|
||||
const saved = JSON.parse(raw.toString());
|
||||
if (!Array.isArray(saved) || saved.length > 100 || saved.some(c => !c || !/^[a-f0-9-]{36}$/.test(c.id)
|
||||
|| typeof c.title !== "string" || c.title.length > 120 || typeof c.createdAt !== "string" || typeof c.updatedAt !== "string"
|
||||
|| (c.sessionId !== undefined && !/^[a-zA-Z0-9-]{1,128}$/.test(c.sessionId)))) throw new Error("Invalid conversation index");
|
||||
conversations = saved;
|
||||
} catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw new Error("Cannot load chat conversation index"); }
|
||||
const save = () => {
|
||||
writeFileSync(file + ".tmp", JSON.stringify(conversations), { mode: 0o600 });
|
||||
renameSync(file + ".tmp", file);
|
||||
};
|
||||
const turns = new Map<string, ReturnType<typeof startTurn>>();
|
||||
app.addHook("onClose", async () => { for (const turn of turns.values()) turn.cancel(); await Promise.all([...turns.values()].map(t => t.done)); });
|
||||
app.get("/api/chat", { websocket: true }, socket => {
|
||||
let active: ReturnType<typeof startTurn> | undefined;
|
||||
const send = (event: ChatEvent) => {
|
||||
if (socket.readyState !== 1) return;
|
||||
if (socket.bufferedAmount > 1024 * 1024) { active?.cancel(); socket.close(1013, "Chat client too slow"); return; }
|
||||
socket.send(JSON.stringify(event), error => { if (error) active?.cancel(); });
|
||||
};
|
||||
send({ type: "history", conversations });
|
||||
socket.on("close", () => active?.cancel());
|
||||
socket.on("error", () => { active?.cancel(); socket.close(); });
|
||||
socket.on("message", (raw, binary) => {
|
||||
const m = binary ? undefined : parseChatMessage(raw.toString());
|
||||
if (!m) { send({ type: "error", code: "invalid", message: "Invalid chat message." }); return; }
|
||||
if (m.type === "cancel") { active?.cancel(); return; }
|
||||
if (active || (m.conversationId && turns.has(m.conversationId))) { send({ type: "error", code: "busy", message: "A turn is already running in this conversation." }); return; }
|
||||
// Bound total concurrent CLI processes, not only per-conversation use.
|
||||
if (turns.size >= 4) { send({ type: "error", code: "busy", message: "Chat is busy. Try again shortly." }); return; }
|
||||
let conversation = conversations.find(c => c.id === m.conversationId);
|
||||
if (m.conversationId && !conversation) { send({ type: "error", code: "invalid", message: "Conversation no longer exists." }); return; }
|
||||
try {
|
||||
if (!conversation) {
|
||||
if (conversations.length >= 100) {
|
||||
const removable = conversations.findIndex(c => !turns.has(c.id));
|
||||
if (removable < 0) throw new Error("No free conversation slots");
|
||||
conversations.splice(removable, 1);
|
||||
}
|
||||
const now = new Date().toISOString();
|
||||
conversation = { id: randomUUID(), title: m.message.replace(/\s+/g, " ").slice(0, 120), createdAt: now, updatedAt: now };
|
||||
conversations.push(conversation);
|
||||
}
|
||||
conversation.updatedAt = new Date().toISOString(); save();
|
||||
const current = conversation;
|
||||
send({ type: "conversation", conversation: current });
|
||||
active = startTurn({ ...processOptions, workspaceDir: config.workspaceDir, message: m.message, allowShell: m.allowShell,
|
||||
notebookPath: m.notebookPath, sessionId: current.sessionId, emit: send,
|
||||
onSession: id => { current.sessionId = id; try { save(); } catch { active?.cancel(); send({ type: "error", code: "cli", message: "Cannot save conversation." }); } },
|
||||
});
|
||||
turns.set(current.id, active);
|
||||
void active.done.finally(() => { turns.delete(current.id); active = undefined; });
|
||||
} catch { send({ type: "error", code: "cli", message: "Cannot start or save conversation." }); }
|
||||
});
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,70 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { StringDecoder } from "node:string_decoder";
|
||||
import type { ChatEvent } from "@shellbook/core";
|
||||
import { buildClaudeArgs, needsLogin, parseClaudeLine } from "./cli";
|
||||
|
||||
export interface TurnOptions {
|
||||
workspaceDir: string; message: string; sessionId?: string; notebookPath?: string; allowShell: boolean;
|
||||
executable?: string; prefixArgs?: string[]; timeoutMs?: number;
|
||||
emit(event: ChatEvent): void; onSession(id: string): void;
|
||||
}
|
||||
/** One process per turn. Resolves only on close, so cancelled turns retain their lock. */
|
||||
export function startTurn(options: TurnOptions): { cancel(): void; done: Promise<void> } {
|
||||
const child = spawn(options.executable ?? "claude", [...(options.prefixArgs ?? []), ...buildClaudeArgs(options)], {
|
||||
cwd: options.workspaceDir, shell: false, stdio: ["pipe", "pipe", "pipe"], windowsHide: true,
|
||||
detached: process.platform !== "win32",
|
||||
});
|
||||
let terminal: ChatEvent | undefined;
|
||||
let stopped = false, bytes = 0, pending = "", stderr = "";
|
||||
const decoder = new StringDecoder("utf8");
|
||||
let force: ReturnType<typeof setTimeout> | undefined;
|
||||
const kill = (signal: NodeJS.Signals) => {
|
||||
// On the Linux service, also stop any shell descendants in the turn's group.
|
||||
try {
|
||||
if (process.platform !== "win32" && child.pid) process.kill(-child.pid, signal);
|
||||
else child.kill(signal);
|
||||
} catch { /* The process may already have exited. */ }
|
||||
};
|
||||
const stop = (event: ChatEvent) => {
|
||||
if (stopped) return;
|
||||
stopped = true; terminal = event;
|
||||
kill("SIGTERM");
|
||||
force = setTimeout(() => kill("SIGKILL"), 1500);
|
||||
force.unref();
|
||||
};
|
||||
const consume = (line: string) => {
|
||||
if (!line.trim()) return;
|
||||
for (const event of parseClaudeLine(line, options.workspaceDir)) {
|
||||
if (event.type === "session") options.onSession(event.sessionId);
|
||||
else if (event.type === "finished" || event.type === "error") terminal = event;
|
||||
else options.emit(event);
|
||||
}
|
||||
};
|
||||
child.stdout.on("data", (chunk: Buffer) => {
|
||||
if (stopped) return;
|
||||
bytes += chunk.length;
|
||||
if (bytes > 4 * 1024 * 1024) { stop({ type: "error", code: "limit", message: "Claude output limit exceeded." }); return; }
|
||||
pending += decoder.write(chunk);
|
||||
if (pending.length > 1024 * 1024) { stop({ type: "error", code: "limit", message: "Claude record limit exceeded." }); return; }
|
||||
const lines = pending.split("\n"); pending = lines.pop()!;
|
||||
try { for (const line of lines) consume(line); }
|
||||
catch { stop({ type: "error", code: "cli", message: "Invalid response from Claude CLI." }); }
|
||||
});
|
||||
child.stderr.on("data", (chunk: Buffer) => { stderr = (stderr + chunk.toString()).slice(-8192); });
|
||||
child.stdin.on("error", () => {});
|
||||
child.stdin.end(JSON.stringify({ type: "user", message: { role: "user", content: options.message } }) + "\n");
|
||||
const timeout = setTimeout(() => stop({ type: "error", code: "timeout", message: "Claude turn timed out." }), options.timeoutMs ?? 5 * 60_000);
|
||||
const done = new Promise<void>(resolve => {
|
||||
child.on("error", (error: NodeJS.ErrnoException) => {
|
||||
terminal = { type: "error", code: error.code === "ENOENT" ? "missing" : "cli", message: error.code === "ENOENT" ? "Claude CLI is missing from the server PATH. Install it, then open Terminal and run claude followed by /login." : "Unable to start Claude CLI." };
|
||||
});
|
||||
child.on("close", code => {
|
||||
clearTimeout(timeout); clearTimeout(force);
|
||||
if (!stopped) { try { consume(pending + decoder.end()); } catch { terminal = undefined; } }
|
||||
if (!stopped && needsLogin(stderr)) terminal = { type: "error", code: "login", message: "Claude needs a login. Open Terminal, run claude, then /login." };
|
||||
if (!terminal || (!stopped && code !== 0 && terminal.type === "finished")) terminal = { type: "error", code: "cli", message: "Claude CLI exited without completing the turn." };
|
||||
options.emit(terminal); resolve();
|
||||
});
|
||||
});
|
||||
return { done, cancel: () => stop({ type: "finished", cancelled: true }) };
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
import {
|
||||
randomBytes,
|
||||
createCipheriv,
|
||||
createDecipheriv,
|
||||
createHash,
|
||||
} from "node:crypto";
|
||||
import {
|
||||
mkdir,
|
||||
readFile,
|
||||
writeFile,
|
||||
chmod,
|
||||
rename,
|
||||
rm,
|
||||
realpath,
|
||||
} from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
// ssh2 is CommonJS: Node's ESM loader cannot see `utils` as a named export (see test/bundle.test.ts).
|
||||
import ssh2 from "ssh2";
|
||||
const { utils } = ssh2;
|
||||
import type {
|
||||
HostCredentialInput,
|
||||
HostCredentialMetadata,
|
||||
} from "@shellbook/core";
|
||||
import { SerialQueue, httpError } from "../workspace";
|
||||
const writes = new SerialQueue();
|
||||
export type StoredCredential = {
|
||||
input: Exclude<HostCredentialInput, { type: "shellbook" }>;
|
||||
metadata: HostCredentialMetadata;
|
||||
};
|
||||
export class CredentialStore {
|
||||
constructor(
|
||||
private dir: string,
|
||||
private workspaceDir?: string,
|
||||
) {}
|
||||
private file(name: string) {
|
||||
return path.join(
|
||||
this.dir,
|
||||
"ssh-credentials",
|
||||
createHash("sha256").update(name).digest("hex") + ".json",
|
||||
);
|
||||
}
|
||||
private key() {
|
||||
return writes.run(path.join(this.dir, "ssh-credentials.key"), () =>
|
||||
this.loadKey(),
|
||||
);
|
||||
}
|
||||
private async loadKey() {
|
||||
await mkdir(this.dir, { recursive: true, mode: 0o700 });
|
||||
if (this.workspaceDir) {
|
||||
const workspace = await realpath(this.workspaceDir);
|
||||
const relative = path.relative(workspace, await realpath(this.dir));
|
||||
if (
|
||||
!relative ||
|
||||
(!relative.startsWith(".." + path.sep) &&
|
||||
relative !== ".." &&
|
||||
!path.isAbsolute(relative))
|
||||
) {
|
||||
throw httpError(
|
||||
400,
|
||||
"SSH credential data directory must be outside the workspace",
|
||||
);
|
||||
}
|
||||
}
|
||||
const file = path.join(this.dir, "ssh-credentials.key");
|
||||
try {
|
||||
await writeFile(file, randomBytes(32), { flag: "wx", mode: 0o600 });
|
||||
} catch (e) {
|
||||
if ((e as NodeJS.ErrnoException).code !== "EEXIST") throw e;
|
||||
}
|
||||
await chmod(file, 0o600);
|
||||
const key = await readFile(file);
|
||||
if (key.length !== 32) throw new Error("Invalid credential encryption key");
|
||||
return key;
|
||||
}
|
||||
async get(name: string): Promise<StoredCredential | undefined> {
|
||||
let bytes: Buffer;
|
||||
try {
|
||||
bytes = await readFile(this.file(name));
|
||||
} catch (e) {
|
||||
if ((e as NodeJS.ErrnoException).code === "ENOENT") return;
|
||||
throw new Error("Cannot read SSH credential");
|
||||
}
|
||||
try {
|
||||
const decipher = createDecipheriv(
|
||||
"aes-256-gcm",
|
||||
await this.key(),
|
||||
bytes.subarray(0, 12),
|
||||
);
|
||||
decipher.setAAD(Buffer.from(name));
|
||||
decipher.setAuthTag(bytes.subarray(12, 28));
|
||||
return JSON.parse(
|
||||
Buffer.concat([
|
||||
decipher.update(bytes.subarray(28)),
|
||||
decipher.final(),
|
||||
]).toString(),
|
||||
) as StoredCredential;
|
||||
} catch {
|
||||
throw new Error("Cannot decrypt SSH credential");
|
||||
}
|
||||
}
|
||||
async set(name: string, value: unknown): Promise<HostCredentialMetadata> {
|
||||
const input = value as HostCredentialInput;
|
||||
if (!input || typeof input !== "object")
|
||||
throw httpError(400, "Invalid credential");
|
||||
let safe: StoredCredential["input"];
|
||||
const metadata: HostCredentialMetadata = {
|
||||
type: input.type,
|
||||
setAt: new Date().toISOString(),
|
||||
};
|
||||
if (input.type === "shellbook") {
|
||||
await this.delete(name);
|
||||
return { type: "shellbook" };
|
||||
}
|
||||
if (input.type === "password") {
|
||||
if (
|
||||
typeof input.password !== "string" ||
|
||||
!input.password ||
|
||||
input.password.length > 16384 ||
|
||||
input.password.includes("\0")
|
||||
)
|
||||
throw httpError(400, "Invalid password");
|
||||
safe = { type: "password", password: input.password };
|
||||
} else if (input.type === "privateKey") {
|
||||
if (
|
||||
typeof input.privateKey !== "string" ||
|
||||
input.privateKey.length > 65536 ||
|
||||
(input.passphrase !== undefined &&
|
||||
(typeof input.passphrase !== "string" ||
|
||||
input.passphrase.length > 16384))
|
||||
)
|
||||
throw httpError(400, "Invalid private key");
|
||||
const parsed = utils.parseKey(input.privateKey, input.passphrase);
|
||||
if (
|
||||
parsed instanceof Error ||
|
||||
Array.isArray(parsed) ||
|
||||
!parsed.isPrivateKey()
|
||||
)
|
||||
throw httpError(400, "Invalid private key or passphrase");
|
||||
metadata.fingerprint =
|
||||
"SHA256:" +
|
||||
createHash("sha256")
|
||||
.update(parsed.getPublicSSH())
|
||||
.digest("base64")
|
||||
.replace(/=+$/, "");
|
||||
safe = {
|
||||
type: "privateKey",
|
||||
privateKey: input.privateKey,
|
||||
...(input.passphrase !== undefined
|
||||
? { passphrase: input.passphrase }
|
||||
: {}),
|
||||
};
|
||||
} else throw httpError(400, "Unsupported SSH authentication type");
|
||||
return writes.run(this.file(name), async () => {
|
||||
const key = await this.key();
|
||||
const iv = randomBytes(12);
|
||||
const cipher = createCipheriv("aes-256-gcm", key, iv);
|
||||
cipher.setAAD(Buffer.from(name));
|
||||
const encrypted = Buffer.concat([
|
||||
cipher.update(JSON.stringify({ input: safe, metadata })),
|
||||
cipher.final(),
|
||||
]);
|
||||
await mkdir(path.dirname(this.file(name)), {
|
||||
recursive: true,
|
||||
mode: 0o700,
|
||||
});
|
||||
const temp = this.file(name) + "." + randomBytes(8).toString("hex");
|
||||
try {
|
||||
await writeFile(
|
||||
temp,
|
||||
Buffer.concat([iv, cipher.getAuthTag(), encrypted]),
|
||||
{ mode: 0o600, flag: "wx" },
|
||||
);
|
||||
await rename(temp, this.file(name));
|
||||
} finally {
|
||||
await rm(temp, { force: true });
|
||||
}
|
||||
return metadata;
|
||||
});
|
||||
}
|
||||
async delete(name: string) {
|
||||
await writes.run(this.file(name), () =>
|
||||
rm(this.file(name), { force: true }),
|
||||
);
|
||||
}
|
||||
}
|
||||
export function credentialSecrets(stored?: StoredCredential): string[] {
|
||||
if (!stored) return [];
|
||||
return stored.input.type === "password"
|
||||
? [stored.input.password]
|
||||
: [
|
||||
stored.input.privateKey,
|
||||
...stored.input.privateKey
|
||||
.split(/\r?\n/)
|
||||
.filter((line) => line && !line.startsWith("-----")),
|
||||
stored.input.passphrase ?? "",
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
import { readFile, writeFile, rename, rm } from "node:fs/promises";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import path from "node:path";
|
||||
import { parseDocument, isSeq, isMap } from "yaml";
|
||||
// ssh2 is CommonJS: Node's ESM loader cannot see `utils` as a named export (see test/bundle.test.ts).
|
||||
import ssh2 from "ssh2";
|
||||
const { utils } = ssh2;
|
||||
import {
|
||||
shellQuote,
|
||||
type HostActionRequest,
|
||||
type SaveHostRequest,
|
||||
} from "@shellbook/core";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import type { ServerConfig } from "../config";
|
||||
import {
|
||||
readHosts,
|
||||
parseHosts,
|
||||
version,
|
||||
httpError,
|
||||
SerialQueue,
|
||||
} from "../workspace";
|
||||
import { connect, exec, forgetHostKey, HostKeyError, sshFailure } from "../ssh";
|
||||
import { CredentialStore } from "./credentials";
|
||||
import { validateHost } from "./validation";
|
||||
const saves = new SerialQueue();
|
||||
export const certificateSupport = {
|
||||
available: false as const,
|
||||
reason:
|
||||
"ssh2 1.17.0 has no client user-certificate authentication API. Use a private key or password.",
|
||||
};
|
||||
export function installKeyScript(publicKey: string) {
|
||||
return `umask 077
|
||||
mkdir -p "$HOME/.ssh"
|
||||
chmod 700 "$HOME/.ssh"
|
||||
touch "$HOME/.ssh/authorized_keys"
|
||||
chmod 600 "$HOME/.ssh/authorized_keys"
|
||||
grep -qxF -- ${shellQuote(publicKey)} "$HOME/.ssh/authorized_keys" || printf '\\n%s\\n' ${shellQuote(publicKey)} >> "$HOME/.ssh/authorized_keys"
|
||||
`;
|
||||
}
|
||||
export async function shellbookPublicKey(config: ServerConfig) {
|
||||
const parsed = utils.parseKey(await readFile(config.sshKeyPath));
|
||||
if (parsed instanceof Error || Array.isArray(parsed))
|
||||
throw httpError(503, "ShellBook key unavailable");
|
||||
return `${parsed.type} ${parsed.getPublicSSH().toString("base64")}`;
|
||||
}
|
||||
/** Runtime values every notebook can reference ({{shellbook.public_key}}); empty when the key is unavailable. */
|
||||
export async function builtinValues(config: ServerConfig): Promise<Record<string, string>> {
|
||||
try { return { "shellbook.public_key": await shellbookPublicKey(config) }; }
|
||||
catch { return {}; }
|
||||
}
|
||||
export async function hostsPlugin(
|
||||
app: FastifyInstance,
|
||||
{ config }: { config: ServerConfig },
|
||||
) {
|
||||
const store = new CredentialStore(config.dataDir, config.workspaceDir);
|
||||
const file = path.join(config.workspaceDir, "hosts.yaml");
|
||||
app.addHook("onSend", async (_req, reply) => {
|
||||
reply.header("Cache-Control", "no-store");
|
||||
});
|
||||
const hostByName = async (name: string) => {
|
||||
const host = (await readHosts(config)).find((h) => h.name === name);
|
||||
if (!host) throw httpError(404, "Host not found");
|
||||
return host;
|
||||
};
|
||||
app.get("/api/host-management", async () => {
|
||||
const source = await readFile(file, "utf8");
|
||||
return {
|
||||
hosts: await Promise.all(
|
||||
parseHosts(source).map(async (host) => ({
|
||||
...host,
|
||||
credential: (await store.get(host.name))?.metadata ?? {
|
||||
type: "shellbook",
|
||||
},
|
||||
})),
|
||||
),
|
||||
version: version(source),
|
||||
publicKey: await shellbookPublicKey(config),
|
||||
certificateSupport,
|
||||
};
|
||||
});
|
||||
async function save(
|
||||
name: string | undefined,
|
||||
body: SaveHostRequest | { baseVersion: string },
|
||||
remove = false,
|
||||
) {
|
||||
if (!body || typeof body.baseVersion !== "string")
|
||||
throw httpError(400, "baseVersion required");
|
||||
return saves.run(file, async () => {
|
||||
const source = await readFile(file, "utf8");
|
||||
if (version(source) !== body.baseVersion)
|
||||
throw httpError(409, "Hosts changed; reload before saving");
|
||||
const hosts = parseHosts(source);
|
||||
const index = hosts.findIndex((h) => h.name === name);
|
||||
if (name !== undefined && index < 0)
|
||||
throw httpError(404, "Host not found");
|
||||
const host = remove
|
||||
? undefined
|
||||
: validateHost((body as SaveHostRequest).host);
|
||||
|
||||
if (host && hosts.some((h, i) => h.name === host.name && i !== index))
|
||||
throw httpError(409, "Host name already exists");
|
||||
const doc = parseDocument(source);
|
||||
const list = isSeq(doc.contents) ? doc.contents : doc.get("hosts", true);
|
||||
if (doc.errors.length || !isSeq(list))
|
||||
throw httpError(400, "Invalid hosts.yaml");
|
||||
if (remove) list.delete(index);
|
||||
else if (index < 0) list.add(doc.createNode(host!));
|
||||
else {
|
||||
const node = list.items[index];
|
||||
if (!isMap(node)) throw httpError(400, "Invalid host entry");
|
||||
for (const [key, value] of Object.entries(host!)) node.set(key, value);
|
||||
}
|
||||
const next = String(doc);
|
||||
const renamedCredential =
|
||||
host && name && host.name !== name ? await store.get(name) : undefined;
|
||||
if (renamedCredential)
|
||||
await store.set(host!.name, renamedCredential.input);
|
||||
const temp = file + "." + randomUUID();
|
||||
try {
|
||||
await writeFile(temp, next, { flag: "wx" });
|
||||
await rename(temp, file);
|
||||
} finally {
|
||||
await rm(temp, { force: true });
|
||||
}
|
||||
if (remove || (host && name && host.name !== name))
|
||||
await store.delete(name!);
|
||||
return { version: version(next) };
|
||||
});
|
||||
}
|
||||
app.post<{ Body: SaveHostRequest }>("/api/host-management", (req) =>
|
||||
save(undefined, req.body),
|
||||
);
|
||||
app.put<{ Params: { name: string }; Body: SaveHostRequest }>(
|
||||
"/api/host-management/:name",
|
||||
(req) => save(req.params.name, req.body),
|
||||
);
|
||||
app.delete<{ Params: { name: string }; Body: { baseVersion: string } }>(
|
||||
"/api/host-management/:name",
|
||||
(req) => save(req.params.name, req.body, true),
|
||||
);
|
||||
app.put<{ Params: { name: string } }>(
|
||||
"/api/host-management/:name/credential",
|
||||
async (req) => {
|
||||
return saves.run(file, async () => {
|
||||
await hostByName(req.params.name);
|
||||
return store.set(req.params.name, req.body);
|
||||
});
|
||||
},
|
||||
);
|
||||
app.delete<{ Params: { name: string } }>(
|
||||
"/api/host-management/:name/credential",
|
||||
async (req) => {
|
||||
return saves.run(file, async () => {
|
||||
await hostByName(req.params.name);
|
||||
await store.delete(req.params.name);
|
||||
return { type: "shellbook" };
|
||||
});
|
||||
},
|
||||
);
|
||||
app.get<{ Params: { name: string } }>(
|
||||
"/api/host-management/:name/install-key",
|
||||
async (req) => {
|
||||
await hostByName(req.params.name);
|
||||
return { script: installKeyScript(await shellbookPublicKey(config)) };
|
||||
},
|
||||
);
|
||||
app.delete<{ Params: { name: string } }>(
|
||||
"/api/host-management/:name/known-key",
|
||||
async (req, reply) => {
|
||||
await forgetHostKey(config, await hostByName(req.params.name));
|
||||
return reply.code(204).send();
|
||||
},
|
||||
);
|
||||
app.post<{ Params: { name: string }; Body: HostActionRequest }>(
|
||||
"/api/host-management/:name/action",
|
||||
async (req) => {
|
||||
const host = await hostByName(req.params.name);
|
||||
const body = req.body;
|
||||
if (
|
||||
!body ||
|
||||
!["test", "install-key"].includes(body.action) ||
|
||||
(body.acceptHostKey !== undefined &&
|
||||
typeof body.acceptHostKey !== "string")
|
||||
)
|
||||
throw httpError(400, "Invalid host action");
|
||||
const script =
|
||||
body.action === "test"
|
||||
? "true\n"
|
||||
: installKeyScript(await shellbookPublicKey(config));
|
||||
if (body.action === "install-key" && body.script !== script)
|
||||
throw httpError(
|
||||
409,
|
||||
"Displayed script changed; reload it before running",
|
||||
);
|
||||
const credential = await store.get(host.name);
|
||||
if (
|
||||
body.action === "install-key" &&
|
||||
credential?.input.type !== "password"
|
||||
)
|
||||
throw httpError(
|
||||
400,
|
||||
"Store a password before installing the ShellBook key",
|
||||
);
|
||||
let client;
|
||||
try {
|
||||
client = await connect(
|
||||
config,
|
||||
host,
|
||||
body.acceptHostKey,
|
||||
credential ?? null,
|
||||
);
|
||||
// Deliberately discard all remote output: these actions expose exit status only.
|
||||
return {
|
||||
exitCode: await exec(
|
||||
client,
|
||||
"bash -euo pipefail -s",
|
||||
script,
|
||||
30000,
|
||||
() => {},
|
||||
),
|
||||
};
|
||||
} catch (e) {
|
||||
if (e instanceof HostKeyError)
|
||||
return {
|
||||
hostKey: {
|
||||
host: host.name,
|
||||
fingerprint: e.fingerprint,
|
||||
changed: e.changed,
|
||||
},
|
||||
};
|
||||
throw httpError(502, sshFailure(e) ?? "SSH connection or action failed");
|
||||
} finally {
|
||||
client?.end();
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { isIP } from "node:net";
|
||||
import type { HostInfo } from "@shellbook/core";
|
||||
import { httpError } from "../workspace";
|
||||
export function validateHost(value: unknown): HostInfo {
|
||||
if (!value || typeof value !== "object") throw httpError(400, "Invalid host");
|
||||
const { name, address, user, port = 22, tags = [] } = value as HostInfo;
|
||||
const hostname =
|
||||
typeof address === "string" &&
|
||||
address.length <= 253 &&
|
||||
address
|
||||
.replace(/\.$/, "")
|
||||
.split(".")
|
||||
.every((label) =>
|
||||
/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/.test(label),
|
||||
);
|
||||
if (
|
||||
typeof name !== "string" ||
|
||||
!/^[A-Za-z0-9._-]{1,128}$/.test(name) ||
|
||||
typeof address !== "string" ||
|
||||
(!isIP(address) && (!hostname || /^[0-9.]+$/.test(address))) ||
|
||||
typeof user !== "string" ||
|
||||
!/^[A-Za-z_][A-Za-z0-9._-]{0,63}\$?$/.test(user) ||
|
||||
!Number.isInteger(port) ||
|
||||
port < 1 ||
|
||||
port > 65535 ||
|
||||
!Array.isArray(tags) ||
|
||||
tags.length > 100 ||
|
||||
tags.some(
|
||||
(t) => typeof t !== "string" || t.length > 128 || /[\x00-\x1f]/.test(t),
|
||||
)
|
||||
)
|
||||
throw httpError(400, "Invalid host fields");
|
||||
return { name, address, user, port, tags };
|
||||
}
|
||||
@@ -1,46 +1,48 @@
|
||||
import { CredentialStore, credentialSecrets } from "../hosts/credentials";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { appendFile, mkdir, copyFile, stat, rm } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { createReadStream } from "node:fs";
|
||||
import { parseNotebook, resolveParams, renderStep, secretEnv, shellQuote, type Block, type Step, type Notebook, type RenderedStep, type StartRunRequest, type HostInfo } from "@shellbook/core";
|
||||
import { blockActive, findStep, isBuiltin, resolveParams, renderStep, secretEnv, shellQuote, type Step, type Notebook, type ParamValues, type RenderedStep, type StartRunRequest, type HostInfo } from "@shellbook/core";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import type { Client } from "ssh2";
|
||||
import type { ServerConfig } from "../config";
|
||||
import { readHosts, readNotebook, safeFile, safeRelative, httpError, SerialQueue } from "../workspace";
|
||||
import { connect, exec, localExec, scriptInput, sftp, sftpRequest, transfer, HostKeyError, type Output } from "../ssh";
|
||||
import { readHosts, loadNotebook, safeFile, safeRelative, httpError, SerialQueue } from "../workspace";
|
||||
import { connect, exec, localExec, scriptInput, sftp, sftpRequest, transfer, HostKeyError, sshFailure, type Output } from "../ssh";
|
||||
import { EventsHub } from "./events";
|
||||
import { runRoot, artifactFile, persistArtifacts, isSensitive, claimArtifact, sweepRuns } from "./artifacts";
|
||||
export { EventsHub } from "./events";
|
||||
|
||||
export function findStep(blocks: Block[], id: string): Step | undefined {
|
||||
for (const block of blocks) {
|
||||
if (block.type === "step" && block.step.attrs.id === id) return block.step;
|
||||
if (block.type === "after") { const found = findStep(block.blocks, id); if (found) return found; }
|
||||
}
|
||||
}
|
||||
|
||||
export function prepareRun(notebook: Notebook, req: StartRunRequest, hosts: HostInfo[]) {
|
||||
/** `notebook` is the composed notebook (see loadNotebook); builtins come from the server only. */
|
||||
export function prepareRun(notebook: Notebook, req: StartRunRequest, hosts: HostInfo[], builtins: ParamValues = {}) {
|
||||
if (notebook.diagnostics.some(d => d.severity === "error")) throw httpError(400, "Notebook has errors");
|
||||
const step = findStep(notebook.blocks, req.stepId);
|
||||
if (!step) throw httpError(404, "Step not found");
|
||||
const names = hosts.map(h => h.name);
|
||||
const resolved = resolveParams(notebook, req.params, names);
|
||||
if (Object.keys(resolved.errors).length) throw httpError(400, "Parameters are missing or invalid");
|
||||
const rendered = renderStep(notebook, step, resolved.values, req.runtime, names);
|
||||
// A client cannot supply or override builtins.
|
||||
const runtime: ParamValues = Object.assign(Object.create(null) as ParamValues,
|
||||
Object.fromEntries(Object.entries(req.runtime).filter(([name]) => !isBuiltin(name))), builtins);
|
||||
const resolved = resolveParams(notebook, req.params, names, runtime);
|
||||
// A step needs exactly the values it uses (core renderStep, spec §3.6): referenced params,
|
||||
// required secrets its script reads and every set secret of its scope (passed as env).
|
||||
// Unused required params never block it, so guided notebooks run early steps first.
|
||||
if (!blockActive(notebook, step.attrs.id, resolved.values)) throw httpError(400, "Step is not part of the selected options");
|
||||
const rendered = renderStep(notebook, step, resolved.values, runtime, names);
|
||||
if (rendered.missing.length || Object.keys(rendered.invalid).length) throw httpError(400, "Step parameters are missing or invalid");
|
||||
const host = hosts.find(h => h.name === rendered.host);
|
||||
if (!rendered.local && !host) throw httpError(400, "Unknown target host");
|
||||
for (const name of rendered.artifacts) safeRelative(name);
|
||||
if (rendered.kind === "check" && (rendered.uploads.length || rendered.artifacts.length)) throw httpError(400, "Checks cannot upload or collect artifacts");
|
||||
if (!Number.isFinite(step.attrs.timeoutSec) || step.attrs.timeoutSec <= 0) throw httpError(400, "Invalid timeout");
|
||||
return { step, rendered, host, env: secretEnv(notebook, resolved.values) };
|
||||
return { step, rendered, host, env: secretEnv(notebook, resolved.values, step.attrs.scope) };
|
||||
}
|
||||
|
||||
/** Streaming redaction retains possible secret prefixes across chunks. */
|
||||
export function redactor(secrets: string[], output: (data: string) => void) {
|
||||
const values = secrets.filter(Boolean).sort((a, b) => b.length - a.length);
|
||||
let pending = "";
|
||||
function flush(final: boolean) {
|
||||
// The run adds its credential snapshot before emitting any output.
|
||||
const values = secrets.filter(Boolean).sort((a, b) => b.length - a.length);
|
||||
let result = "";
|
||||
while (pending) {
|
||||
if (!final && values.some(value => value.startsWith(pending))) break;
|
||||
@@ -64,6 +66,7 @@ export async function executeRun({ config, hub, runId, request, step, rendered,
|
||||
const workdir = path.join(root, "work");
|
||||
const artifactDir = path.join(root, "artifacts");
|
||||
const secrets = Object.values(env).filter(Boolean);
|
||||
let credential: Awaited<ReturnType<CredentialStore["get"]>>;
|
||||
const clean = (value: string) => { for (const secret of [...secrets].sort((a,b) => b.length-a.length)) value = value.split(secret).join("[REDACTED]"); return value; };
|
||||
let stdout = "";
|
||||
let captureTooLarge = false;
|
||||
@@ -85,13 +88,14 @@ export async function executeRun({ config, hub, runId, request, step, rendered,
|
||||
};
|
||||
const output: Output = (stream, data) => streams[stream].write(data);
|
||||
try {
|
||||
if (host) { credential = await new CredentialStore(config.dataDir, config.workspaceDir).get(host.name); secrets.push(...credentialSecrets(credential).filter(Boolean)); }
|
||||
await mkdir(workdir, { recursive: true, mode: 0o700 });
|
||||
await mkdir(artifactDir, { mode: 0o700 });
|
||||
hub.publish({ type: "run.started", runId, notebookPath: request.notebookPath, stepId: rendered.stepId, host: rendered.host, script: clean(rendered.script) });
|
||||
const timeout = step.attrs.timeoutSec * 1000;
|
||||
if (!rendered.local) {
|
||||
failureReason = `Cannot connect to ${host!.address}:${host!.port}`;
|
||||
client = await connect(config, host!, request.acceptHostKey);
|
||||
client = await connect(config, host!, request.acceptHostKey, credential ?? null);
|
||||
failureReason = "Cannot create remote workdir";
|
||||
let directory = "";
|
||||
const code = await exec(client, "mktemp -d", "", timeout, (stream, data) => { if (stream === "stdout") directory += data; });
|
||||
@@ -175,7 +179,7 @@ export async function executeRun({ config, hub, runId, request, step, rendered,
|
||||
function stringMap(value: unknown): value is Record<string, string> {
|
||||
return !!value && typeof value === "object" && !Array.isArray(value) && Object.values(value).every(v => typeof v === "string");
|
||||
}
|
||||
export async function runsPlugin(app: FastifyInstance, { config, hub }: { config: ServerConfig; hub: EventsHub }) {
|
||||
export async function runsPlugin(app: FastifyInstance, { config, hub, builtins = async () => ({}) }: { config: ServerConfig; hub: EventsHub; builtins?: () => Promise<ParamValues> }) {
|
||||
const queue = new SerialQueue();
|
||||
const active = new Set<string>();
|
||||
const downloads = new Set<Promise<void>>();
|
||||
@@ -193,8 +197,8 @@ export async function runsPlugin(app: FastifyInstance, { config, hub }: { config
|
||||
app.post<{ Body: StartRunRequest }>("/api/runs", async (req, reply) => {
|
||||
const body = req.body;
|
||||
if (!body || typeof body.notebookPath !== "string" || typeof body.stepId !== "string" || !stringMap(body.params) || !stringMap(body.runtime) || !stringMap(body.artifactSources) || (body.acceptHostKey !== undefined && typeof body.acceptHostKey !== "string")) throw httpError(400, "Invalid run request");
|
||||
const { source } = await readNotebook(config, body.notebookPath);
|
||||
const prepared = prepareRun(parseNotebook(source), body, await readHosts(config));
|
||||
const { notebook } = await loadNotebook(config, body.notebookPath);
|
||||
const prepared = prepareRun(notebook, body, await readHosts(config), await builtins());
|
||||
const runId = randomUUID();
|
||||
active.add(runId);
|
||||
// Queue immediately; defer the work to allow the HTTP response to reach the subscriber.
|
||||
@@ -228,7 +232,8 @@ export async function runsPlugin(app: FastifyInstance, { config, hub }: { config
|
||||
function runFailure(error: unknown, fallback: string, timeoutSec: number): string {
|
||||
const e = error as { message?: string; level?: string; code?: string };
|
||||
if (e.message === "Execution timed out") return `Execution timed out after ${timeoutSec} s`;
|
||||
if (e.level === "client-authentication") return "SSH authentication failed";
|
||||
const ssh = sshFailure(error);
|
||||
if (ssh) return ssh;
|
||||
if (e.message === "Captured output exceeds 1 MiB") return e.message;
|
||||
if (e.message?.startsWith("SFTP ") && e.message.endsWith(" timed out")) return "File transfer timed out";
|
||||
return fallback;
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { access } from "node:fs/promises";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import type { ClaudeStatusResponse, SystemInfoResponse } from "@shellbook/core";
|
||||
import type { ServerConfig } from "../config";
|
||||
import { version } from "../../package.json";
|
||||
|
||||
/** No shell, bounded runtime/output, and no credential contents are accessed. */
|
||||
export async function claudeStatus(
|
||||
home = homedir(),
|
||||
env = process.env,
|
||||
): Promise<ClaudeStatusResponse> {
|
||||
const loginAppearsPresent = await access(
|
||||
join(home, ".claude", ".credentials.json"),
|
||||
).then(
|
||||
() => true,
|
||||
() => false,
|
||||
);
|
||||
return new Promise((resolve) => {
|
||||
execFile(
|
||||
"claude",
|
||||
["--version"],
|
||||
{ env, timeout: 3000, maxBuffer: 4096, windowsHide: true },
|
||||
(error, stdout) => {
|
||||
resolve({
|
||||
available: !error,
|
||||
version: error ? null : stdout.trim(),
|
||||
loginAppearsPresent,
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
export async function registerSettings(
|
||||
app: FastifyInstance,
|
||||
config: ServerConfig,
|
||||
): Promise<void> {
|
||||
app.get("/api/settings/claude", async (_request, reply) =>
|
||||
reply.header("Cache-Control", "no-store").send(await claudeStatus()),
|
||||
);
|
||||
app.get("/api/settings/system", async (_request, reply) => {
|
||||
const info: SystemInfoResponse = {
|
||||
version,
|
||||
workspacePath: config.workspaceDir,
|
||||
dataDirPath: config.dataDir,
|
||||
nodeVersion: process.version,
|
||||
};
|
||||
return reply.header("Cache-Control", "no-store").send(info);
|
||||
});
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import { StringDecoder } from "node:string_decoder";
|
||||
import { shellQuote, type HostInfo } from "@shellbook/core";
|
||||
import type { ServerConfig } from "../config";
|
||||
import { SerialQueue } from "../workspace";
|
||||
import { CredentialStore, type StoredCredential } from "../hosts/credentials";
|
||||
|
||||
export type Output = (stream: "stdout" | "stderr", data: string) => void;
|
||||
export class HostKeyError extends Error {
|
||||
@@ -15,9 +16,12 @@ export class HostKeyError extends Error {
|
||||
const keyWrites = new SerialQueue();
|
||||
export function fingerprint(key: Buffer) { return "SHA256:" + createHash("sha256").update(key).digest("base64").replace(/=+$/, ""); }
|
||||
|
||||
export async function connect(config: ServerConfig, host: HostInfo, accepted?: string): Promise<Client> {
|
||||
export async function connect(config: ServerConfig, host: HostInfo, accepted?: string, credential?: StoredCredential | null): Promise<Client> {
|
||||
const file = path.join(config.workspaceDir, "known_hosts");
|
||||
const privateKey = await readFile(config.sshKeyPath);
|
||||
const stored = credential === undefined ? await new CredentialStore(config.dataDir, config.workspaceDir).get(host.name) : credential;
|
||||
const auth = stored?.input.type === "password" ? { password: stored.input.password, tryKeyboard: true } :
|
||||
stored?.input.type === "privateKey" ? { privateKey: stored.input.privateKey, passphrase: stored.input.passphrase } :
|
||||
{ privateKey: await readFile(config.sshKeyPath) };
|
||||
// Serialize read/verify/write, so simultaneous first connections cannot overwrite pins.
|
||||
return keyWrites.run(file, async () => {
|
||||
const contents = await readFile(file, "utf8").catch((e: NodeJS.ErrnoException) => { if (e.code === "ENOENT") return ""; throw e; });
|
||||
@@ -31,7 +35,14 @@ export async function connect(config: ServerConfig, host: HostInfo, accepted?: s
|
||||
client.once("ready", resolve);
|
||||
client.on("error", err => reject(failure ?? err));
|
||||
client.once("close", () => reject(failure ?? new Error("SSH connection closed")));
|
||||
client.connect({ host: host.address, port: host.port, username: host.user, privateKey, readyTimeout: 10000,
|
||||
if (stored?.input.type === "password") {
|
||||
const password = stored.input.password;
|
||||
client.on("keyboard-interactive", (_name, _instructions, _lang, prompts, finish) => {
|
||||
// Answer password prompts only; never send a password as an OTP or echoed text.
|
||||
finish(prompts.map(prompt => !prompt.echo && /password/i.test(prompt.prompt) ? password : ""));
|
||||
});
|
||||
}
|
||||
client.connect({ host: host.address, port: host.port, username: host.user, ...auth, readyTimeout: 10000,
|
||||
hostVerifier(key: Buffer) {
|
||||
const encoded = key.toString("base64");
|
||||
if (matches.some(line => line.split(/\s+/)[2] === encoded)) return true;
|
||||
@@ -136,3 +147,32 @@ export function sftpRequest<T>(session: SFTPWrapper, request: (done: (error: Err
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
export async function forgetHostKey(config: ServerConfig, host: HostInfo) {
|
||||
const file = path.join(config.workspaceDir, "known_hosts");
|
||||
return keyWrites.run(file, async () => {
|
||||
const source = await readFile(file, "utf8").catch((e: NodeJS.ErrnoException) => { if (e.code === "ENOENT") return ""; throw e; });
|
||||
const identity = host.port === 22 ? host.address : `[${host.address}]:${host.port}`;
|
||||
const lines = source.split(/\r?\n/).flatMap(line => {
|
||||
const fields = line.split(/\s+/);
|
||||
if (!fields[0]?.split(",").includes(identity)) return [line];
|
||||
const aliases = fields[0].split(",").filter(alias => alias !== identity);
|
||||
return aliases.length ? [[aliases.join(","), ...fields.slice(1)].join(" ")] : [];
|
||||
});
|
||||
await writeFile(file, lines.join("\n"), { mode: 0o600 });
|
||||
});
|
||||
}
|
||||
|
||||
const unreachable: Record<string, string> = {
|
||||
ECONNREFUSED: "connection refused", EHOSTUNREACH: "host unreachable", ENETUNREACH: "network unreachable",
|
||||
ENOTFOUND: "unknown host name", EAI_AGAIN: "host name lookup failed", ETIMEDOUT: "connection timed out",
|
||||
ECONNRESET: "connection reset",
|
||||
};
|
||||
/** User-facing reason for a failed SSH connection; undefined when not a connection problem. Never includes secrets. */
|
||||
export function sshFailure(error: unknown): string | undefined {
|
||||
const e = error as { level?: string; code?: string } | null;
|
||||
if (e?.level === "client-authentication") return "SSH authentication failed: check the user and the saved password or key";
|
||||
if (e?.level === "client-timeout") return "Cannot reach the server: SSH handshake timed out";
|
||||
if (e?.code && unreachable[e.code]) return `Cannot reach the server: ${unreachable[e.code]}`;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { access, mkdir, open, writeFile } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import type {
|
||||
UpdateCheckResponse,
|
||||
UpdateStartResponse,
|
||||
UpdateState,
|
||||
UpdateStatusResponse,
|
||||
} from "@shellbook/core";
|
||||
|
||||
/**
|
||||
* Self-update from the web UI (#15). The service never gains privileges: it only writes
|
||||
* a request file. A root-owned systemd path unit (deploy/install.sh) watches that file
|
||||
* and starts `shellbook-update.service`, which runs the fixed root-owned updater and
|
||||
* writes its output to a root-owned log. Here we only read that state back.
|
||||
*/
|
||||
export interface UpdateOptions {
|
||||
/** Written to request an update; watched by shellbook-update.path. */
|
||||
requestFile: string;
|
||||
/** Present when the trigger units are installed. */
|
||||
triggerUnit: string;
|
||||
/** Output of the last update run (StandardOutput of the update unit). */
|
||||
logFile: string;
|
||||
/** The git checkout the server runs from. */
|
||||
repoDir: string;
|
||||
/** Runs a program with argv (no shell) and returns stdout; rejects on failure. */
|
||||
run(file: string, args: string[], timeoutMs: number): Promise<string>;
|
||||
}
|
||||
|
||||
const UNIT = "shellbook-update.service";
|
||||
const LOG_BYTES = 64 * 1024;
|
||||
const LOG_LINES = 200;
|
||||
|
||||
function run(file: string, args: string[], timeoutMs: number): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
execFile(
|
||||
file,
|
||||
args,
|
||||
// Never wait for credentials on a terminal that is not there.
|
||||
{ timeout: timeoutMs, maxBuffer: 1024 * 1024, windowsHide: true, env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } },
|
||||
(error, stdout) => (error ? reject(error) : resolve(stdout)),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function defaultUpdateOptions(dataDir: string): UpdateOptions {
|
||||
return {
|
||||
requestFile: join(dataDir, "update-request"),
|
||||
triggerUnit: "/etc/systemd/system/shellbook-update.path",
|
||||
logFile: "/var/log/shellbook-update.log",
|
||||
// systemd starts the service in the checkout (WorkingDirectory=/opt/shellbook).
|
||||
repoDir: process.cwd(),
|
||||
run,
|
||||
};
|
||||
}
|
||||
|
||||
/** `--timestamp=unix` prints `@<seconds>`; empty or `n/a` means never. */
|
||||
function timestamp(value: string | undefined): string | null {
|
||||
const match = value?.match(/^@(\d+)$/);
|
||||
return match ? new Date(Number(match[1]) * 1000).toISOString() : null;
|
||||
}
|
||||
|
||||
/** The last lines of the log, reading at most LOG_BYTES from its end. */
|
||||
async function logTail(path: string): Promise<string> {
|
||||
let file;
|
||||
try {
|
||||
file = await open(path, "r");
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
const { size } = await file.stat();
|
||||
const length = Math.min(size, LOG_BYTES);
|
||||
const buffer = Buffer.alloc(length);
|
||||
await file.read(buffer, 0, length, size - length);
|
||||
const lines = buffer.toString("utf8").split("\n");
|
||||
// Drop a partial first line when the read started mid-file.
|
||||
if (length < size) lines.shift();
|
||||
if (lines.at(-1) === "") lines.pop();
|
||||
return lines.slice(-LOG_LINES).join("\n");
|
||||
} finally {
|
||||
await file.close();
|
||||
}
|
||||
}
|
||||
|
||||
export function createUpdater(options: UpdateOptions) {
|
||||
const git = (args: string[], timeoutMs = 5000) =>
|
||||
options.run("git", ["-C", options.repoDir, ...args], timeoutMs).then((out) => out.trim());
|
||||
const current = () => git(["rev-parse", "--short", "HEAD"]).catch(() => null);
|
||||
const available = () => access(options.triggerUnit).then(() => true, () => false);
|
||||
|
||||
async function unitState(): Promise<Pick<UpdateStatusResponse, "state" | "startedAt" | "finishedAt">> {
|
||||
let output: string;
|
||||
try {
|
||||
output = await options.run(
|
||||
"systemctl",
|
||||
["show", UNIT, "--timestamp=unix", "--property=ActiveState,Result,ExecMainStartTimestamp,ExecMainExitTimestamp"],
|
||||
5000,
|
||||
);
|
||||
} catch {
|
||||
return { state: "unknown", startedAt: null, finishedAt: null };
|
||||
}
|
||||
const props: Record<string, string> = Object.fromEntries(
|
||||
output.split("\n").filter((line) => line.includes("=")).map((line) => {
|
||||
const at = line.indexOf("=");
|
||||
return [line.slice(0, at), line.slice(at + 1).trim()];
|
||||
}),
|
||||
);
|
||||
const startedAt = timestamp(props.ExecMainStartTimestamp);
|
||||
const finishedAt = timestamp(props.ExecMainExitTimestamp);
|
||||
let state: UpdateState;
|
||||
if (["activating", "active", "reloading", "deactivating"].includes(props.ActiveState ?? "")) state = "running";
|
||||
else if (props.ActiveState === "failed" || (startedAt && props.Result !== "success")) state = "failed";
|
||||
else state = startedAt ? "succeeded" : "idle";
|
||||
return { state, startedAt, finishedAt: state === "running" ? null : finishedAt };
|
||||
}
|
||||
|
||||
return {
|
||||
async status(): Promise<UpdateStatusResponse> {
|
||||
const [isAvailable, commit] = await Promise.all([available(), current()]);
|
||||
if (!isAvailable)
|
||||
return { available: false, state: "idle", current: commit, startedAt: null, finishedAt: null, log: "" };
|
||||
return { available: true, current: commit, ...(await unitState()), log: await logTail(options.logFile) };
|
||||
},
|
||||
|
||||
/** Fetches the tracked branch (FETCH_HEAD only) and lists the commits an update would bring. */
|
||||
async check(): Promise<UpdateCheckResponse> {
|
||||
const commit = await current();
|
||||
const branch = await git(["symbolic-ref", "-q", "--short", "HEAD"]).catch(() => null);
|
||||
// A detached HEAD is a pinned SHELLBOOK_REF: the installer never pulls it.
|
||||
if (!branch) return { current: commit, latest: null, pinned: true, changes: [] };
|
||||
const upstream = await git(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"]);
|
||||
const slash = upstream.indexOf("/");
|
||||
if (slash <= 0) throw new Error(`Unexpected upstream: ${upstream}`);
|
||||
await git(["fetch", "--quiet", "--no-tags", "--", upstream.slice(0, slash), upstream.slice(slash + 1)], 30_000);
|
||||
const latest = await git(["rev-parse", "--short", "FETCH_HEAD"]);
|
||||
const log = await git(["log", "--format=%h%x09%s", "-n", "50", "HEAD..FETCH_HEAD"]);
|
||||
const changes = log
|
||||
? log.split("\n").map((line) => {
|
||||
const tab = line.indexOf("\t");
|
||||
return { commit: line.slice(0, tab), subject: line.slice(tab + 1) };
|
||||
})
|
||||
: [];
|
||||
return { current: commit, latest, pinned: false, changes };
|
||||
},
|
||||
|
||||
/** Requests an update; systemd runs it as root. Returns null when it cannot start. */
|
||||
async start(): Promise<{ ok: true; response: UpdateStartResponse } | { ok: false; error: string }> {
|
||||
if (!(await available())) return { ok: false, error: "Updating from the web UI is not installed here. Run shellbook-update as root." };
|
||||
if ((await unitState()).state === "running") return { ok: false, error: "An update is already running." };
|
||||
const requestedAt = new Date().toISOString();
|
||||
await mkdir(dirname(options.requestFile), { recursive: true });
|
||||
// Closing the written file is what triggers the path unit (PathChanged=).
|
||||
await writeFile(options.requestFile, requestedAt + "\n", { mode: 0o600 });
|
||||
return { ok: true, response: { requestedAt } };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function registerUpdate(app: FastifyInstance, options: UpdateOptions): Promise<void> {
|
||||
const updater = createUpdater(options);
|
||||
app.get("/api/settings/update", async (_request, reply) =>
|
||||
reply.header("Cache-Control", "no-store").send(await updater.status()),
|
||||
);
|
||||
app.post("/api/settings/update/check", async (_request, reply) => {
|
||||
if ((await updater.status()).state === "running")
|
||||
return reply.code(409).send({ error: "An update is running." });
|
||||
try {
|
||||
return reply.header("Cache-Control", "no-store").send(await updater.check());
|
||||
} catch (error) {
|
||||
app.log.warn({ err: error }, "update check failed");
|
||||
return reply.code(502).send({ error: "Could not check the repository for updates." });
|
||||
}
|
||||
});
|
||||
app.post("/api/settings/update", async (_request, reply) => {
|
||||
const result = await updater.start();
|
||||
return result.ok ? reply.code(202).send(result.response) : reply.code(409).send({ error: result.error });
|
||||
});
|
||||
}
|
||||
@@ -22,7 +22,7 @@ export function createNotebookWatcher(workspaceDir: string, options: {
|
||||
const listeners = new Set<(event: NotebookFileEvent) => void>();
|
||||
const pending = new Map<string, ReturnType<typeof setTimeout>>();
|
||||
let closed = false;
|
||||
const watcher = watch(root, { ignoreInitial: true, followSymlinks: false, atomic: true });
|
||||
const watcher = watch([root, resolve(workspaceDir, "hosts.yaml")], { ignoreInitial: true, followSymlinks: false, atomic: true });
|
||||
const ready = new Promise<void>((resolveReady, reject) => {
|
||||
watcher.once("ready", resolveReady);
|
||||
watcher.on("error", (error) => {
|
||||
@@ -34,8 +34,8 @@ export function createNotebookWatcher(workspaceDir: string, options: {
|
||||
// Callers can await ready; avoid an unhandled rejection before they attach.
|
||||
void ready.catch(() => {});
|
||||
const schedule = (type: NotebookFileEvent["type"], file: string) => {
|
||||
const path = relative(root, file).split(sep).join("/");
|
||||
if (closed || !path.endsWith(".md") || path.startsWith("../") || isAbsolute(path)) return;
|
||||
const path = resolve(file) === resolve(workspaceDir, "hosts.yaml") ? "hosts.yaml" : relative(root, file).split(sep).join("/");
|
||||
if (closed || (!path.endsWith(".md") && path !== "hosts.yaml") || path.startsWith("../") || isAbsolute(path)) return;
|
||||
clearTimeout(pending.get(path));
|
||||
pending.set(path, setTimeout(() => {
|
||||
pending.delete(path);
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { atomicNotebookWrite, notebookRoot, notebookManagement } from "./notebooks";
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFile, writeFile, readdir, realpath, lstat } from "node:fs/promises";
|
||||
import { readFile, readdir, realpath, lstat } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { parse } from "yaml";
|
||||
import { parseNotebook, type HostInfo } from "@shellbook/core";
|
||||
import { validateHost } from "../hosts/validation";
|
||||
import { composeNotebook, notebookIncludes, parseNotebook, type HostInfo, type Notebook, type ParamValues } from "@shellbook/core";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import type { ServerConfig } from "../config";
|
||||
|
||||
@@ -34,26 +36,50 @@ export async function safeFile(root: string, name: string): Promise<string> {
|
||||
}
|
||||
|
||||
export async function readNotebook(config: ServerConfig, name: string) {
|
||||
// Name rules apply to creating notebooks only; existing files (git, Claude) stay readable.
|
||||
await notebookRoot(config);
|
||||
if (!name.endsWith(".md")) throw httpError(400, "Only Markdown notebooks are allowed");
|
||||
const file = await safeFile(path.join(config.workspaceDir, "notebooks"), name);
|
||||
return { file, source: await readFile(file, "utf8") };
|
||||
}
|
||||
|
||||
/** Upper bound on notebook files read for one composition (includes of includes). */
|
||||
const MAX_INCLUDE_FILES = 32;
|
||||
|
||||
/**
|
||||
* Read a notebook and compose its `::use` includes. Included files go through the same
|
||||
* workspace path rules; unreadable ones become "not found" diagnostics on the use line.
|
||||
*/
|
||||
export async function loadNotebook(config: ServerConfig, name: string) {
|
||||
const { file, source } = await readNotebook(config, name);
|
||||
const root = parseNotebook(source);
|
||||
const parsed = new Map<string, Notebook | undefined>([[name, root]]);
|
||||
const queue = notebookIncludes(root);
|
||||
while (queue.length && parsed.size < MAX_INCLUDE_FILES) {
|
||||
const next = queue.shift()!;
|
||||
if (parsed.has(next)) continue;
|
||||
const included = await readNotebook(config, next).then(r => parseNotebook(r.source), () => undefined);
|
||||
parsed.set(next, included);
|
||||
if (included) queue.push(...notebookIncludes(included));
|
||||
}
|
||||
const notebook = composeNotebook(name, root, include => parsed.get(include));
|
||||
return { file, source, notebook, includes: [...parsed.keys()].filter(include => include !== name) };
|
||||
}
|
||||
|
||||
export async function readHosts(config: ServerConfig): Promise<HostInfo[]> {
|
||||
const document: unknown = parse(await readFile(path.join(config.workspaceDir, "hosts.yaml"), "utf8"));
|
||||
return parseHosts(await readFile(path.join(config.workspaceDir, "hosts.yaml"), "utf8"));
|
||||
}
|
||||
export function parseHosts(source: string): HostInfo[] {
|
||||
let document: unknown;
|
||||
try { document = parse(source); } catch { throw httpError(400, "Invalid hosts.yaml"); }
|
||||
const entries = Array.isArray(document) ? document : (document as { hosts?: unknown } | null)?.hosts;
|
||||
if (!Array.isArray(entries)) throw httpError(400, "hosts.yaml must contain a host list");
|
||||
const names = new Set<string>();
|
||||
return entries.map((entry: Record<string, unknown>) => {
|
||||
if (!entry || typeof entry !== "object") throw httpError(400, "Invalid host");
|
||||
const { name, address, user, port = 22, tags = [] } = entry;
|
||||
if (typeof name !== "string" || !/^[A-Za-z0-9._-]+$/.test(name) || names.has(name) ||
|
||||
typeof address !== "string" || !address || /[\s\x00]/.test(address) ||
|
||||
typeof user !== "string" || !/^[A-Za-z0-9._-]+$/.test(user) ||
|
||||
!Number.isInteger(port) || Number(port) < 1 || Number(port) > 65535 ||
|
||||
!Array.isArray(tags) || tags.some(t => typeof t !== "string")) throw httpError(400, "Invalid or duplicate host entry");
|
||||
names.add(name);
|
||||
return { name, address, user, port: Number(port), tags: tags as string[] };
|
||||
const host = validateHost(entry);
|
||||
if (names.has(host.name)) throw httpError(400, "Duplicate host name");
|
||||
names.add(host.name);
|
||||
return host;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -69,8 +95,15 @@ export class SerialQueue {
|
||||
async idle() { await Promise.allSettled(this.tails.values()); }
|
||||
}
|
||||
|
||||
export async function workspacePlugin(app: FastifyInstance, { config }: { config: ServerConfig }) {
|
||||
export interface WorkspaceOptions {
|
||||
config: ServerConfig;
|
||||
/** Server-provided runtime values such as shellbook.public_key. */
|
||||
builtins?: () => Promise<ParamValues>;
|
||||
}
|
||||
|
||||
export async function workspacePlugin(app: FastifyInstance, { config, builtins = async () => ({}) }: WorkspaceOptions) {
|
||||
const saves = new SerialQueue();
|
||||
notebookManagement(app, config, saves);
|
||||
app.get("/api/hosts", async () => ({ hosts: await readHosts(config) }));
|
||||
app.get("/api/notebooks", async () => {
|
||||
const notebooks: { path: string; title: string }[] = [];
|
||||
@@ -84,19 +117,20 @@ export async function workspacePlugin(app: FastifyInstance, { config }: { config
|
||||
}
|
||||
}
|
||||
}
|
||||
await notebookRoot(config);
|
||||
await walk(path.join(config.workspaceDir, "notebooks"));
|
||||
return { notebooks: notebooks.sort((a, b) => a.path.localeCompare(b.path)) };
|
||||
});
|
||||
app.get<{ Params: { path: string } }>("/api/notebooks/:path", async req => {
|
||||
const { source } = await readNotebook(config, req.params.path);
|
||||
return { path: req.params.path, source, notebook: parseNotebook(source), version: version(source) };
|
||||
const { source, notebook, includes } = await loadNotebook(config, req.params.path);
|
||||
return { path: req.params.path, source, notebook, includes, builtins: await builtins(), version: version(source) };
|
||||
});
|
||||
app.put<{ Params: { path: string }; Body: { source: string; baseVersion: string } }>("/api/notebooks/:path", async req => {
|
||||
if (!req.body || typeof req.body.source !== "string" || typeof req.body.baseVersion !== "string") throw httpError(400, "Invalid save request");
|
||||
return saves.run(req.params.path, async () => {
|
||||
return saves.run("notebooks", async () => {
|
||||
const { file, source } = await readNotebook(config, req.params.path);
|
||||
if (version(source) !== req.body.baseVersion) throw httpError(409, "Notebook changed");
|
||||
await writeFile(file, req.body.source, "utf8");
|
||||
await atomicNotebookWrite(file, req.body.source);
|
||||
return { version: version(req.body.source) };
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import {
|
||||
lstat,
|
||||
mkdir,
|
||||
realpath,
|
||||
writeFile,
|
||||
rename,
|
||||
unlink,
|
||||
rmdir,
|
||||
link,
|
||||
} from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import type {
|
||||
CreateNotebookRequest,
|
||||
MoveNotebookRequest,
|
||||
DeleteNotebookRequest,
|
||||
} from "@shellbook/core";
|
||||
import { httpError, readNotebook, SerialQueue, version } from "./index";
|
||||
import type { ServerConfig } from "../config";
|
||||
|
||||
export function notebookName(name: string): string {
|
||||
if (
|
||||
typeof name !== "string" ||
|
||||
name.length > 240 ||
|
||||
!name.endsWith(".md") ||
|
||||
name
|
||||
.split("/")
|
||||
.some(
|
||||
(p) =>
|
||||
!/^[A-Za-z0-9][A-Za-z0-9 _.-]*$/.test(p) ||
|
||||
p.includes("..") ||
|
||||
/[. ]$/.test(p) ||
|
||||
/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(p),
|
||||
)
|
||||
) {
|
||||
throw httpError(
|
||||
400,
|
||||
"Use a relative .md path with letters, numbers, spaces, dots, underscores or hyphens",
|
||||
);
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
/** Validate the root before resolving any notebook path. */
|
||||
export async function notebookRoot(config: ServerConfig): Promise<string> {
|
||||
const root = path.join(await realpath(config.workspaceDir), "notebooks");
|
||||
try {
|
||||
const info = await lstat(root);
|
||||
if (info.isSymbolicLink() || !info.isDirectory())
|
||||
throw httpError(
|
||||
400,
|
||||
"Symlinks and non-directory parents are not allowed",
|
||||
);
|
||||
} catch (e) {
|
||||
if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e;
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
/** Walk every component; never follow symlinks. */
|
||||
export async function notebookDestination(
|
||||
config: ServerConfig,
|
||||
name: string,
|
||||
): Promise<string> {
|
||||
notebookName(name);
|
||||
let current = await notebookRoot(config);
|
||||
const parts = name.split("/");
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
current = path.join(current, parts[i]!);
|
||||
try {
|
||||
const info = await lstat(current);
|
||||
if (
|
||||
info.isSymbolicLink() ||
|
||||
(i < parts.length - 1 && !info.isDirectory())
|
||||
)
|
||||
throw httpError(
|
||||
400,
|
||||
"Symlinks and non-directory parents are not allowed",
|
||||
);
|
||||
} catch (e) {
|
||||
if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e;
|
||||
}
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
export async function atomicNotebookWrite(
|
||||
file: string,
|
||||
source: string,
|
||||
exclusive = false,
|
||||
) {
|
||||
await mkdir(path.dirname(file), { recursive: true });
|
||||
const temp = path.join(path.dirname(file), `.shellbook-${randomUUID()}.tmp`);
|
||||
try {
|
||||
await writeFile(temp, source, {
|
||||
encoding: "utf8",
|
||||
flag: "wx",
|
||||
mode: 0o600,
|
||||
});
|
||||
// link publishes a complete file without replacing an existing destination.
|
||||
if (exclusive) await link(temp, file);
|
||||
else await rename(temp, file);
|
||||
} catch (e) {
|
||||
if ((e as NodeJS.ErrnoException).code === "EEXIST")
|
||||
throw httpError(409, "Notebook already exists");
|
||||
throw e;
|
||||
} finally {
|
||||
await unlink(temp).catch(() => {});
|
||||
}
|
||||
}
|
||||
async function prune(config: ServerConfig, file: string) {
|
||||
// Same resolved root as the file path; stop at it, never walk above it.
|
||||
const root = await notebookRoot(config);
|
||||
for (let dir = path.dirname(file); dir.startsWith(root + path.sep); dir = path.dirname(dir)) {
|
||||
try {
|
||||
await rmdir(dir);
|
||||
} catch (e) {
|
||||
if (
|
||||
["ENOTEMPTY", "EEXIST", "ENOENT"].includes(
|
||||
(e as NodeJS.ErrnoException).code ?? "",
|
||||
)
|
||||
)
|
||||
return;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
export function notebookManagement(
|
||||
app: FastifyInstance,
|
||||
config: ServerConfig,
|
||||
queue: SerialQueue,
|
||||
) {
|
||||
app.post<{ Body: CreateNotebookRequest }>("/api/notebooks", async (req) =>
|
||||
queue.run("notebooks", async () => {
|
||||
if (!req.body || typeof req.body.source !== "string")
|
||||
throw httpError(400, "Invalid notebook");
|
||||
const file = await notebookDestination(config, req.body.path);
|
||||
await atomicNotebookWrite(file, req.body.source, true);
|
||||
return { path: req.body.path, version: version(req.body.source) };
|
||||
}),
|
||||
);
|
||||
for (const operation of ["rename", "duplicate"] as const) {
|
||||
app.post<{ Params: { path: string }; Body: MoveNotebookRequest }>(
|
||||
`/api/notebooks/:path/${operation}`,
|
||||
async (req) =>
|
||||
queue.run("notebooks", async () => {
|
||||
if (!req.body || typeof req.body.baseVersion !== "string")
|
||||
throw httpError(400, "Missing baseVersion");
|
||||
// Only the new path must satisfy the create rules; the source may predate them.
|
||||
const { file: original, source } = await readNotebook(config, req.params.path);
|
||||
if (version(source) !== req.body.baseVersion)
|
||||
throw httpError(409, "Notebook changed");
|
||||
const target = await notebookDestination(config, req.body.path);
|
||||
await atomicNotebookWrite(target, source, true);
|
||||
if (operation === "rename") {
|
||||
try {
|
||||
await unlink(original);
|
||||
} catch (e) {
|
||||
await unlink(target);
|
||||
throw e;
|
||||
}
|
||||
await prune(config, original);
|
||||
}
|
||||
return { path: req.body.path, version: version(source) };
|
||||
}),
|
||||
);
|
||||
}
|
||||
app.delete<{ Params: { path: string }; Body: DeleteNotebookRequest }>(
|
||||
"/api/notebooks/:path",
|
||||
async (req) =>
|
||||
queue.run("notebooks", async () => {
|
||||
if (!req.body || typeof req.body.baseVersion !== "string")
|
||||
throw httpError(400, "Missing baseVersion");
|
||||
const { file, source } = await readNotebook(config, req.params.path);
|
||||
if (version(source) !== req.body.baseVersion)
|
||||
throw httpError(409, "Notebook changed");
|
||||
await unlink(file);
|
||||
await prune(config, file);
|
||||
return { deleted: true };
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { execFile, spawn } from "node:child_process";
|
||||
import { mkdtemp, readFile, rm } from "node:fs/promises";
|
||||
import { createServer } from "node:net";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
// Vitest resolves CommonJS packages differently than Node's ESM loader, so only the
|
||||
// real production bundle shows whether externals like ssh2 import correctly.
|
||||
const serverDir = path.resolve(__dirname, "..");
|
||||
|
||||
async function freePort() {
|
||||
const probe = createServer();
|
||||
await new Promise<void>(resolve => probe.listen(0, "127.0.0.1", resolve));
|
||||
const { port } = probe.address() as { port: number };
|
||||
await new Promise(resolve => probe.close(resolve));
|
||||
return port;
|
||||
}
|
||||
|
||||
it("starts the production bundle with Node and answers the health check", async () => {
|
||||
const outdir = await mkdtemp(path.join(serverDir, ".bundle-test-"));
|
||||
const work = await mkdtemp(path.join(tmpdir(), "shellbook-bundle-"));
|
||||
try {
|
||||
const { scripts } = JSON.parse(await readFile(path.join(serverDir, "package.json"), "utf8")) as { scripts: { build: string } };
|
||||
const args = scripts.build.split(" ").slice(1).map(arg => arg.startsWith("--outdir=") ? `--outdir=${outdir}` : arg);
|
||||
await promisify(execFile)(path.join(serverDir, "node_modules", ".bin", "esbuild"), args, { cwd: serverDir, shell: process.platform === "win32" });
|
||||
const port = await freePort();
|
||||
const child = spawn(process.execPath, [path.join(outdir, "main.js")], {
|
||||
cwd: serverDir,
|
||||
env: { ...process.env, SHELLBOOK_HOST: "127.0.0.1", SHELLBOOK_PORT: String(port), SHELLBOOK_WORKSPACE: path.join(work, "workspace"), SHELLBOOK_DATA_DIR: path.join(work, "data"), SHELLBOOK_SSH_KEY: path.join(work, "data", "id_ed25519") },
|
||||
stdio: ["ignore", "ignore", "pipe"],
|
||||
});
|
||||
let stderr = "";
|
||||
child.stderr.on("data", chunk => { stderr += chunk; });
|
||||
const exited = new Promise<number | null>(resolve => child.on("exit", resolve));
|
||||
try {
|
||||
const healthy = await Promise.race([
|
||||
(async () => {
|
||||
for (let attempt = 0; attempt < 100; attempt++) {
|
||||
try { if ((await fetch(`http://127.0.0.1:${port}/api/health`)).ok) return true; } catch { /* not listening yet */ }
|
||||
await new Promise(r => setTimeout(r, 100));
|
||||
}
|
||||
return false;
|
||||
})(),
|
||||
exited.then(code => { throw new Error(`Server exited with ${code}: ${stderr}`); }),
|
||||
]);
|
||||
expect(healthy).toBe(true);
|
||||
} finally {
|
||||
child.kill();
|
||||
await exited;
|
||||
}
|
||||
} finally {
|
||||
await rm(outdir, { recursive: true, force: true });
|
||||
await rm(work, { recursive: true, force: true });
|
||||
}
|
||||
}, 60_000);
|
||||
@@ -0,0 +1,190 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { cp, mkdtemp, mkdir, writeFile, rm } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { generateKeyPairSync } from "node:crypto";
|
||||
import type { HostInfo, NotebookResponse, StartRunRequest } from "@shellbook/core";
|
||||
import { findStep, parseNotebook } from "@shellbook/core";
|
||||
import { buildApp } from "../src/app";
|
||||
import { loadConfig, type ServerConfig } from "../src/config";
|
||||
import { prepareRun } from "../src/runs";
|
||||
import { loadNotebook } from "../src/workspace";
|
||||
|
||||
const lxc = `---
|
||||
title: LXC container
|
||||
params:
|
||||
proxmox: {type: host, required: true}
|
||||
hostname: {type: name, required: true}
|
||||
ROOTPW: {type: secret}
|
||||
---
|
||||
\`\`\`sh {run host="{{proxmox}}" id=create capture=address}
|
||||
pct create --hostname {{hostname}} --key {{shellbook.public_key}} --pw "$ROOTPW"
|
||||
\`\`\`
|
||||
|
||||
::host{name="{{hostname}}" address="{{address}}" capture=host}
|
||||
`;
|
||||
const service = `---
|
||||
title: Web server
|
||||
params:
|
||||
target: {type: choice, options: [existing, lxc], default: lxc}
|
||||
host: {type: host, required: true, default: "{{ct.host}}"}
|
||||
TOKEN: {type: secret}
|
||||
---
|
||||
:::when{target=lxc}
|
||||
::use{notebook="infra/lxc.md" as=ct with="hostname=web-ct"}
|
||||
:::
|
||||
|
||||
\`\`\`sh {run host="{{host}}" id=install}
|
||||
apt-get install -y nginx
|
||||
\`\`\`
|
||||
`;
|
||||
const hosts: HostInfo[] = ["pve", "web-ct", "existing"].map(name => ({ name, address: "127.0.0.1", user: "root", port: 22, tags: [] }));
|
||||
|
||||
const cleanup: (() => Promise<unknown>)[] = [];
|
||||
afterEach(async () => { for (const fn of cleanup.splice(0).reverse()) await fn(); });
|
||||
async function fixture(files: Record<string, string> = { "infra/lxc.md": lxc, "services/web.md": service }) {
|
||||
const dir = await mkdtemp(path.join(os.tmpdir(), "shellbook-chain-"));
|
||||
cleanup.push(() => rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }));
|
||||
const config = loadConfig({ workspaceDir: path.join(dir, "workspace"), dataDir: path.join(dir, "data"), sshKeyPath: path.join(dir, "key") });
|
||||
await mkdir(path.join(config.workspaceDir, "notebooks"), { recursive: true });
|
||||
for (const [name, source] of Object.entries(files)) {
|
||||
await mkdir(path.dirname(path.join(config.workspaceDir, "notebooks", name)), { recursive: true });
|
||||
await writeFile(path.join(config.workspaceDir, "notebooks", name), source);
|
||||
}
|
||||
await writeFile(path.join(config.workspaceDir, "hosts.yaml"), "- name: pve\n address: 127.0.0.1\n user: root\n");
|
||||
await writeFile(config.sshKeyPath, generateKeyPairSync("rsa", { modulusLength: 2048 }).privateKey.export({ type: "pkcs1", format: "pem" }).toString());
|
||||
return config;
|
||||
}
|
||||
async function app(config: ServerConfig) {
|
||||
const instance = await buildApp({ config, auth: false });
|
||||
cleanup.push(() => instance.close());
|
||||
return instance;
|
||||
}
|
||||
const request = (stepId: string, params: Record<string, string>, runtime: Record<string, string> = {}): StartRunRequest =>
|
||||
({ notebookPath: "services/web.md", stepId, params, runtime, artifactSources: {} });
|
||||
|
||||
describe("chained notebooks on the server", () => {
|
||||
it("returns the composed notebook with its includes and builtins", async () => {
|
||||
const config = await fixture();
|
||||
const res = await (await app(config)).inject("/api/notebooks/services%2Fweb.md");
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json() as NotebookResponse;
|
||||
expect(body.source).toBe(service);
|
||||
expect(body.includes).toEqual(["infra/lxc.md"]);
|
||||
expect(body.builtins["shellbook.public_key"]).toMatch(/^ssh-rsa AAAA/);
|
||||
expect(body.notebook.diagnostics).toEqual([]);
|
||||
expect(body.notebook.params.map(p => p.name)).toContain("ct.hostname");
|
||||
expect(findStep(body.notebook.blocks, "ct.create")?.attrs.scope).toBe("ct");
|
||||
});
|
||||
|
||||
it("reports a missing or unreadable include on the use line and refuses runs", async () => {
|
||||
const config = await fixture({ "web.md": '::use{notebook="../escape.md" as=x}\n::use{notebook="gone.md" as=y}\n' });
|
||||
const { notebook, includes } = await loadNotebook(config, "web.md");
|
||||
expect(includes).toEqual(["gone.md"]);
|
||||
expect(notebook.diagnostics.map(d => [d.line, d.message])).toEqual([
|
||||
[1, 'use requires notebook="dir/name.md" (relative to notebooks/)'],
|
||||
[2, "Included notebook not found: gone.md"],
|
||||
]);
|
||||
const res = await (await app(config)).inject({ method: "POST", url: "/api/runs", payload: { ...request("x", {}), notebookPath: "web.md" } });
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.json().message).toBe("Notebook has errors");
|
||||
});
|
||||
|
||||
it("gates by scope, refuses inactive when sections and injects server builtins only", async () => {
|
||||
const config = await fixture();
|
||||
const { notebook } = await loadNotebook(config, "services/web.md");
|
||||
const builtins = { "shellbook.public_key": "ssh-ed25519 SERVER" };
|
||||
const values = { target: "lxc", "ct.proxmox": "pve", "ct.ROOTPW": "root-pw", TOKEN: "token" };
|
||||
// The parent's host is still pending (captured later), which must not block the container step.
|
||||
const prepared = prepareRun(notebook, request("ct.create", values, { "shellbook.public_key": "ssh-ed25519 CLIENT" }), hosts, builtins);
|
||||
expect(prepared.rendered.script).toBe("pct create --hostname web-ct --key 'ssh-ed25519 SERVER' --pw \"$ROOTPW\"\n");
|
||||
expect(prepared.host?.name).toBe("pve");
|
||||
expect(prepared.env).toEqual({ ROOTPW: "root-pw" });
|
||||
expect(() => prepareRun(notebook, request("install", values), hosts, builtins)).toThrow("Step parameters are missing or invalid");
|
||||
const parent = prepareRun(notebook, request("install", values, { "ct.host": "web-ct" }), hosts, builtins);
|
||||
expect(parent.host?.name).toBe("web-ct");
|
||||
expect(parent.env).toEqual({ TOKEN: "token" });
|
||||
// Container steps are refused when "existing host" is selected; the included form gates its own steps.
|
||||
expect(() => prepareRun(notebook, request("ct.create", { ...values, target: "existing" }), hosts, builtins)).toThrow("Step is not part of the selected options");
|
||||
expect(() => prepareRun(notebook, request("ct.create", { target: "lxc" }), hosts, builtins)).toThrow("Step parameters are missing or invalid");
|
||||
// Without a server key the builtin stays missing even if a client sends one.
|
||||
expect(() => prepareRun(notebook, request("ct.create", values, { "shellbook.public_key": "ssh-ed25519 CLIENT" }), hosts, {})).toThrow("Step parameters are missing or invalid");
|
||||
});
|
||||
|
||||
it("lets an optional parameter wait for a capture without blocking the step that captures it", async () => {
|
||||
const config = await fixture({ "next.md": `---
|
||||
params:
|
||||
proxmox: {type: host, required: true}
|
||||
ctid: {type: name, default: "{{nextid}}"}
|
||||
---
|
||||
\`\`\`sh {check host="{{proxmox}}" id=next capture=nextid}
|
||||
pvesh get /cluster/nextid
|
||||
\`\`\`
|
||||
|
||||
\`\`\`sh {run host="{{proxmox}}" id=create}
|
||||
pct create {{ctid}}
|
||||
\`\`\`
|
||||
` });
|
||||
const { notebook } = await loadNotebook(config, "next.md");
|
||||
const run = (stepId: string, runtime: Record<string, string> = {}) =>
|
||||
prepareRun(notebook, { notebookPath: "next.md", stepId, params: { proxmox: "pve" }, runtime, artifactSources: {} }, hosts);
|
||||
expect(run("next").rendered.script).toBe("pvesh get /cluster/nextid\n");
|
||||
expect(() => run("create")).toThrow("Step parameters are missing or invalid");
|
||||
expect(run("create", { nextid: "105" }).rendered.script).toBe("pct create 105\n");
|
||||
});
|
||||
|
||||
it("ships template notebooks that compose without diagnostics", async () => {
|
||||
const config = await fixture({});
|
||||
await cp(path.resolve(__dirname, "../../../templates/workspace/notebooks"), path.join(config.workspaceDir, "notebooks"), { recursive: true });
|
||||
const names = ["base-hardening-checks.md", "install-package.md", "ssh-key.md", "infra/lxc-container.md", "services/web-server.md"];
|
||||
for (const name of names) expect((await loadNotebook(config, name)).notebook.diagnostics, name).toEqual([]);
|
||||
const { notebook, includes } = await loadNotebook(config, "services/web-server.md");
|
||||
expect(includes).toEqual(["infra/lxc-container.md"]);
|
||||
const values = { target: "lxc", server_name: "web", "ct.proxmox": "pve", "ct.net": "ip=10.0.30.160/24,gw=10.0.30.1" };
|
||||
const runtime = { "ct.nextid": "105", "ct.template": "local:vztmpl/debian-12-standard_12.7-1_amd64.tar.zst" };
|
||||
const prepared = prepareRun(notebook, request("ct.create", values, runtime), hosts, { "shellbook.public_key": "ssh-ed25519 AAAAKEY shellbook" });
|
||||
expect(prepared.rendered.script).toContain("printf '%s\\n' 'ssh-ed25519 AAAAKEY shellbook' > \"$keys\"");
|
||||
expect(prepared.rendered.script).toContain("pct create 105 local:vztmpl/debian-12-standard_12.7-1_amd64.tar.zst \\\n --hostname web \\");
|
||||
expect(prepared.rendered.script).toContain("--net0 name=eth0,bridge=vmbr0,'ip=10.0.30.160/24,gw=10.0.30.1'");
|
||||
expect(() => prepareRun(notebook, request("install", { ...values, target: "existing" }), hosts, {})).toThrow("Step parameters are missing or invalid");
|
||||
expect(prepareRun(notebook, request("install", { target: "existing", host: "existing" }), hosts, {}).host?.name).toBe("existing");
|
||||
});
|
||||
|
||||
it("refuses an inactive step over HTTP", async () => {
|
||||
const config = await fixture();
|
||||
const res = await (await app(config)).inject({ method: "POST", url: "/api/runs", payload: request("ct.create", { target: "existing", "ct.proxmox": "pve" }) });
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.json().message).toBe("Step is not part of the selected options");
|
||||
});
|
||||
});
|
||||
|
||||
describe("guided notebooks (#16)", () => {
|
||||
const guided = parseNotebook(`---
|
||||
params:
|
||||
host: {type: host, required: true}
|
||||
user: {type: name, required: true}
|
||||
TOKEN: {type: secret, required: true}
|
||||
---
|
||||
:::group{title="1. Server"}
|
||||
::param{name=host}
|
||||
\`\`\`sh {check host="{{host}}" id=first}
|
||||
true
|
||||
\`\`\`
|
||||
:::
|
||||
\`\`\`sh {run host="{{host}}" id=later}
|
||||
useradd {{user}} && curl -H "Authorization: $TOKEN" https://example.invalid
|
||||
\`\`\`
|
||||
`);
|
||||
|
||||
it("runs an early step before later required values are filled", () => {
|
||||
expect(guided.diagnostics).toEqual([]);
|
||||
expect(prepareRun(guided, request("first", { host: "pve" }), hosts).rendered.script).toBe("true\n");
|
||||
expect(() => prepareRun(guided, request("later", { host: "pve", TOKEN: "t" }), hosts)).toThrow("Step parameters are missing or invalid");
|
||||
expect(() => prepareRun(guided, request("later", { host: "pve", user: "ops" }), hosts)).toThrow("Step parameters are missing or invalid");
|
||||
expect(prepareRun(guided, request("later", { host: "pve", user: "ops", TOKEN: "t" }), hosts).env).toEqual({ TOKEN: "t" });
|
||||
});
|
||||
|
||||
it("still refuses an invalid secret even when the step does not read it", () => {
|
||||
expect(() => prepareRun(guided, request("first", { host: "pve", TOKEN: "a\0b" }), hosts)).toThrow("Step parameters are missing or invalid");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { copyFileSync, linkSync, mkdtempSync, readFileSync, rmSync, symlinkSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import Fastify from "fastify";
|
||||
import websocket from "@fastify/websocket";
|
||||
import { buildClaudeArgs, notebookPath, parseClaudeLine } from "../src/chat/cli";
|
||||
import { startTurn } from "../src/chat/process";
|
||||
import { chatPlugin, parseChatMessage } from "../src/chat";
|
||||
import { buildApp } from "../src/app";
|
||||
import { loadConfig } from "../src/config";
|
||||
import { loadSessionSecret, signSession } from "../src/auth/session";
|
||||
import type { ChatEvent } from "@shellbook/core";
|
||||
|
||||
const dirs: string[] = [];
|
||||
const temp = () => { const dir = mkdtempSync(join(tmpdir(), "shellbook-chat-")); dirs.push(dir); return dir; };
|
||||
afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });
|
||||
const fixture = resolve("test/fixtures/fake-claude.cjs");
|
||||
const processOptions = { executable: process.execPath, prefixArgs: [fixture], timeoutMs: 3000 };
|
||||
const run = (message: string, extra = {}) => {
|
||||
const events: ChatEvent[] = []; const sessions: string[] = [];
|
||||
const turn = startTurn({ ...processOptions, workspaceDir: process.cwd(), message, allowShell: false,
|
||||
emit: e => events.push(e), onSession: id => sessions.push(id), ...extra });
|
||||
return { ...turn, events, sessions };
|
||||
};
|
||||
describe("chat CLI contract", () => {
|
||||
it("restricts tools, keeps prompts out of argv, resumes explicitly", () => {
|
||||
const args = buildClaudeArgs({ allowShell: false, sessionId: "abc", notebookPath: "notebooks/a.md" });
|
||||
expect(args).toEqual(expect.arrayContaining(["-p", "--restricted", "--strict-mcp-config", "mcp__*", "--include-partial-messages", "--resume", "abc", "acceptEdits"]));
|
||||
expect(args[args.indexOf("--tools") + 1]).toBe("Read,Glob,Grep,Edit,Write,MultiEdit");
|
||||
expect(args.join(" ")).not.toContain("bypassPermissions");
|
||||
expect(args[args.indexOf("--append-system-prompt") + 1]).toContain("notebooks/a.md");
|
||||
const shell = buildClaudeArgs({ allowShell: true });
|
||||
expect(shell[shell.indexOf("--allowedTools") + 1]).toContain(",Bash");
|
||||
});
|
||||
it("parses captured-format fixture records without duplicating text or exposing tool contents", () => {
|
||||
const events = readFileSync(resolve("test/fixtures/chat.jsonl"), "utf8").trim().split("\n").flatMap(line => parseClaudeLine(line, process.cwd()));
|
||||
expect(events.filter(e => e.type === "delta")).toEqual([{ type: "delta", text: "Hello notebook" }]);
|
||||
expect(events).toContainEqual({ type: "tool", name: "Edit", path: "notebooks/setup/nginx.md" });
|
||||
expect(events).toContainEqual({ type: "finished", costUsd: .002, durationMs: 1234 });
|
||||
expect(JSON.stringify(events)).not.toContain("private contents");
|
||||
expect(parseClaudeLine('{"type":"future"}', process.cwd())).toEqual([]);
|
||||
expect(() => parseClaudeLine("bad", process.cwd())).toThrow();
|
||||
});
|
||||
it.each(["../secret", "notebooks/../secret.md", "notebooks/a\\b.md", "/notebooks/a.md", "notebooks/x\n.md"])("rejects invalid notebook %s", path => expect(notebookPath(path)).toBe(false));
|
||||
it.each(["null", "bad", '{"type":"send","message":"a","allowShell":"yes"}', JSON.stringify({ type: "send", message: "a".repeat(32001), allowShell: false })])("rejects invalid client frame %#", text => expect(parseChatMessage(text)).toBeUndefined());
|
||||
});
|
||||
describe("fake CLI lifecycle", () => {
|
||||
it("streams text, extracts session ID, and waits for exit", async () => {
|
||||
const turn = run("hello ' ; $(test)"); await turn.done;
|
||||
expect(turn.sessions).toContain("11111111-1111-4111-8111-111111111111");
|
||||
expect(turn.events.at(-1)).toEqual({ type: "finished", costUsd: .002, durationMs: 1234 });
|
||||
});
|
||||
it.each(["login", "stderr-login"])("detects login failure: %s", async message => {
|
||||
const turn = run(message); await turn.done; expect(turn.events.at(-1)).toMatchObject({ type: "error", code: "login" });
|
||||
});
|
||||
it("detects missing CLI", async () => { const turn = run("a", { executable: join(temp(), "missing-claude"), prefixArgs: [] }); await turn.done; expect(turn.events.at(-1)).toMatchObject({ code: "missing" }); });
|
||||
it("resolves the fake executable on PATH without a shell", async () => {
|
||||
const dir = temp(); const launcher = join(dir, process.platform === "win32" ? "claude.exe" : "claude");
|
||||
if (process.platform === "win32") { try { linkSync(process.execPath, launcher); } catch { copyFileSync(process.execPath, launcher); } }
|
||||
else symlinkSync(process.execPath, launcher);
|
||||
const previous = process.env.PATH;
|
||||
process.env.PATH = dir + (process.platform === "win32" ? ";" : ":") + previous;
|
||||
try { const turn = run("hello", { executable: "claude" }); await turn.done; expect(turn.events.at(-1)?.type).toBe("finished"); }
|
||||
finally { process.env.PATH = previous; }
|
||||
});
|
||||
it.each(["bad", "failed", "huge"])("fails safely on %s output", async message => { const turn = run(message); await turn.done; expect(turn.events.at(-1)?.type).toBe("error"); });
|
||||
it("cancels and reaps the process", async () => { const turn = run("hang"); turn.cancel(); await turn.done; expect(turn.events.at(-1)).toEqual({ type: "finished", cancelled: true }); });
|
||||
it("times out and reaps the process", async () => { const turn = run("hang", { timeoutMs: 100 }); await turn.done; expect(turn.events.at(-1)).toMatchObject({ code: "timeout" }); });
|
||||
});
|
||||
describe("chat route", () => {
|
||||
it("rejects unauthenticated upgrades and foreign origins", async () => {
|
||||
const dir = temp(); const app = await buildApp({ config: { dataDir: dir } });
|
||||
try {
|
||||
expect((await app.inject("/api/chat")).statusCode).toBe(401);
|
||||
await expect(app.injectWS("/api/chat")).rejects.toThrow("401");
|
||||
const cookie = `shellbook_session=${signSession(loadSessionSecret(dir), Date.now() + 60000)}`;
|
||||
expect((await app.inject({ url: "/api/chat", headers: { cookie, origin: "https://evil.example" } })).statusCode).toBe(403);
|
||||
} finally { await app.close(); }
|
||||
});
|
||||
it("persists metadata, prevents concurrent turns, and cancels on disconnect", async () => {
|
||||
const dir = temp(); const config = loadConfig({ dataDir: dir, workspaceDir: process.cwd() });
|
||||
const app = Fastify(); await app.register(websocket); await app.register(chatPlugin, { config, processOptions }); await app.ready();
|
||||
const a = await app.injectWS("/api/chat"); const b = await app.injectWS("/api/chat");
|
||||
const first: any[] = [], second: any[] = [];
|
||||
a.on("message", raw => first.push(JSON.parse(raw.toString()))); b.on("message", raw => second.push(JSON.parse(raw.toString())));
|
||||
try {
|
||||
a.send(JSON.stringify({ type: "send", message: "hang", allowShell: false }));
|
||||
await vi.waitFor(() => expect(first.some(e => e.type === "conversation")).toBe(true));
|
||||
const id = first.find(e => e.type === "conversation").conversation.id;
|
||||
b.send(JSON.stringify({ type: "send", message: "hello", allowShell: false, conversationId: id }));
|
||||
await vi.waitFor(() => expect(second.some(e => e.code === "busy")).toBe(true));
|
||||
[...app.websocketServer.clients][0]!.terminate();
|
||||
await vi.waitFor(() => expect(a.readyState).toBe(3));
|
||||
b.send(JSON.stringify({ type: "send", message: "hello", allowShell: false }));
|
||||
await vi.waitFor(() => expect(second.some(e => e.type === "finished")).toBe(true));
|
||||
const saved = JSON.parse(readFileSync(join(dir, "chat-conversations.json"), "utf8"));
|
||||
expect(saved).toHaveLength(2); expect(saved[1].sessionId).toBeTruthy();
|
||||
expect(Object.keys(saved[1]).sort()).toEqual(["createdAt", "id", "sessionId", "title", "updatedAt"]);
|
||||
} finally { a.terminate(); b.terminate(); await app.close(); }
|
||||
const restart = Fastify(); await restart.register(websocket); await restart.register(chatPlugin, { config, processOptions });
|
||||
try { await restart.ready(); } finally { await restart.close(); }
|
||||
});
|
||||
});
|
||||
Vendored
+4
@@ -0,0 +1,4 @@
|
||||
{"type":"system","subtype":"init","session_id":"11111111-1111-4111-8111-111111111111"}
|
||||
{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hello notebook"}}}
|
||||
{"type":"assistant","message":{"content":[{"type":"text","text":"Hello notebook"},{"type":"tool_use","id":"tool-1","name":"Edit","input":{"file_path":"notebooks/setup/nginx.md","old_string":"private contents","new_string":"other contents"}}]}}
|
||||
{"type":"result","subtype":"success","is_error":false,"session_id":"11111111-1111-4111-8111-111111111111","total_cost_usd":0.002,"duration_ms":1234,"result":"Hello notebook"}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
// Test-only executable. No external network or real CLI calls.
|
||||
const fs = require('node:fs');
|
||||
let input = '';
|
||||
process.stdin.on('data', chunk => input += chunk);
|
||||
process.stdin.on('end', () => {
|
||||
const message = JSON.parse(input).message.content;
|
||||
if (message === 'hang') { setInterval(() => {}, 1000); return; }
|
||||
if (message === 'login') { console.log(JSON.stringify({ type: 'result', subtype: 'error_during_execution', is_error: true, result: 'Not logged in · Please run /login' })); process.exitCode = 1; return; }
|
||||
if (message === 'stderr-login') { process.stderr.write('Authentication required'); process.exitCode = 1; return; }
|
||||
if (message === 'bad') { console.log('not JSON'); return; }
|
||||
if (message === 'huge') { process.stdout.write('x'.repeat(1024 * 1024 + 1)); return; }
|
||||
if (message === 'failed') { process.exitCode = 2; return; }
|
||||
const lines = fs.readFileSync(__dirname + '/chat.jsonl', 'utf8');
|
||||
process.stdout.write(lines);
|
||||
});
|
||||
@@ -0,0 +1,475 @@
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
import {
|
||||
mkdtemp,
|
||||
mkdir,
|
||||
writeFile,
|
||||
readFile,
|
||||
rm,
|
||||
readdir,
|
||||
stat,
|
||||
} from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { generateKeyPairSync, randomUUID, createPrivateKey } from "node:crypto";
|
||||
import { utils } from "ssh2";
|
||||
import { buildApp } from "../src/app";
|
||||
import { loadConfig } from "../src/config";
|
||||
import { validateHost } from "../src/hosts/validation";
|
||||
import { CredentialStore } from "../src/hosts/credentials";
|
||||
import { installKeyScript } from "../src/hosts";
|
||||
import { connect, exec, forgetHostKey, sftp, transfer } from "../src/ssh";
|
||||
import { createSshFixture } from "./ssh-fixture";
|
||||
import { executeRun, EventsHub } from "../src/runs";
|
||||
import { shellQuote, type ServerEvent } from "@shellbook/core";
|
||||
const cleanup: (() => Promise<unknown>)[] = [];
|
||||
afterEach(async () => {
|
||||
for (const fn of cleanup.splice(0).reverse()) await fn();
|
||||
});
|
||||
const host = {
|
||||
name: "demo",
|
||||
address: "example.org",
|
||||
user: "ops",
|
||||
port: 22,
|
||||
tags: ["prod"],
|
||||
};
|
||||
async function fixture(auth = false) {
|
||||
const dir = await mkdtemp(path.join(os.tmpdir(), "shellbook-hosts-"));
|
||||
cleanup.push(() =>
|
||||
rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }),
|
||||
);
|
||||
const config = loadConfig({
|
||||
workspaceDir: path.join(dir, "workspace"),
|
||||
dataDir: path.join(dir, "data"),
|
||||
sshKeyPath: path.join(dir, "key"),
|
||||
});
|
||||
await mkdir(config.workspaceDir);
|
||||
await mkdir(path.join(config.workspaceDir, "notebooks"));
|
||||
await writeFile(
|
||||
path.join(config.workspaceDir, "hosts.yaml"),
|
||||
"# Inventory\nhosts:\n # Production\n - name: demo # stable name\n address: example.org # endpoint\n user: ops\n",
|
||||
);
|
||||
const key = generateKeyPairSync("rsa", { modulusLength: 2048 })
|
||||
.privateKey.export({ format: "pem", type: "pkcs1" })
|
||||
.toString();
|
||||
await writeFile(config.sshKeyPath, key);
|
||||
const app = await buildApp({ config, auth: auth ? {} : false });
|
||||
cleanup.push(() => app.close());
|
||||
return { config, app, key, store: new CredentialStore(config.dataDir) };
|
||||
}
|
||||
it.each([
|
||||
{ name: "../bad" },
|
||||
{ name: "" },
|
||||
{ address: "a b" },
|
||||
{ address: "a/b" },
|
||||
{ address: "999.1.1.1" },
|
||||
{ address: "-host" },
|
||||
{ address: "host:22" },
|
||||
{ user: "-x" },
|
||||
{ user: "a;id" },
|
||||
{ port: 0 },
|
||||
{ port: 65536 },
|
||||
{ port: 1.5 },
|
||||
{ tags: [2] },
|
||||
])("rejects invalid host fields %j", (value) => {
|
||||
expect(() => validateHost({ ...host, ...value })).toThrow();
|
||||
});
|
||||
it.each([
|
||||
"localhost",
|
||||
"example.org",
|
||||
"host-1.example.org.",
|
||||
"127.0.0.1",
|
||||
"::1",
|
||||
"2001:db8::1",
|
||||
])("accepts address %s", (address) => {
|
||||
expect(validateHost({ ...host, address }).address).toBe(address);
|
||||
});
|
||||
it("round-trips YAML comments/order, validates uniqueness, renames and rejects stale saves", async () => {
|
||||
const { app, config, store } = await fixture();
|
||||
const first = (await app.inject("/api/host-management")).json();
|
||||
const url = "/api/host-management/demo";
|
||||
await store.set("demo", { type: "password", password: "kept-on-rename" });
|
||||
const payload = {
|
||||
host: { ...host, name: "renamed" },
|
||||
baseVersion: first.version,
|
||||
};
|
||||
const results = await Promise.all([
|
||||
app.inject({ method: "PUT", url, payload }),
|
||||
app.inject({ method: "PUT", url, payload }),
|
||||
]);
|
||||
expect(results.map((r) => r.statusCode).sort()).toEqual([200, 409]);
|
||||
const source = await readFile(
|
||||
path.join(config.workspaceDir, "hosts.yaml"),
|
||||
"utf8",
|
||||
);
|
||||
for (const comment of [
|
||||
"# Inventory",
|
||||
"# Production",
|
||||
"# stable name",
|
||||
"# endpoint",
|
||||
])
|
||||
expect(source).toContain(comment);
|
||||
expect((await store.get("renamed"))?.input).toEqual({
|
||||
type: "password",
|
||||
password: "kept-on-rename",
|
||||
});
|
||||
expect(await store.get("demo")).toBeUndefined();
|
||||
const current = (await app.inject("/api/host-management")).json();
|
||||
expect(
|
||||
(
|
||||
await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/host-management",
|
||||
payload: {
|
||||
host: { ...host, name: "renamed" },
|
||||
baseVersion: current.version,
|
||||
},
|
||||
})
|
||||
).statusCode,
|
||||
).toBe(409);
|
||||
expect(
|
||||
(
|
||||
await app.inject({
|
||||
method: "DELETE",
|
||||
url: "/api/host-management/renamed",
|
||||
payload: { baseVersion: current.version },
|
||||
})
|
||||
).statusCode,
|
||||
).toBe(200);
|
||||
expect(await store.get("renamed")).toBeUndefined();
|
||||
});
|
||||
it("encrypts credentials, rejects tampering and stores no secrets in workspace", async () => {
|
||||
const { config, store, key } = await fixture();
|
||||
await store.set("demo", { type: "password", password: "very-secret-value" });
|
||||
expect((await store.get("demo"))?.input).toEqual({
|
||||
type: "password",
|
||||
password: "very-secret-value",
|
||||
});
|
||||
const dir = path.join(config.dataDir, "ssh-credentials");
|
||||
const file = path.join(dir, (await readdir(dir))[0]!);
|
||||
const bytes = await readFile(file);
|
||||
expect(bytes.toString()).not.toContain("very-secret-value");
|
||||
if (process.platform !== "win32")
|
||||
for (const f of [file, path.join(config.dataDir, "ssh-credentials.key")])
|
||||
expect((await stat(f)).mode & 0o777).toBe(0o600);
|
||||
bytes[30] = bytes[30]! ^ 1;
|
||||
await writeFile(file, bytes);
|
||||
await expect(store.get("demo")).rejects.toThrow("Cannot decrypt");
|
||||
expect(
|
||||
(await store.set("demo", { type: "privateKey", privateKey: key }))
|
||||
.fingerprint,
|
||||
).toMatch(/^SHA256:/);
|
||||
expect((await store.get("demo"))?.input).toEqual({
|
||||
type: "privateKey",
|
||||
privateKey: key,
|
||||
});
|
||||
await expect(
|
||||
store.set("demo", { type: "privateKey", privateKey: "bad secret" }),
|
||||
).rejects.toThrow("Invalid private key");
|
||||
expect(
|
||||
await readFile(path.join(config.workspaceDir, "hosts.yaml"), "utf8"),
|
||||
).not.toContain("very-secret-value");
|
||||
});
|
||||
it("keeps the API write-only and removes credentials when selecting the default", async () => {
|
||||
const { app } = await fixture();
|
||||
const url = "/api/host-management/demo/credential";
|
||||
const response = await app.inject({
|
||||
method: "PUT",
|
||||
url,
|
||||
payload: { type: "password", password: "browser-never-gets-this" },
|
||||
});
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json()).toMatchObject({
|
||||
type: "password",
|
||||
setAt: expect.any(String),
|
||||
});
|
||||
const inventory = await app.inject("/api/host-management");
|
||||
expect(inventory.body + response.body).not.toContain(
|
||||
"browser-never-gets-this",
|
||||
);
|
||||
expect(inventory.headers["cache-control"]).toBe("no-store");
|
||||
expect((await app.inject(url)).statusCode).toBe(404);
|
||||
expect(
|
||||
(
|
||||
await app.inject({
|
||||
method: "PUT",
|
||||
url,
|
||||
payload: { type: "certificate", privateKey: "secret" },
|
||||
})
|
||||
).statusCode,
|
||||
).toBe(400);
|
||||
await app.inject({ method: "DELETE", url });
|
||||
expect(
|
||||
(await app.inject("/api/host-management")).json().hosts[0].credential,
|
||||
).toEqual({ type: "shellbook" });
|
||||
});
|
||||
it.each([
|
||||
["GET", ""],
|
||||
["POST", ""],
|
||||
["PUT", "/demo"],
|
||||
["DELETE", "/demo"],
|
||||
["PUT", "/demo/credential"],
|
||||
["DELETE", "/demo/credential"],
|
||||
["GET", "/demo/install-key"],
|
||||
["POST", "/demo/action"],
|
||||
["DELETE", "/demo/known-key"],
|
||||
] as const)(
|
||||
"guards %s host management%s with session and origin checks",
|
||||
async (method, suffix) => {
|
||||
const { app } = await fixture(true);
|
||||
expect(
|
||||
(await app.inject({ method, url: "/api/host-management" + suffix }))
|
||||
.statusCode,
|
||||
).toBe(401);
|
||||
expect(
|
||||
(
|
||||
await app.inject({
|
||||
method,
|
||||
url: "/api/host-management" + suffix,
|
||||
headers: { origin: "https://evil.invalid" },
|
||||
})
|
||||
).statusCode,
|
||||
).toBe(403);
|
||||
},
|
||||
);
|
||||
it.each(["password", "keyboard", "privateKey", "encryptedKey"])(
|
||||
"uses stored %s authentication with strict TOFU",
|
||||
async (mode) => {
|
||||
const { config, store, key } = await fixture();
|
||||
const parsed = utils.parseKey(key);
|
||||
if (parsed instanceof Error || Array.isArray(parsed))
|
||||
throw new Error("key");
|
||||
let accepted = false;
|
||||
const ssh = await createSshFixture(config, cleanup, (ctx) => {
|
||||
if (
|
||||
mode === "password" &&
|
||||
ctx.method === "password" &&
|
||||
ctx.password === "ssh-password"
|
||||
) {
|
||||
accepted = true;
|
||||
ctx.accept();
|
||||
} else if (mode === "keyboard" && ctx.method === "keyboard-interactive")
|
||||
ctx.prompt([{ prompt: "Password: ", echo: false }], (answers) => {
|
||||
if (answers[0] === "ssh-password") {
|
||||
accepted = true;
|
||||
ctx.accept();
|
||||
} else ctx.reject();
|
||||
});
|
||||
else if (
|
||||
(mode === "privateKey" || mode === "encryptedKey") &&
|
||||
ctx.method === "publickey" &&
|
||||
ctx.key.data.equals(parsed.getPublicSSH()) &&
|
||||
(!ctx.signature ||
|
||||
parsed.verify(ctx.blob!, ctx.signature, ctx.hashAlgo) === true)
|
||||
) {
|
||||
accepted = true;
|
||||
ctx.accept();
|
||||
} else
|
||||
ctx.reject(
|
||||
mode === "keyboard"
|
||||
? ["keyboard-interactive"]
|
||||
: mode === "password"
|
||||
? ["password"]
|
||||
: ["publickey"],
|
||||
);
|
||||
});
|
||||
await store.set(
|
||||
ssh.host.name,
|
||||
mode === "privateKey" || mode === "encryptedKey"
|
||||
? {
|
||||
type: "privateKey",
|
||||
privateKey:
|
||||
mode === "encryptedKey"
|
||||
? createPrivateKey(key)
|
||||
.export({
|
||||
type: "pkcs1",
|
||||
format: "pem",
|
||||
cipher: "aes-256-cbc",
|
||||
passphrase: "key-passphrase",
|
||||
})
|
||||
.toString()
|
||||
: key,
|
||||
...(mode === "encryptedKey"
|
||||
? { passphrase: "key-passphrase" }
|
||||
: {}),
|
||||
}
|
||||
: { type: "password", password: "ssh-password" },
|
||||
);
|
||||
await expect(connect(config, ssh.host)).rejects.toMatchObject({
|
||||
fingerprint: ssh.fp,
|
||||
});
|
||||
const client = await connect(config, ssh.host, ssh.fp);
|
||||
expect(await exec(client, "true", "", 2000, () => {})).toBe(0);
|
||||
const session = await sftp(client);
|
||||
const output = path.join(config.dataDir, "download.txt");
|
||||
await transfer(session, "fastGet", "/tmp/shellbook-test/out.txt", output);
|
||||
await transfer(session, "fastPut", output, "/tmp/uploaded.txt");
|
||||
expect(ssh.files.get("/tmp/uploaded.txt")?.toString()).toBe(
|
||||
"artifact bytes",
|
||||
);
|
||||
session.end();
|
||||
client.end();
|
||||
expect(accepted).toBe(true);
|
||||
await forgetHostKey(config, ssh.host);
|
||||
await expect(connect(config, ssh.host)).rejects.toMatchObject({
|
||||
fingerprint: ssh.fp,
|
||||
});
|
||||
},
|
||||
);
|
||||
it("renders the exact install command using core quoting and checks the preview before execution", async () => {
|
||||
const publicKey = "ssh-ed25519 AAAA a'comment";
|
||||
const script = installKeyScript(publicKey);
|
||||
expect(script).toContain(`grep -qxF -- ${shellQuote(publicKey)}`);
|
||||
expect(script).toContain(`printf '\\n%s\\n' ${shellQuote(publicKey)}`);
|
||||
const { app, config, store } = await fixture();
|
||||
const ssh = await createSshFixture(config, cleanup);
|
||||
await writeFile(
|
||||
path.join(config.workspaceDir, "hosts.yaml"),
|
||||
JSON.stringify([ssh.host]),
|
||||
);
|
||||
await store.set(ssh.host.name, { type: "password", password: "ssh-secret" });
|
||||
const root = `/api/host-management/${ssh.host.name}`;
|
||||
const preview = (await app.inject(root + "/install-key")).json().script;
|
||||
expect(
|
||||
(
|
||||
await app.inject({
|
||||
method: "POST",
|
||||
url: root + "/action",
|
||||
payload: { action: "install-key", script: "other" },
|
||||
})
|
||||
).statusCode,
|
||||
).toBe(409);
|
||||
const untrusted = (
|
||||
await app.inject({
|
||||
method: "POST",
|
||||
url: root + "/action",
|
||||
payload: { action: "test" },
|
||||
})
|
||||
).json();
|
||||
expect(untrusted.hostKey).toMatchObject({
|
||||
fingerprint: ssh.fp,
|
||||
changed: false,
|
||||
});
|
||||
const result = await app.inject({
|
||||
method: "POST",
|
||||
url: root + "/action",
|
||||
payload: { action: "install-key", script: preview, acceptHostKey: ssh.fp },
|
||||
});
|
||||
expect(result.json()).toEqual({ exitCode: 0 });
|
||||
expect(ssh.received.at(-1)?.input).toBe(preview);
|
||||
});
|
||||
it("redacts credential values in streamed run output and audit", async () => {
|
||||
const { config, store } = await fixture();
|
||||
const ssh = await createSshFixture(config, cleanup);
|
||||
await store.set(ssh.host.name, { type: "password", password: "hello" });
|
||||
const events: ServerEvent[] = [];
|
||||
const hub = new EventsHub();
|
||||
hub.subscribe((e) => events.push(e));
|
||||
await executeRun({
|
||||
config,
|
||||
hub,
|
||||
host: ssh.host,
|
||||
runId: randomUUID(),
|
||||
env: {},
|
||||
request: {
|
||||
notebookPath: "a.md",
|
||||
stepId: "x",
|
||||
params: {},
|
||||
runtime: {},
|
||||
artifactSources: {},
|
||||
acceptHostKey: ssh.fp,
|
||||
},
|
||||
step: {
|
||||
kind: "check",
|
||||
lang: "sh",
|
||||
script: "true",
|
||||
range: { startLine: 1, endLine: 3 },
|
||||
attrs: {
|
||||
id: "x",
|
||||
local: false,
|
||||
sudo: false,
|
||||
confirm: false,
|
||||
artifacts: [],
|
||||
uploads: [],
|
||||
timeoutSec: 5,
|
||||
},
|
||||
},
|
||||
rendered: {
|
||||
stepId: "x",
|
||||
kind: "check",
|
||||
host: ssh.host.name,
|
||||
local: false,
|
||||
script: "true",
|
||||
artifacts: [],
|
||||
uploads: [],
|
||||
missing: [],
|
||||
invalid: {},
|
||||
},
|
||||
});
|
||||
expect(JSON.stringify(events)).not.toContain("hello");
|
||||
expect(JSON.stringify(events)).toContain("[REDACTED]");
|
||||
expect(events.at(-1)).toMatchObject({ type: "run.finished", exitCode: 0 });
|
||||
});
|
||||
|
||||
it("creates one encryption key under concurrent writes", async () => {
|
||||
const { config } = await fixture();
|
||||
await Promise.all(
|
||||
Array.from({ length: 20 }, (_, i) =>
|
||||
new CredentialStore(config.dataDir).set(String(i), {
|
||||
type: "password",
|
||||
password: `password-${i}`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
for (let i = 0; i < 20; i++)
|
||||
expect(
|
||||
(await new CredentialStore(config.dataDir).get(String(i)))?.input,
|
||||
).toEqual({ type: "password", password: `password-${i}` });
|
||||
});
|
||||
|
||||
it("separates appended public keys from an existing unterminated line", () => {
|
||||
expect(installKeyScript("ssh-ed25519 AAA")).toContain("printf '\\n%s\\n'");
|
||||
});
|
||||
|
||||
it("pins an explicit ShellBook authentication snapshot instead of rereading a changed credential", async () => {
|
||||
const { config, store } = await fixture();
|
||||
const ssh = await createSshFixture(config, cleanup, (ctx) =>
|
||||
ctx.method === "publickey" ? ctx.accept() : ctx.reject(["publickey"]),
|
||||
);
|
||||
await store.set(ssh.host.name, {
|
||||
type: "password",
|
||||
password: "wrong-method",
|
||||
});
|
||||
const client = await connect(config, ssh.host, ssh.fp, null);
|
||||
client.end();
|
||||
});
|
||||
|
||||
it("refuses to write credential secrets inside the git workspace", async () => {
|
||||
const { config } = await fixture();
|
||||
const dir = path.join(config.workspaceDir, "data");
|
||||
await expect(
|
||||
new CredentialStore(dir, config.workspaceDir).set("demo", {
|
||||
type: "password",
|
||||
password: "must-not-write",
|
||||
}),
|
||||
).rejects.toThrow("outside the workspace");
|
||||
expect(await readdir(dir)).not.toContain("ssh-credentials.key");
|
||||
});
|
||||
it("tells wrong credentials apart from unreachable hosts on Test connection", async () => {
|
||||
const { app, config, store } = await fixture();
|
||||
const ssh = await createSshFixture(config, cleanup, false);
|
||||
const { createServer } = await import("node:net");
|
||||
const closed = createServer();
|
||||
await new Promise<void>(resolve => closed.listen(0, "127.0.0.1", resolve));
|
||||
const port = (closed.address() as import("node:net").AddressInfo).port;
|
||||
await new Promise(resolve => closed.close(resolve));
|
||||
const offline = { ...ssh.host, name: "offline", port };
|
||||
await writeFile(path.join(config.workspaceDir, "hosts.yaml"), JSON.stringify([ssh.host, offline]));
|
||||
await store.set(ssh.host.name, { type: "password", password: "wrong" });
|
||||
const denied = await app.inject({ method: "POST", url: `/api/host-management/${ssh.host.name}/action`, payload: { action: "test", acceptHostKey: ssh.fp } });
|
||||
expect(denied.statusCode).toBe(502);
|
||||
expect(denied.body).toMatch(/authentication failed/i);
|
||||
expect(denied.body).not.toContain("wrong");
|
||||
const unreachable = await app.inject({ method: "POST", url: "/api/host-management/offline/action", payload: { action: "test" } });
|
||||
expect(unreachable.statusCode).toBe(502);
|
||||
expect(unreachable.body).toMatch(/cannot reach/i);
|
||||
});
|
||||
@@ -13,7 +13,9 @@ import { SerialQueue, safeRelative } from "../src/workspace";
|
||||
import { connect, exec, fingerprint, HostKeyError, localExec, scriptInput } from "../src/ssh";
|
||||
import { executeRun, EventsHub, prepareRun, redactor } from "../src/runs";
|
||||
|
||||
vi.mock("@shellbook/core", () => ({
|
||||
vi.mock("@shellbook/core", async importOriginal => ({
|
||||
// Composition helpers stay real; parsing and rendering are stubbed per test.
|
||||
...pick(await importOriginal<typeof import("@shellbook/core")>(), "composeNotebook", "notebookIncludes", "findStep", "blockActive", "isBuiltin"),
|
||||
parseNotebook: vi.fn((source: string) => ({ title: source.split("\n")[0], params: [], blocks: [], diagnostics: [] })),
|
||||
shellQuote: (value: string) => /^[A-Za-z0-9._/@:=+-]+$/.test(value) ? value : "'" + value.replaceAll("'", "'\\''") + "'",
|
||||
resolveParams: vi.fn((_notebook: Notebook, values: Record<string, string>) => ({ values, errors: {} })),
|
||||
@@ -21,6 +23,9 @@ vi.mock("@shellbook/core", () => ({
|
||||
secretEnv: vi.fn(() => ({})),
|
||||
}));
|
||||
|
||||
function pick<T extends object, K extends keyof T>(object: T, ...keys: K[]) {
|
||||
return Object.fromEntries(keys.map(key => [key, object[key]])) as Pick<T, K>;
|
||||
}
|
||||
const cleanup: (() => Promise<unknown>)[] = [];
|
||||
afterEach(async () => { for (const fn of cleanup.splice(0).reverse()) await fn(); vi.clearAllMocks(); });
|
||||
async function fixture() {
|
||||
@@ -175,9 +180,7 @@ describe("pipeline helpers", () => {
|
||||
expect(events.at(-1)).toMatchObject({ type: "run.finished", exitCode: -1 });
|
||||
});
|
||||
it("refuses missing or invalid parameters before execution", () => {
|
||||
const notebook: Notebook = { title: "Test", params: [], blocks: [{ type: "step", step: step() }], diagnostics: [] };
|
||||
vi.mocked(resolveParams).mockReturnValueOnce({ values: {}, errors: { required: "missing" } });
|
||||
expect(() => prepareRun(notebook, request(), [])).toThrow("Parameters are missing or invalid");
|
||||
const notebook: Notebook = { title: "Test", params: [{ name: "required", type: "string", required: true }], blocks: [{ type: "step", step: step() }], diagnostics: [] };
|
||||
vi.mocked(renderStep).mockReturnValueOnce({ ...rendered(), missing: ["required"] });
|
||||
expect(() => prepareRun(notebook, request(), [])).toThrow("Step parameters are missing or invalid");
|
||||
});
|
||||
|
||||
@@ -205,5 +205,5 @@ it("reports SSH authentication failure without raw transport details", async ()
|
||||
const f = await httpFixture(false);
|
||||
const result = await run(f, 'authorize');
|
||||
expect(result.finished.exitCode).toBe(-1);
|
||||
expect(f.events).toContainEqual({ type: 'run.error', runId: result.id, message: 'SSH authentication failed' });
|
||||
expect(f.events).toContainEqual({ type: 'run.error', runId: result.id, message: 'SSH authentication failed: check the user and the saved password or key' });
|
||||
});
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
import { mkdtemp, mkdir, rm, symlink, stat } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { buildApp } from "../src/app";
|
||||
import { notebookName, notebookDestination } from "../src/workspace/notebooks";
|
||||
import { setPassword } from "../src/auth/credentials";
|
||||
const dirs: string[] = [];
|
||||
afterEach(async () => {
|
||||
for (const dir of dirs.splice(0))
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
});
|
||||
async function setup(auth = false) {
|
||||
const dir = await mkdtemp(join(tmpdir(), "shellbook-notebooks-"));
|
||||
dirs.push(dir);
|
||||
await mkdir(join(dir, "notebooks"));
|
||||
await setPassword(dir, "test password");
|
||||
return {
|
||||
dir,
|
||||
app: await buildApp({
|
||||
config: { workspaceDir: dir, dataDir: dir },
|
||||
auth: auth ? { dataDir: dir } : false,
|
||||
}),
|
||||
};
|
||||
}
|
||||
it.each([
|
||||
"../x.md",
|
||||
"/x.md",
|
||||
"C:/x.md",
|
||||
"a\\x.md",
|
||||
"a/../x.md",
|
||||
"a//x.md",
|
||||
"a.txt",
|
||||
"a/./x.md",
|
||||
"nul.md",
|
||||
"x\u0000.md",
|
||||
"a./x.md",
|
||||
])("rejects invalid notebook path %s", (name) => {
|
||||
expect(() => notebookName(name)).toThrow();
|
||||
});
|
||||
it("rejects symlink parents, files and notebook root", async () => {
|
||||
const { app, dir } = await setup();
|
||||
try {
|
||||
await mkdir(join(dir, "outside"));
|
||||
await symlink(
|
||||
join(dir, "outside"),
|
||||
join(dir, "notebooks", "linked"),
|
||||
"junction",
|
||||
);
|
||||
await expect(
|
||||
notebookDestination({ workspaceDir: dir } as never, "linked/new.md"),
|
||||
).rejects.toThrow("Symlinks");
|
||||
await rm(join(dir, "notebooks"), { recursive: true });
|
||||
await symlink(join(dir, "outside"), join(dir, "notebooks"), "junction");
|
||||
await expect(
|
||||
notebookDestination({ workspaceDir: dir } as never, "new.md"),
|
||||
).rejects.toThrow("Symlinks");
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
it("creates, duplicates, moves, saves and deletes with conflicts and prunes folders", async () => {
|
||||
const { app, dir } = await setup();
|
||||
const url = (p: string) => `/api/notebooks/${encodeURIComponent(p)}`;
|
||||
try {
|
||||
const created = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/notebooks",
|
||||
payload: { path: "old/a.md", source: "# A\n" },
|
||||
});
|
||||
expect(created.statusCode).toBe(200);
|
||||
let baseVersion = created.json().version;
|
||||
expect(
|
||||
(
|
||||
await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/notebooks",
|
||||
payload: { path: "old/a.md", source: "overwrite" },
|
||||
})
|
||||
).statusCode,
|
||||
).toBe(409);
|
||||
for (const op of ["rename", "duplicate"]) {
|
||||
expect(
|
||||
(
|
||||
await app.inject({
|
||||
method: "POST",
|
||||
url: url("old/a.md") + `/${op}`,
|
||||
payload: { path: "new/b.md", baseVersion: "stale" },
|
||||
})
|
||||
).statusCode,
|
||||
).toBe(409);
|
||||
}
|
||||
expect(
|
||||
(
|
||||
await app.inject({
|
||||
method: "POST",
|
||||
url: url("old/a.md") + "/duplicate",
|
||||
payload: { path: "copy.md", baseVersion },
|
||||
})
|
||||
).statusCode,
|
||||
).toBe(200);
|
||||
expect(
|
||||
(
|
||||
await app.inject({
|
||||
method: "POST",
|
||||
url: url("old/a.md") + "/rename",
|
||||
payload: { path: "copy.md", baseVersion },
|
||||
})
|
||||
).statusCode,
|
||||
).toBe(409);
|
||||
expect(
|
||||
(
|
||||
await app.inject({
|
||||
method: "POST",
|
||||
url: url("old/a.md") + "/rename",
|
||||
payload: { path: "new/b.md", baseVersion },
|
||||
})
|
||||
).statusCode,
|
||||
).toBe(200);
|
||||
await expect(stat(join(dir, "notebooks", "old"))).rejects.toThrow();
|
||||
expect((await app.inject(url("new/b.md"))).json().source).toBe("# A\n");
|
||||
const saved = await app.inject({
|
||||
method: "PUT",
|
||||
url: url("new/b.md"),
|
||||
payload: { source: "# B", baseVersion },
|
||||
});
|
||||
expect(saved.statusCode).toBe(200);
|
||||
baseVersion = saved.json().version;
|
||||
expect(
|
||||
(
|
||||
await app.inject({
|
||||
method: "DELETE",
|
||||
url: url("new/b.md"),
|
||||
payload: { baseVersion: "stale" },
|
||||
})
|
||||
).statusCode,
|
||||
).toBe(409);
|
||||
expect(
|
||||
(
|
||||
await app.inject({
|
||||
method: "DELETE",
|
||||
url: url("new/b.md"),
|
||||
payload: { baseVersion },
|
||||
})
|
||||
).statusCode,
|
||||
).toBe(200);
|
||||
await expect(stat(join(dir, "notebooks", "new"))).rejects.toThrow();
|
||||
expect((await app.inject(url("new/b.md"))).statusCode).toBe(404);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
it("guards every management route with session and origin checks", async () => {
|
||||
const { app } = await setup(true);
|
||||
try {
|
||||
const login = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/login",
|
||||
payload: { password: "test password" },
|
||||
});
|
||||
const cookie = String(login.headers["set-cookie"]).split(";")[0]!;
|
||||
for (const [method, url] of [
|
||||
["POST", "/api/notebooks"],
|
||||
["POST", "/api/notebooks/a.md/rename"],
|
||||
["POST", "/api/notebooks/a.md/duplicate"],
|
||||
["DELETE", "/api/notebooks/a.md"],
|
||||
] as const) {
|
||||
expect((await app.inject({ method, url, payload: {} })).statusCode).toBe(
|
||||
401,
|
||||
);
|
||||
expect(
|
||||
(
|
||||
await app.inject({
|
||||
method,
|
||||
url,
|
||||
payload: {},
|
||||
headers: { cookie, origin: "https://evil.test" },
|
||||
})
|
||||
).statusCode,
|
||||
).toBe(403);
|
||||
}
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects notebook reads through a symlinked notebooks root", async () => {
|
||||
const { app, dir } = await setup();
|
||||
try {
|
||||
const { writeFile } = await import("node:fs/promises");
|
||||
await mkdir(join(dir, "outside"));
|
||||
await writeFile(join(dir, "outside", "secret.md"), "private");
|
||||
await rm(join(dir, "notebooks"), { recursive: true });
|
||||
await symlink(join(dir, "outside"), join(dir, "notebooks"), "junction");
|
||||
expect((await app.inject("/api/notebooks/secret.md")).statusCode).toBe(400);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("publishes create/move/delete changes to other tabs through the watcher", async () => {
|
||||
const { vi } = await import("vitest");
|
||||
const { EventsHub } = await import("../src/runs");
|
||||
const dir = await mkdtemp(join(tmpdir(), "shellbook-events-"));
|
||||
dirs.push(dir);
|
||||
await mkdir(join(dir, "notebooks"));
|
||||
const hub = new EventsHub();
|
||||
const events: unknown[] = [];
|
||||
hub.subscribe((event) => events.push(event));
|
||||
const app = await buildApp({
|
||||
config: { workspaceDir: dir, dataDir: dir },
|
||||
auth: false,
|
||||
events: hub,
|
||||
watchNotebooks: true,
|
||||
});
|
||||
try {
|
||||
const created = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/notebooks",
|
||||
payload: { path: "old/a.md", source: "# A" },
|
||||
});
|
||||
await vi.waitFor(() =>
|
||||
expect(events).toContainEqual({ type: "file.changed", path: "old/a.md" }),
|
||||
);
|
||||
expect(
|
||||
(
|
||||
await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/notebooks/old%2Fa.md/rename",
|
||||
payload: { path: "new/a.md", baseVersion: created.json().version },
|
||||
})
|
||||
).statusCode,
|
||||
).toBe(200);
|
||||
await vi.waitFor(() => {
|
||||
expect(events).toContainEqual({ type: "file.deleted", path: "old/a.md" });
|
||||
expect(events).toContainEqual({ type: "file.changed", path: "new/a.md" });
|
||||
});
|
||||
await app.inject({
|
||||
method: "DELETE",
|
||||
url: "/api/notebooks/new%2Fa.md",
|
||||
payload: { baseVersion: created.json().version },
|
||||
});
|
||||
await vi.waitFor(() =>
|
||||
expect(events).toContainEqual({ type: "file.deleted", path: "new/a.md" }),
|
||||
);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
it("does not overwrite concurrent creates", async () => {
|
||||
const { app } = await setup();
|
||||
try {
|
||||
const responses = await Promise.all(
|
||||
["one", "two"].map((source) =>
|
||||
app.inject({
|
||||
method: "POST",
|
||||
url: "/api/notebooks",
|
||||
payload: { path: "race.md", source },
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(responses.map((r) => r.statusCode).sort()).toEqual([200, 409]);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("still opens and saves existing notebooks whose names the create rules would reject", async () => {
|
||||
const { app, dir } = await setup();
|
||||
try {
|
||||
const { writeFile } = await import("node:fs/promises");
|
||||
// Written by git or Claude, not through the create API.
|
||||
await writeFile(join(dir, "notebooks", "Übersicht (alt).md"), "# Old\n");
|
||||
const name = encodeURIComponent("Übersicht (alt).md");
|
||||
const read = await app.inject(`/api/notebooks/${name}`);
|
||||
expect(read.statusCode).toBe(200);
|
||||
const save = await app.inject({ method: "PUT", url: `/api/notebooks/${name}`, payload: { source: "# New\n", baseVersion: read.json().version } });
|
||||
expect(save.statusCode).toBe(200);
|
||||
const moved = await app.inject({ method: "POST", url: `/api/notebooks/${name}/rename`, payload: { path: "uebersicht.md", baseVersion: save.json().version } });
|
||||
expect(moved.statusCode).toBe(200);
|
||||
expect((await app.inject("/api/notebooks/uebersicht.md")).statusCode).toBe(200);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("never removes folders outside notebooks/ when the workspace path is a symlink", async () => {
|
||||
const real = await mkdtemp(join(tmpdir(), "shellbook-real-"));
|
||||
const linkParent = await mkdtemp(join(tmpdir(), "shellbook-link-"));
|
||||
dirs.push(real, linkParent);
|
||||
await mkdir(join(real, "notebooks"));
|
||||
const workspace = join(linkParent, "ws");
|
||||
await symlink(real, workspace, "junction");
|
||||
const app = await buildApp({ config: { workspaceDir: workspace, dataDir: real }, auth: false });
|
||||
try {
|
||||
const created = await app.inject({ method: "POST", url: "/api/notebooks", payload: { path: "a/x.md", source: "# X\n" } });
|
||||
expect(created.statusCode).toBe(200);
|
||||
const deleted = await app.inject({ method: "DELETE", url: `/api/notebooks/${encodeURIComponent("a/x.md")}`, payload: { baseVersion: created.json().version } });
|
||||
expect(deleted.statusCode).toBe(200);
|
||||
expect((await stat(join(real, "notebooks"))).isDirectory()).toBe(true);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,310 @@
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
import {
|
||||
mkdtemp,
|
||||
readFile,
|
||||
rm,
|
||||
stat,
|
||||
writeFile,
|
||||
mkdir,
|
||||
copyFile,
|
||||
} from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { buildApp } from "../src/app";
|
||||
import { setPassword } from "../src/auth/credentials";
|
||||
import { claudeStatus } from "../src/settings";
|
||||
const dirs: string[] = [],
|
||||
apps: FastifyInstance[] = [];
|
||||
async function dir() {
|
||||
const path = await mkdtemp(join(tmpdir(), "settings-"));
|
||||
dirs.push(path);
|
||||
return path;
|
||||
}
|
||||
async function setup(maxAttempts = 5) {
|
||||
const dataDir = await dir();
|
||||
const app = await buildApp({ config: { dataDir }, auth: { maxAttempts } });
|
||||
apps.push(app);
|
||||
return { app, dataDir };
|
||||
}
|
||||
const password = "a long test password";
|
||||
const cookieOf = (r: { headers: Record<string, unknown> }) =>
|
||||
String(r.headers["set-cookie"]).split(";")[0]!;
|
||||
afterEach(async () => {
|
||||
for (const app of apps.splice(0)) await app.close();
|
||||
for (const path of dirs.splice(0))
|
||||
await rm(path, { recursive: true, force: true });
|
||||
});
|
||||
it("creates a persistent private token and consumes it once, including parallel setup", async () => {
|
||||
const { app, dataDir } = await setup();
|
||||
const token = (await readFile(join(dataDir, "setup-token"), "utf8")).trim();
|
||||
expect(token).toMatch(/^[a-f0-9]{64}$/);
|
||||
if (process.platform !== "win32")
|
||||
expect((await stat(join(dataDir, "setup-token"))).mode & 0o777).toBe(0o600);
|
||||
expect((await app.inject("/api/auth/setup")).json()).toEqual({
|
||||
required: true,
|
||||
});
|
||||
expect(
|
||||
(
|
||||
await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/setup",
|
||||
payload: {
|
||||
token: "wrong",
|
||||
newPassword: password,
|
||||
confirmPassword: password,
|
||||
},
|
||||
})
|
||||
).statusCode,
|
||||
).toBe(401);
|
||||
const payload = { token, newPassword: password, confirmPassword: password };
|
||||
const results = await Promise.all(
|
||||
[1, 2].map(() =>
|
||||
app.inject({ method: "POST", url: "/api/auth/setup", payload }),
|
||||
),
|
||||
);
|
||||
expect(results.map((r) => r.statusCode).sort()).toEqual([204, 409]);
|
||||
await expect(stat(join(dataDir, "setup-token"))).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
expect((await app.inject("/api/auth/setup")).json()).toEqual({
|
||||
required: false,
|
||||
});
|
||||
const cookie = cookieOf(results.find((r) => r.statusCode === 204)!);
|
||||
expect(
|
||||
(await app.inject({ url: "/api/auth/me", headers: { cookie } })).statusCode,
|
||||
).toBe(200);
|
||||
if (process.platform !== "win32")
|
||||
expect((await stat(join(dataDir, "auth.json"))).mode & 0o777).toBe(0o600);
|
||||
});
|
||||
it("retains the setup token across restart and removes stale tokens with configured password", async () => {
|
||||
const { app, dataDir } = await setup();
|
||||
const token = await readFile(join(dataDir, "setup-token"), "utf8");
|
||||
await app.close();
|
||||
apps.splice(apps.indexOf(app), 1);
|
||||
const second = await buildApp({ config: { dataDir } });
|
||||
apps.push(second);
|
||||
expect(await readFile(join(dataDir, "setup-token"), "utf8")).toBe(token);
|
||||
await setPassword(dataDir, password);
|
||||
const third = await buildApp({ config: { dataDir } });
|
||||
apps.push(third);
|
||||
await expect(stat(join(dataDir, "setup-token"))).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
});
|
||||
it("shares setup/login limits and rejects weak or mismatched passwords", async () => {
|
||||
const { app, dataDir } = await setup(3);
|
||||
const token = (await readFile(join(dataDir, "setup-token"), "utf8")).trim();
|
||||
for (const [newPassword, confirmPassword] of [
|
||||
["short", "short"],
|
||||
[password, "different"],
|
||||
]) {
|
||||
expect(
|
||||
(
|
||||
await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/setup",
|
||||
payload: { token, newPassword, confirmPassword },
|
||||
})
|
||||
).statusCode,
|
||||
).toBe(400);
|
||||
}
|
||||
expect(
|
||||
(
|
||||
await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/login",
|
||||
payload: { password },
|
||||
})
|
||||
).statusCode,
|
||||
).toBe(401);
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/setup",
|
||||
payload: { token, newPassword: password, confirmPassword: password },
|
||||
});
|
||||
expect(response.statusCode).toBe(429);
|
||||
expect(response.headers["retry-after"]).toBeDefined();
|
||||
});
|
||||
it("keeps every settings route private and setup under the origin check", async () => {
|
||||
const { app } = await setup();
|
||||
for (const [method, url] of [
|
||||
["GET", "/api/settings/system"],
|
||||
["GET", "/api/settings/claude"],
|
||||
["GET", "/api/settings/session"],
|
||||
["POST", "/api/settings/password"],
|
||||
["POST", "/api/settings/sessions/revoke"],
|
||||
["GET", "/api/auth/setup/"],
|
||||
["GET", "/api/auth/setup/extra"],
|
||||
] as const) {
|
||||
expect((await app.inject({ method, url })).statusCode, url).toBe(401);
|
||||
}
|
||||
expect(
|
||||
(
|
||||
await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/setup",
|
||||
headers: { origin: "https://evil.test" },
|
||||
payload: {},
|
||||
})
|
||||
).statusCode,
|
||||
).toBe(403);
|
||||
});
|
||||
it("checks current password, revokes cookies on password change and rotation, survives restart", async () => {
|
||||
const { app, dataDir } = await setup();
|
||||
await setPassword(dataDir, password);
|
||||
const login = async () =>
|
||||
cookieOf(
|
||||
await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/login",
|
||||
payload: { password },
|
||||
}),
|
||||
);
|
||||
const cookie = await login();
|
||||
const payload = {
|
||||
currentPassword: "wrong",
|
||||
newPassword: "new long password",
|
||||
confirmPassword: "new long password",
|
||||
};
|
||||
const change = () =>
|
||||
app.inject({
|
||||
method: "POST",
|
||||
url: "/api/settings/password",
|
||||
headers: { cookie },
|
||||
payload,
|
||||
});
|
||||
expect((await change()).statusCode).toBe(401);
|
||||
payload.currentPassword = password;
|
||||
payload.confirmPassword = "mismatch";
|
||||
expect((await change()).statusCode).toBe(400);
|
||||
payload.confirmPassword = payload.newPassword;
|
||||
const changed = await change();
|
||||
expect(changed.statusCode).toBe(204);
|
||||
const fresh = cookieOf(changed);
|
||||
expect(
|
||||
(await app.inject({ url: "/api/auth/me", headers: { cookie } })).statusCode,
|
||||
).toBe(401);
|
||||
expect(
|
||||
(
|
||||
await app.inject({
|
||||
url: "/api/settings/session",
|
||||
headers: { cookie: fresh },
|
||||
})
|
||||
).json(),
|
||||
).toEqual({ lifetimeSeconds: 2592000 });
|
||||
const oldSecret = await readFile(join(dataDir, "session-secret"));
|
||||
const revoked = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/settings/sessions/revoke",
|
||||
headers: { cookie: fresh },
|
||||
});
|
||||
expect(revoked.statusCode).toBe(204);
|
||||
expect(await readFile(join(dataDir, "session-secret"))).not.toEqual(
|
||||
oldSecret,
|
||||
);
|
||||
expect(
|
||||
(await app.inject({ url: "/api/auth/me", headers: { cookie: fresh } }))
|
||||
.statusCode,
|
||||
).toBe(401);
|
||||
const renewed = cookieOf(revoked);
|
||||
const second = await buildApp({ config: { dataDir } });
|
||||
apps.push(second);
|
||||
expect(
|
||||
(
|
||||
await second.inject({
|
||||
url: "/api/settings/system",
|
||||
headers: { cookie: renewed },
|
||||
})
|
||||
).json(),
|
||||
).toMatchObject({
|
||||
dataDirPath: dataDir,
|
||||
nodeVersion: process.version,
|
||||
version: "0.0.0",
|
||||
});
|
||||
await setPassword(dataDir, "CLI changed password");
|
||||
expect(
|
||||
(await second.inject({ url: "/api/auth/me", headers: { cookie: renewed } }))
|
||||
.statusCode,
|
||||
).toBe(401);
|
||||
});
|
||||
it("reports absent CLI/credentials without reading contents", async () => {
|
||||
const home = await dir();
|
||||
expect(await claudeStatus(home, { PATH: home })).toEqual({
|
||||
available: false,
|
||||
version: null,
|
||||
loginAppearsPresent: false,
|
||||
});
|
||||
await mkdir(join(home, ".claude"));
|
||||
await mkdir(join(home, ".claude", ".credentials.json"));
|
||||
expect((await claudeStatus(home, { PATH: home })).loginAppearsPresent).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
it("runs a fake Claude executable from PATH with argv", async () => {
|
||||
const home = await dir();
|
||||
if (process.platform === "win32") {
|
||||
await copyFile(process.execPath, join(home, "claude.exe"));
|
||||
expect(
|
||||
await claudeStatus(home, {
|
||||
PATH: home,
|
||||
SystemRoot: process.env.SystemRoot,
|
||||
}),
|
||||
).toEqual({
|
||||
available: true,
|
||||
version: process.version,
|
||||
loginAppearsPresent: false,
|
||||
});
|
||||
return;
|
||||
}
|
||||
await writeFile(
|
||||
join(home, "claude"),
|
||||
'#!/bin/sh\n[ "$1" = --version ] || exit 1\nprintf "fake-claude 1.0\\n"\n',
|
||||
{ mode: 0o700 },
|
||||
);
|
||||
expect(await claudeStatus(home, { PATH: home })).toEqual({
|
||||
available: true,
|
||||
version: "fake-claude 1.0",
|
||||
loginAppearsPresent: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("closes active WebSockets on password changes and sign-out-all", async () => {
|
||||
const { app, dataDir } = await setup();
|
||||
await setPassword(dataDir, password);
|
||||
app.get("/api/test-socket", { websocket: true }, (socket) => {
|
||||
socket.send("ready");
|
||||
});
|
||||
let cookie = cookieOf(
|
||||
await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/login",
|
||||
payload: { password },
|
||||
}),
|
||||
);
|
||||
for (const url of [
|
||||
"/api/settings/password",
|
||||
"/api/settings/sessions/revoke",
|
||||
]) {
|
||||
const ws = await app.injectWS("/api/test-socket", { headers: { cookie } });
|
||||
const closed = new Promise((resolve) => ws.on("close", resolve));
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url,
|
||||
headers: { cookie },
|
||||
payload: url.endsWith("password")
|
||||
? {
|
||||
currentPassword: password,
|
||||
newPassword: "changed test password",
|
||||
confirmPassword: "changed test password",
|
||||
}
|
||||
: {},
|
||||
});
|
||||
expect(response.statusCode).toBe(204);
|
||||
await closed;
|
||||
await expect(
|
||||
app.injectWS("/api/test-socket", { headers: { cookie } }),
|
||||
).rejects.toThrow("401");
|
||||
cookie = cookieOf(response);
|
||||
}
|
||||
});
|
||||
@@ -3,7 +3,7 @@ import { Server, utils, type Connection } from "ssh2";
|
||||
import type { HostInfo } from "@shellbook/core";
|
||||
import type { ServerConfig } from "../src/config";
|
||||
import { fingerprint } from "../src/ssh";
|
||||
export async function createSshFixture(config: ServerConfig, cleanup: (() => Promise<unknown>)[], authenticate = true) {
|
||||
export async function createSshFixture(config: ServerConfig, cleanup: (() => Promise<unknown>)[], authenticate: boolean | ((ctx: import("ssh2").AuthContext) => void) = true) {
|
||||
const key = generateKeyPairSync("rsa", { modulusLength: 2048 }).privateKey.export({ type: "pkcs1", format: "pem" }).toString();
|
||||
const parsed = utils.parseKey(key);
|
||||
if (parsed instanceof Error) throw parsed;
|
||||
@@ -15,7 +15,7 @@ export async function createSshFixture(config: ServerConfig, cleanup: (() => Pro
|
||||
clients.add(client);
|
||||
client.on("error", () => {});
|
||||
client.on("close", () => clients.delete(client));
|
||||
client.on("authentication", ctx => authenticate ? ctx.accept() : ctx.reject());
|
||||
client.on("authentication", ctx => typeof authenticate === "function" ? authenticate(ctx) : authenticate ? ctx.accept() : ctx.reject());
|
||||
client.on("ready", () => client.on("session", accept => {
|
||||
const session = accept();
|
||||
session.on("exec", (acceptExec, _reject, info) => {
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { buildApp } from "../src/app";
|
||||
import type { UpdateOptions } from "../src/update";
|
||||
|
||||
const dirs: string[] = [];
|
||||
const apps: FastifyInstance[] = [];
|
||||
afterEach(async () => {
|
||||
for (const app of apps.splice(0)) await app.close();
|
||||
for (const path of dirs.splice(0)) await rm(path, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
type Reply = string | Error;
|
||||
/** Fake for `git`/`systemctl`: answers by "file arg arg…" prefix and records every call. */
|
||||
function fakeRun(answers: Record<string, Reply>) {
|
||||
const calls: string[][] = [];
|
||||
const run: UpdateOptions["run"] = async (file, args) => {
|
||||
calls.push([file, ...args]);
|
||||
const line = [file, ...args].join(" ");
|
||||
const key = Object.keys(answers).sort((a, b) => b.length - a.length).find((k) => line.startsWith(k));
|
||||
if (key === undefined) throw new Error(`unexpected command: ${line}`);
|
||||
const answer = answers[key]!;
|
||||
if (answer instanceof Error) throw answer;
|
||||
return answer;
|
||||
};
|
||||
return { run, calls };
|
||||
}
|
||||
|
||||
const show = (state: string, result = "success", start = "@1763300000", exit = "@1763300090") =>
|
||||
`ActiveState=${state}\nResult=${result}\nExecMainStartTimestamp=${start}\nExecMainExitTimestamp=${exit}\n`;
|
||||
const git = (repo: string) => `git -C ${repo}`;
|
||||
|
||||
async function setup(answers: Record<string, Reply>, installed = true, withAuth = false) {
|
||||
const root = await mkdtemp(join(tmpdir(), "update-"));
|
||||
dirs.push(root);
|
||||
const triggerUnit = join(root, "shellbook-update.path");
|
||||
if (installed) await writeFile(triggerUnit, "[Path]\n");
|
||||
const fake = fakeRun(answers);
|
||||
const options: Partial<UpdateOptions> = {
|
||||
triggerUnit,
|
||||
logFile: join(root, "update.log"),
|
||||
repoDir: join(root, "repo"),
|
||||
run: fake.run,
|
||||
};
|
||||
const app = await buildApp({ config: { dataDir: join(root, "data") }, auth: withAuth ? undefined : false, update: options });
|
||||
apps.push(app);
|
||||
return { app, root, repo: options.repoDir!, calls: fake.calls, requestFile: join(root, "data", "update-request"), logFile: options.logFile! };
|
||||
}
|
||||
|
||||
it("reports the installed commit, the last run and the end of its log", async () => {
|
||||
const { app, logFile, calls } = await setup({
|
||||
"git -C": "abc1234\n",
|
||||
"systemctl show shellbook-update.service": show("inactive"),
|
||||
});
|
||||
const lines = Array.from({ length: 400 }, (_, i) => `line ${i}`);
|
||||
await writeFile(logFile, lines.join("\n") + "\n");
|
||||
const status = (await app.inject("/api/settings/update")).json();
|
||||
expect(status).toMatchObject({
|
||||
available: true,
|
||||
state: "succeeded",
|
||||
current: "abc1234",
|
||||
startedAt: new Date(1763300000 * 1000).toISOString(),
|
||||
finishedAt: new Date(1763300090 * 1000).toISOString(),
|
||||
});
|
||||
// Only the end of a long log is returned.
|
||||
expect(status.log.split("\n")[0]).toBe("line 200");
|
||||
expect(status.log).toContain("line 399");
|
||||
// Read-only queries only, with argv (no shell).
|
||||
expect(calls.map((c) => c[0])).toEqual(expect.arrayContaining(["git", "systemctl"]));
|
||||
expect(calls.find((c) => c[0] === "systemctl")).toEqual([
|
||||
"systemctl", "show", "shellbook-update.service", "--timestamp=unix",
|
||||
"--property=ActiveState,Result,ExecMainStartTimestamp,ExecMainExitTimestamp",
|
||||
]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[show("activating", "success", "@1763300000", ""), "running"],
|
||||
[show("failed", "exit-code"), "failed"],
|
||||
[show("inactive", "success", "", ""), "idle"],
|
||||
])("maps unit state %#", async (output, state) => {
|
||||
const { app } = await setup({ "git -C": "abc1234\n", "systemctl show": output });
|
||||
expect((await app.inject("/api/settings/update")).json().state).toBe(state);
|
||||
});
|
||||
|
||||
it("says so when systemd cannot be asked, and is unavailable without the trigger unit", async () => {
|
||||
const broken = await setup({ "git -C": new Error("no git"), "systemctl show": new Error("no systemd") });
|
||||
expect((await broken.app.inject("/api/settings/update")).json()).toMatchObject({ available: true, state: "unknown", current: null });
|
||||
const missing = await setup({ "git -C": "abc1234\n" }, false);
|
||||
expect((await missing.app.inject("/api/settings/update")).json()).toMatchObject({ available: false, state: "idle", current: "abc1234" });
|
||||
// Never asks systemd or writes a request without the units.
|
||||
expect(missing.calls.some((c) => c[0] === "systemctl")).toBe(false);
|
||||
expect((await missing.app.inject({ method: "POST", url: "/api/settings/update", payload: {} })).statusCode).toBe(409);
|
||||
await expect(stat(missing.requestFile)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
});
|
||||
|
||||
it("starts an update only by writing the request file, and never twice at once", async () => {
|
||||
const idle = await setup({ "git -C": "abc1234\n", "systemctl show": show("inactive") });
|
||||
const started = await idle.app.inject({ method: "POST", url: "/api/settings/update", payload: {} });
|
||||
expect(started.statusCode).toBe(202);
|
||||
const { requestedAt } = started.json();
|
||||
expect(Date.parse(requestedAt)).not.toBeNaN();
|
||||
expect((await readFile(idle.requestFile, "utf8")).trim()).toBe(requestedAt);
|
||||
// The server itself never starts units or runs the updater.
|
||||
expect(idle.calls.filter((c) => c[0] === "systemctl").every((c) => c[1] === "show")).toBe(true);
|
||||
const busy = await setup({ "git -C": "abc1234\n", "systemctl show": show("active", "success", "@1763300000", "") });
|
||||
expect((await busy.app.inject({ method: "POST", url: "/api/settings/update", payload: {} })).statusCode).toBe(409);
|
||||
});
|
||||
|
||||
it("checks the tracked branch and lists the commits an update would bring", async () => {
|
||||
const answers: Record<string, Reply> = {};
|
||||
const target = await setup(answers);
|
||||
Object.assign(answers, {
|
||||
[`${git(target.repo)} rev-parse --short HEAD`]: "abc1234\n",
|
||||
[`${git(target.repo)} symbolic-ref -q --short HEAD`]: "main\n",
|
||||
[`${git(target.repo)} rev-parse --abbrev-ref --symbolic-full-name @{u}`]: "origin/main\n",
|
||||
[`${git(target.repo)} fetch --quiet --no-tags -- origin main`]: "",
|
||||
[`${git(target.repo)} rev-parse --short FETCH_HEAD`]: "def5678\n",
|
||||
[`${git(target.repo)} log --format=%h%x09%s -n 50 HEAD..FETCH_HEAD`]: "def5678\tfeat(web): b\nbbb0000\tfix: a\ttab\n",
|
||||
"systemctl show": show("inactive"),
|
||||
});
|
||||
const result = await target.app.inject({ method: "POST", url: "/api/settings/update/check", payload: {} });
|
||||
expect(result.statusCode).toBe(200);
|
||||
expect(result.json()).toEqual({
|
||||
current: "abc1234",
|
||||
latest: "def5678",
|
||||
pinned: false,
|
||||
changes: [
|
||||
{ commit: "def5678", subject: "feat(web): b" },
|
||||
{ commit: "bbb0000", subject: "fix: a\ttab" },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("reports a pinned checkout without fetching, and a failed fetch as 502", async () => {
|
||||
const pinnedAnswers: Record<string, Reply> = {};
|
||||
const pinned = await setup(pinnedAnswers);
|
||||
Object.assign(pinnedAnswers, {
|
||||
[`${git(pinned.repo)} rev-parse --short HEAD`]: "abc1234\n",
|
||||
[`${git(pinned.repo)} symbolic-ref -q --short HEAD`]: new Error("detached"),
|
||||
"systemctl show": show("inactive"),
|
||||
});
|
||||
const result = await pinned.app.inject({ method: "POST", url: "/api/settings/update/check", payload: {} });
|
||||
expect(result.json()).toEqual({ current: "abc1234", latest: null, pinned: true, changes: [] });
|
||||
expect(pinned.calls.some((c) => c.includes("fetch"))).toBe(false);
|
||||
|
||||
const offlineAnswers: Record<string, Reply> = {};
|
||||
const offline = await setup(offlineAnswers);
|
||||
Object.assign(offlineAnswers, {
|
||||
[`${git(offline.repo)} rev-parse --short HEAD`]: "abc1234\n",
|
||||
[`${git(offline.repo)} symbolic-ref -q --short HEAD`]: "main\n",
|
||||
[`${git(offline.repo)} rev-parse --abbrev-ref --symbolic-full-name @{u}`]: "origin/main\n",
|
||||
[`${git(offline.repo)} fetch`]: new Error("Could not resolve host"),
|
||||
"systemctl show": show("inactive"),
|
||||
});
|
||||
const failed = await offline.app.inject({ method: "POST", url: "/api/settings/update/check", payload: {} });
|
||||
expect(failed.statusCode).toBe(502);
|
||||
// The git error text stays in the server log, not in the response.
|
||||
expect(failed.body).not.toContain("resolve host");
|
||||
});
|
||||
|
||||
it("requires a session", async () => {
|
||||
const { app } = await setup({ "git -C": "abc1234\n", "systemctl show": show("inactive") }, true, true);
|
||||
expect((await app.inject("/api/settings/update")).statusCode).toBe(401);
|
||||
expect((await app.inject({ method: "POST", url: "/api/settings/update", payload: {} })).statusCode).toBe(401);
|
||||
});
|
||||
@@ -4,34 +4,39 @@ import { join } from "node:path";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import { createNotebookWatcher, type NotebookFileEvent } from "../src/watch/index";
|
||||
|
||||
// Generous timings: the full parallel test run on Windows can delay fs events by >100 ms.
|
||||
const debounceMs = 300;
|
||||
const settle = { timeout: 5000 };
|
||||
const quiet = () => new Promise((r) => setTimeout(r, debounceMs * 3));
|
||||
|
||||
it("watches nested Markdown, debounces writes, handles atomic saves/deletes and unsubscribes", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "shellbook-watch-"));
|
||||
await mkdir(join(dir, "notebooks", "setup"), { recursive: true });
|
||||
const file = join(dir, "notebooks", "setup", "test.md");
|
||||
await writeFile(file, "initial");
|
||||
const watcher = createNotebookWatcher(dir, { debounceMs: 100 });
|
||||
const watcher = createNotebookWatcher(dir, { debounceMs });
|
||||
const events: NotebookFileEvent[] = [];
|
||||
const off = watcher.on((event) => events.push(event));
|
||||
try {
|
||||
await watcher.ready;
|
||||
expect(events).toEqual([]);
|
||||
await writeFile(file, "first"); await writeFile(file, "second");
|
||||
await vi.waitFor(() => expect(events).toEqual([{ type: "file.changed", path: "setup/test.md" }]));
|
||||
await vi.waitFor(() => expect(events).toEqual([{ type: "file.changed", path: "setup/test.md" }]), settle);
|
||||
await writeFile(`${file}.tmp`, "replacement"); await rename(`${file}.tmp`, file);
|
||||
await vi.waitFor(() => expect(events).toHaveLength(2));
|
||||
await vi.waitFor(() => expect(events).toHaveLength(2), settle);
|
||||
expect(events[1]).toEqual({ type: "file.changed", path: "setup/test.md" });
|
||||
await rm(file);
|
||||
await vi.waitFor(() => expect(events[2]).toEqual({ type: "file.deleted", path: "setup/test.md" }));
|
||||
await vi.waitFor(() => expect(events[2]).toEqual({ type: "file.deleted", path: "setup/test.md" }), settle);
|
||||
await mkdir(join(dir, "notebooks", "new"));
|
||||
await writeFile(join(dir, "notebooks", "new", "added.md"), "new");
|
||||
await vi.waitFor(() => expect(events[3]).toEqual({ type: "file.changed", path: "new/added.md" }));
|
||||
await vi.waitFor(() => expect(events[3]).toEqual({ type: "file.changed", path: "new/added.md" }), settle);
|
||||
await writeFile(join(dir, "notebooks", "ignored.txt"), "ignore");
|
||||
await writeFile(join(dir, "outside.md"), "ignore");
|
||||
await new Promise((r) => setTimeout(r, 300)); expect(events).toHaveLength(4);
|
||||
await quiet(); expect(events).toHaveLength(4);
|
||||
off(); await writeFile(file, "unsubscribed");
|
||||
await new Promise((r) => setTimeout(r, 300)); expect(events).toHaveLength(4);
|
||||
await quiet(); expect(events).toHaveLength(4);
|
||||
} finally { await watcher.close(); await rm(dir, { recursive: true, force: true }); }
|
||||
});
|
||||
}, 30_000);
|
||||
|
||||
it("starts before notebooks exists and cancels pending notifications on close", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "shellbook-watch-"));
|
||||
@@ -44,3 +49,16 @@ it("starts before notebooks exists and cancels pending notifications on close",
|
||||
await new Promise((r) => setTimeout(r, 600)); expect(listener).not.toHaveBeenCalled();
|
||||
} finally { await watcher.close(); await rm(dir, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
it("publishes hosts.yaml changes, atomic replacements and deletion", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "shellbook-hostwatch-"));
|
||||
const file = join(dir, "hosts.yaml"); await writeFile(file, "[]");
|
||||
const watcher = createNotebookWatcher(dir, { debounceMs: 10 });
|
||||
const events: NotebookFileEvent[] = []; watcher.on(e => events.push(e));
|
||||
try {
|
||||
await watcher.ready; await writeFile(file + ".tmp", "# changed\n[]"); await rename(file + ".tmp", file);
|
||||
await vi.waitFor(() => expect(events).toContainEqual({ type: "file.changed", path: "hosts.yaml" }));
|
||||
await rm(file);
|
||||
await vi.waitFor(() => expect(events).toContainEqual({ type: "file.deleted", path: "hosts.yaml" }));
|
||||
} finally { await watcher.close(); await rm(dir, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
@@ -82,3 +82,31 @@ and reconnect. App tests drive the SSH-key fixture through keygen, sensitive art
|
||||
downloads (including 410), after sections, capture substitution, and authorize
|
||||
artifact provenance. Real tmux/Claude login and browser terminal rendering still
|
||||
need an interactive server check.
|
||||
|
||||
## Notebook management and authoring
|
||||
|
||||
The sidebar groups notebooks into folders and filters by title or path. **New notebook**
|
||||
asks for a name, optional folder and title, then opens a valid starter with a host
|
||||
parameter, a read-only check, and a confirmed run placeholder. **Rename / move** and
|
||||
**Duplicate** take a destination path relative to `notebooks/` (including `.md`).
|
||||
Folders are created automatically; empty folders disappear after moves or deletes.
|
||||
**Delete** requires explicit confirmation. Names use letters, numbers, spaces, dots,
|
||||
underscores and hyphens; traversal, absolute paths, symlinks and Windows device names
|
||||
are rejected. Management needs a real server; the demo reports that limitation.
|
||||
|
||||
In edit mode, the toolbar inserts Check, Run, Artifacts, Upload or Capture examples
|
||||
at the cursor, targeting the local ShellBook server or a declared host parameter.
|
||||
Review example commands and file names before execution. **Parameter** adds a YAML
|
||||
mapping via a form (including choice options and secret rules), preserving unrelated
|
||||
YAML and comments. **After step** selects an existing step for conditional instructions.
|
||||
**Format help** explains attributes and parameter references. Save and live preview
|
||||
continue to use the core parser. Attribute editing remains available in Markdown.
|
||||
|
||||
All mutations use authenticated, same-origin API calls. Save, move, duplicate and
|
||||
delete use optimistic versions (409 means stale content or an occupied destination).
|
||||
Files publish atomically, and the existing watcher refreshes other tabs' lists and
|
||||
clean open documents. External rename/delete retains the old open draft with a
|
||||
notice; select the new path from the refreshed list. Unsaved edits require confirmation
|
||||
before navigation or management. External filesystem writers must be trusted: as with
|
||||
other workspace operations, symlink checks cannot prevent a privileged local process
|
||||
from swapping path components between filesystem calls.
|
||||
|
||||
@@ -4,6 +4,11 @@
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="color-scheme" content="dark light" />
|
||||
<meta name="theme-color" content="#141a22" />
|
||||
<link rel="icon" href="/shellbook.svg" type="image/svg+xml" />
|
||||
<link rel="icon" href="/icon-192.png" type="image/png" sizes="192x192" />
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||
<link rel="manifest" href="/manifest.webmanifest" />
|
||||
<title>ShellBook</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -19,7 +19,8 @@
|
||||
"codemirror": "^6.0.1",
|
||||
"highlight.js": "^11.10.0",
|
||||
"@xterm/xterm": "^5.5.0",
|
||||
"@xterm/addon-fit": "^0.10.0"
|
||||
"@xterm/addon-fit": "^0.10.0",
|
||||
"yaml": "^2.6.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^18.3.12",
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 3.4 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 4.7 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "ShellBook",
|
||||
"short_name": "ShellBook",
|
||||
"description": "Notebook-style server runbooks",
|
||||
"start_url": "/",
|
||||
"display": "standalone",
|
||||
"background_color": "#11151b",
|
||||
"theme_color": "#141a22",
|
||||
"icons": [
|
||||
{ "src": "/shellbook.svg", "type": "image/svg+xml", "sizes": "any" },
|
||||
{ "src": "/icon-192.png", "type": "image/png", "sizes": "192x192" },
|
||||
{ "src": "/icon-512.png", "type": "image/png", "sizes": "512x512" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="ShellBook">
|
||||
<!-- Dark tile so the mark reads on light and dark tabs alike. -->
|
||||
<rect width="64" height="64" rx="14" fill="#141a22"/>
|
||||
<!-- Notebook: mint cover with a darker spine. -->
|
||||
<rect x="11" y="7" width="42" height="50" rx="6" fill="#86dab9"/>
|
||||
<path d="M17 7h5v50h-5a6 6 0 0 1-6-6V13a6 6 0 0 1 6-6z" fill="#4fa985"/>
|
||||
<!-- Bookmark ribbon. -->
|
||||
<path d="M41 7h7v16l-3.5-3-3.5 3z" fill="#f2c56b"/>
|
||||
<!-- Shell prompt: >_ -->
|
||||
<path d="M28.5 25.5l8 6.5-8 6.5" fill="none" stroke="#141a22" stroke-width="5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M39.5 41.5h8" fill="none" stroke="#141a22" stroke-width="5" stroke-linecap="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 759 B |
+469
-251
@@ -1,3 +1,7 @@
|
||||
import { HeaderNavigation, type NavigationPage } from "./HeaderNavigation";
|
||||
import { SettingsPage } from "./SettingsPage";
|
||||
import { SetupScreen } from "./SetupScreen";
|
||||
import { settingsApi } from "./settingsApi";
|
||||
import {
|
||||
lazy,
|
||||
Suspense,
|
||||
@@ -9,10 +13,15 @@ import {
|
||||
} from "react";
|
||||
import ReactMarkdown from "react-markdown";
|
||||
import {
|
||||
blockActive,
|
||||
groupInputs,
|
||||
notebookIncludes,
|
||||
parseNotebook,
|
||||
renderHost,
|
||||
renderStep,
|
||||
renderText,
|
||||
resolveParams,
|
||||
scopeActive,
|
||||
} from "@shellbook/core";
|
||||
import type {
|
||||
Block,
|
||||
@@ -24,11 +33,21 @@ import type {
|
||||
StartRunRequest,
|
||||
Step,
|
||||
} from "@shellbook/core";
|
||||
import { NotebookList } from "./NotebookList";
|
||||
import { HostKeyConfirmation } from "./HostKeyConfirmation";
|
||||
import { HostsPage } from "./HostsPage";
|
||||
import { HttpError } from "./api";
|
||||
import type { Api } from "./api";
|
||||
import { emptySession, eventReducer, stepKey } from "./events";
|
||||
import { ParamsForm } from "./ParamsForm";
|
||||
import { ParamField, ParamsForm, type ParamGroup } from "./ParamsForm";
|
||||
import { GroupSection } from "./GroupSection";
|
||||
import { HostBlockCard } from "./HostBlockCard";
|
||||
import { StepCard } from "./StepCard";
|
||||
import { ChatPanel } from "./ChatPanel";
|
||||
import { parseRoute, routeHash } from "./route";
|
||||
import { recallValues, rememberValues } from "./paramMemory";
|
||||
import { Dialog, Logo } from "./ui";
|
||||
import { readFlag, writeFlag } from "./uiPrefs";
|
||||
const TerminalSlot = lazy(() =>
|
||||
import("./TerminalSlot").then((module) => ({ default: module.TerminalSlot })),
|
||||
);
|
||||
@@ -38,23 +57,34 @@ const Editor = lazy(() =>
|
||||
|
||||
function steps(blocks: Block[]): Step[] {
|
||||
return blocks.flatMap((block) =>
|
||||
block.type === "step"
|
||||
? [block.step]
|
||||
: block.type === "after"
|
||||
? steps(block.blocks)
|
||||
: [],
|
||||
block.type === "step" ? [block.step] : "blocks" in block ? steps(block.blocks) : [],
|
||||
);
|
||||
}
|
||||
type UseBlock = Extract<Block, { type: "use" }>;
|
||||
/** Included notebooks (`::use`, nested too), whose parameters the form shows as groups. */
|
||||
function includes(blocks: Block[]): UseBlock[] {
|
||||
return blocks.flatMap((block): UseBlock[] =>
|
||||
block.type === "use" ? [block, ...includes(block.blocks)] : "blocks" in block ? includes(block.blocks) : [],
|
||||
);
|
||||
}
|
||||
/** Values that are set; unset ones stay visible as `{{name}}` in prose. */
|
||||
function setValuesOnly(values: ParamValues): ParamValues {
|
||||
return Object.fromEntries(Object.entries(values).filter(([, value]) => value));
|
||||
}
|
||||
export function App({ api }: { api: Api }) {
|
||||
const [auth, setAuth] = useState<"loading" | "login" | "ready">("loading");
|
||||
const initialRoute = useRef(parseRoute(location.hash));
|
||||
const [auth, setAuth] = useState<"loading" | "login" | "setup" | "ready">("loading");
|
||||
const [page, setPage] = useState<NavigationPage>(initialRoute.current.page);
|
||||
const [password, setPassword] = useState("");
|
||||
const [list, setList] = useState<NotebookSummary[]>([]);
|
||||
const [list, setList] = useState<NotebookSummary[]>();
|
||||
const [hosts, setHosts] = useState<HostInfo[]>([]);
|
||||
const [doc, setDoc] = useState<NotebookResponse>();
|
||||
const [source, setSource] = useState("");
|
||||
const [values, setValues] = useState<ParamValues>({});
|
||||
const [edit, setEdit] = useState(false);
|
||||
const [terminal, setTerminal] = useState(false);
|
||||
const [chat, setChat] = useState(false);
|
||||
const [paramsOpen, setParamsOpen] = useState(() => readFlag("params-open", true));
|
||||
const [terminalOpened, setTerminalOpened] = useState(false);
|
||||
const [conflict, setConflict] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
@@ -88,7 +118,7 @@ export function App({ api }: { api: Api }) {
|
||||
setConflict(false);
|
||||
setError("");
|
||||
if (!same) {
|
||||
setValues({});
|
||||
setValues(recallValues(path, next.notebook));
|
||||
setEdit(false);
|
||||
setCheckIds([]);
|
||||
}
|
||||
@@ -98,13 +128,18 @@ export function App({ api }: { api: Api }) {
|
||||
},
|
||||
[api],
|
||||
);
|
||||
const leave = () => !current.current.dirty || window.confirm("Discard unsaved edits?");
|
||||
useEffect(() => {
|
||||
void api
|
||||
.me()
|
||||
.then(() => setAuth("ready"))
|
||||
.catch((e) => {
|
||||
if (e instanceof HttpError && e.status === 401) setAuth("login");
|
||||
else setError(String(e));
|
||||
if (e instanceof HttpError && e.status === 401) {
|
||||
setAuth("login");
|
||||
void settingsApi.setupStatus()
|
||||
.then(status => { if (status.required) setAuth("setup"); })
|
||||
.catch(() => {});
|
||||
} else setError(String(e));
|
||||
});
|
||||
}, [api]);
|
||||
useEffect(() => {
|
||||
@@ -115,12 +150,30 @@ export function App({ api }: { api: Api }) {
|
||||
if (!active) return;
|
||||
setList(notebooks.notebooks);
|
||||
setHosts(inventory.hosts);
|
||||
if (notebooks.notebooks[0]) void load(notebooks.notebooks[0].path);
|
||||
// Open the notebook from the URL, else the first one.
|
||||
const wanted = initialRoute.current.notebook;
|
||||
const first = notebooks.notebooks.find((n) => n.path === wanted) ?? notebooks.notebooks[0];
|
||||
if (first) void load(first.path);
|
||||
})
|
||||
.catch((e) => setError(String(e)));
|
||||
const close = api.events((event: ServerEvent) => {
|
||||
if ((event.type === "file.changed" || event.type === "file.deleted") && event.path === "hosts.yaml") {
|
||||
void api.hosts().then(result => setHosts(result.hosts)).catch(e => setError(String(e)));
|
||||
window.dispatchEvent(new Event("shellbook:hosts-changed")); return;
|
||||
}
|
||||
const open = current.current;
|
||||
if (event.type === "file.changed" && event.path === open.doc?.path) {
|
||||
if (event.type === "file.changed" || event.type === "file.deleted") {
|
||||
void api
|
||||
.list()
|
||||
.then((result) => {
|
||||
if (active) setList(result.notebooks);
|
||||
})
|
||||
.catch((e) => setError(String(e)));
|
||||
}
|
||||
// A changed included notebook changes the composed one; a draft keeps its own copy.
|
||||
if (event.type === "file.changed" && event.path !== open.doc?.path && open.doc?.includes.includes(event.path)) {
|
||||
if (!open.dirty) void load(open.doc.path);
|
||||
} else if (event.type === "file.changed" && event.path === open.doc?.path) {
|
||||
if (open.dirty) setConflict(true);
|
||||
else void load(event.path);
|
||||
} else if (
|
||||
@@ -146,23 +199,63 @@ export function App({ api }: { api: Api }) {
|
||||
window.addEventListener("beforeunload", guard);
|
||||
return () => window.removeEventListener("beforeunload", guard);
|
||||
}, [dirty]);
|
||||
// Keep the page and notebook in the URL; back/forward navigate between them.
|
||||
useEffect(() => {
|
||||
if (auth !== "ready") return;
|
||||
// Until the first notebook is open, keep the requested one in the URL.
|
||||
if (page === "Notebooks" && !doc && list === undefined) return;
|
||||
const hash = routeHash({ page, notebook: doc?.path });
|
||||
if (location.hash === hash) return;
|
||||
if (location.hash) history.pushState(null, "", hash);
|
||||
else history.replaceState(null, "", hash);
|
||||
}, [auth, page, doc, list]);
|
||||
useEffect(() => {
|
||||
const follow = () => {
|
||||
const route = parseRoute(location.hash);
|
||||
setPage(route.page);
|
||||
if (route.notebook && route.notebook !== current.current.doc?.path && leave()) void load(route.notebook);
|
||||
};
|
||||
window.addEventListener("hashchange", follow);
|
||||
return () => window.removeEventListener("hashchange", follow);
|
||||
}, [load]);
|
||||
|
||||
// The saved notebook comes composed from the server; a draft shows its includes after saving.
|
||||
const notebook = doc
|
||||
? edit
|
||||
? edit && source !== doc.source
|
||||
? parseNotebook(source)
|
||||
: doc.notebook
|
||||
: undefined;
|
||||
const resolved = notebook
|
||||
? resolveParams(
|
||||
notebook,
|
||||
values,
|
||||
hosts.map((h) => h.name),
|
||||
)
|
||||
: { values: {}, errors: {} };
|
||||
const path = doc?.path ?? "";
|
||||
const runtime = session.runtime[path] ?? {};
|
||||
const hostNames = hosts.map((h) => h.name);
|
||||
const sessionRuntime = session.runtime[path] ?? {};
|
||||
// Builtins ({{shellbook.public_key}}) come from the server, which also sets them on runs.
|
||||
const runtime = { ...sessionRuntime, ...doc?.builtins };
|
||||
const resolved = notebook
|
||||
? resolveParams(notebook, values, hostNames, runtime)
|
||||
: { values: {}, errors: {} };
|
||||
const active = (id: string) => !!notebook && blockActive(notebook, id, resolved.values);
|
||||
const groups: ParamGroup[] = notebook
|
||||
? includes(notebook.blocks)
|
||||
.filter((block) => scopeActive(notebook, block.scope, resolved.values))
|
||||
.map((block) => ({
|
||||
scope: block.scope,
|
||||
title: `${block.title ?? block.path} (${block.scope})`,
|
||||
status: groupInputs(notebook, block, values, hostNames, runtime).status,
|
||||
}))
|
||||
: [];
|
||||
const activeChecks = notebook
|
||||
? steps(notebook.blocks).filter((s) => s.kind === "check" && active(s.attrs.id))
|
||||
: [];
|
||||
const runnable = (step: Step) => {
|
||||
const rendered = renderStep(notebook!, step, resolved.values, runtime, hostNames);
|
||||
return !rendered.missing.length && !Object.keys(rendered.invalid).length;
|
||||
};
|
||||
const runFor = (id: string) =>
|
||||
session.runs[session.latest[stepKey(path, id)] ?? ""];
|
||||
function changeValues(next: ParamValues) {
|
||||
setValues(next);
|
||||
if (doc) rememberValues(doc.path, doc.notebook, next);
|
||||
}
|
||||
async function start(request: StartRunRequest) {
|
||||
const key = stepKey(request.notebookPath, request.stepId);
|
||||
setPending((previous) => new Set(previous).add(key));
|
||||
@@ -181,13 +274,13 @@ export function App({ api }: { api: Api }) {
|
||||
}
|
||||
}
|
||||
function requestRun(step: Step) {
|
||||
if (!notebook || !doc || dirty) return;
|
||||
if (!notebook || !doc || dirty || !active(step.attrs.id)) return;
|
||||
const rendered = renderStep(
|
||||
notebook,
|
||||
step,
|
||||
resolved.values,
|
||||
runtime,
|
||||
hosts.map((h) => h.name),
|
||||
hostNames,
|
||||
);
|
||||
if (
|
||||
rendered.missing.length ||
|
||||
@@ -199,7 +292,7 @@ export function App({ api }: { api: Api }) {
|
||||
notebookPath: path,
|
||||
stepId: step.attrs.id,
|
||||
params: { ...resolved.values },
|
||||
runtime: { ...runtime },
|
||||
runtime: { ...sessionRuntime },
|
||||
artifactSources: { ...session.artifactSources[path] },
|
||||
};
|
||||
const host = hosts.find((h) => h.name === rendered.host);
|
||||
@@ -210,21 +303,91 @@ export function App({ api }: { api: Api }) {
|
||||
setConfirm(request);
|
||||
else void start(request);
|
||||
}
|
||||
const changeValue = (name: string, value: string) => changeValues({ ...values, [name]: value });
|
||||
function blocks(items: Block[]): React.ReactNode {
|
||||
if (!notebook) return null;
|
||||
const prose = (text: string) => renderText(text, setValuesOnly({ ...runtime, ...resolved.values }), notebook);
|
||||
return items.map((block, i) => {
|
||||
if (block.type === "markdown")
|
||||
return (
|
||||
<div className="prose" key={i}>
|
||||
<ReactMarkdown>
|
||||
{renderText(
|
||||
block.text,
|
||||
{ ...runtime, ...resolved.values },
|
||||
notebook,
|
||||
)}
|
||||
</ReactMarkdown>
|
||||
<ReactMarkdown>{prose(block.text)}</ReactMarkdown>
|
||||
</div>
|
||||
);
|
||||
if (block.type === "param") {
|
||||
const def = notebook.params.find((param) => param.name === block.name);
|
||||
// The parser reports unknown names; the panel still lists every parameter.
|
||||
return def ? (
|
||||
<div className="inline-param" key={i}>
|
||||
<ParamField
|
||||
param={def}
|
||||
value={resolved.values[def.name]}
|
||||
error={resolved.errors[def.name]}
|
||||
hosts={hosts}
|
||||
idPrefix={`inline-${i}-${block.range.startLine}`}
|
||||
onChange={changeValue}
|
||||
/>
|
||||
</div>
|
||||
) : null;
|
||||
}
|
||||
if (block.type === "group")
|
||||
return (
|
||||
<GroupSection
|
||||
key={`${path}:${block.range.startLine}`}
|
||||
title={prose(block.title)}
|
||||
inputs={groupInputs(notebook, block, values, hostNames, runtime)}
|
||||
params={notebook.params}
|
||||
storageKey={`${path}:${block.title}`}
|
||||
defaultOpen={!block.collapsed}
|
||||
>
|
||||
{blocks(block.blocks)}
|
||||
</GroupSection>
|
||||
);
|
||||
if (block.type === "when")
|
||||
return block.values.includes(resolved.values[block.param] ?? "") ? (
|
||||
<div className="when" key={i}>
|
||||
{blocks(block.blocks)}
|
||||
</div>
|
||||
) : null;
|
||||
if (block.type === "use")
|
||||
return (
|
||||
<GroupSection
|
||||
key={`${path}:use:${block.scope}`}
|
||||
className="included"
|
||||
title={block.title ?? block.path}
|
||||
subtitle={`${block.path} · as ${block.scope}`}
|
||||
inputs={groupInputs(notebook, block, values, hostNames, runtime)}
|
||||
params={notebook.params}
|
||||
storageKey={`${path}:use:${block.scope}`}
|
||||
>
|
||||
{block.blocks.length ? (
|
||||
blocks(block.blocks)
|
||||
) : (
|
||||
<p className="muted">Save the notebook to load {block.path}.</p>
|
||||
)}
|
||||
</GroupSection>
|
||||
);
|
||||
if (block.type === "host") {
|
||||
const rendered = renderHost(notebook, block, resolved.values, runtime, hostNames);
|
||||
const capture = (name: string) => {
|
||||
if (block.capture) dispatch({ type: "runtime.set", notebookPath: path, name: block.capture, value: name });
|
||||
};
|
||||
return (
|
||||
<HostBlockCard
|
||||
key={block.id}
|
||||
rendered={rendered}
|
||||
existing={hosts.find((h) => h.name === rendered.name)}
|
||||
captured={block.capture ? runtime[block.capture] : undefined}
|
||||
onUse={capture}
|
||||
onAdd={async (host) => {
|
||||
await api.addHost(host);
|
||||
setHosts((await api.hosts()).hosts);
|
||||
window.dispatchEvent(new Event("shellbook:hosts-changed"));
|
||||
capture(host.name);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (block.type === "after") {
|
||||
const run = runFor(block.stepId);
|
||||
return run &&
|
||||
@@ -239,7 +402,7 @@ export function App({ api }: { api: Api }) {
|
||||
block.step,
|
||||
resolved.values,
|
||||
runtime,
|
||||
hosts.map((h) => h.name),
|
||||
hostNames,
|
||||
);
|
||||
return (
|
||||
<StepCard
|
||||
@@ -262,30 +425,66 @@ export function App({ api }: { api: Api }) {
|
||||
);
|
||||
});
|
||||
}
|
||||
const canSave =
|
||||
dirty && !conflict && !notebook?.diagnostics.some((d) => d.severity === "error");
|
||||
async function save() {
|
||||
if (!doc) return;
|
||||
try {
|
||||
const saved = await api.save(path, source, doc.version);
|
||||
const parsed = parseNotebook(source);
|
||||
setDoc({
|
||||
...doc,
|
||||
source,
|
||||
notebook: parseNotebook(source),
|
||||
notebook: parsed,
|
||||
version: saved.version,
|
||||
});
|
||||
setConflict(false);
|
||||
// Includes are composed on the server: reload to show them.
|
||||
if (notebookIncludes(parsed).length || doc.includes.length) await load(path);
|
||||
} catch (e) {
|
||||
if (e instanceof HttpError && e.status === 409) setConflict(true);
|
||||
else setError(String(e));
|
||||
}
|
||||
}
|
||||
// Ctrl/Cmd+S saves the open draft.
|
||||
const saveRef = useRef(save);
|
||||
saveRef.current = save;
|
||||
const canSaveRef = useRef(canSave);
|
||||
canSaveRef.current = canSave && edit;
|
||||
useEffect(() => {
|
||||
const key = (e: KeyboardEvent) => {
|
||||
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "s" && canSaveRef.current) {
|
||||
e.preventDefault();
|
||||
void saveRef.current();
|
||||
}
|
||||
};
|
||||
window.addEventListener("keydown", key);
|
||||
return () => window.removeEventListener("keydown", key);
|
||||
}, []);
|
||||
const keyPrompt = Object.values(session.runs).find(
|
||||
(run) => run.status === "hostKey" && requests.current.has(run.runId),
|
||||
);
|
||||
const checksBusy = notebook
|
||||
? steps(notebook.blocks).some(
|
||||
(s) =>
|
||||
runFor(s.attrs.id)?.status === "running" ||
|
||||
pending.has(stepKey(path, s.attrs.id)),
|
||||
)
|
||||
: false;
|
||||
const openTerminal = () => {
|
||||
setTerminalOpened(true);
|
||||
setChat(false);
|
||||
setTerminal(true);
|
||||
};
|
||||
if (auth === "setup") return <SetupScreen onComplete={() => setAuth("ready")} />;
|
||||
if (auth === "login")
|
||||
return (
|
||||
<main className="login">
|
||||
<h1>ShellBook</h1>
|
||||
<p>Sign in to your workspace</p>
|
||||
<h1>
|
||||
<Logo size={48} />
|
||||
ShellBook<span>RUNBOOKS</span>
|
||||
</h1>
|
||||
<p className="muted">Sign in to your workspace</p>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
@@ -315,177 +514,243 @@ export function App({ api }: { api: Api }) {
|
||||
</label>
|
||||
<button className="primary">Sign in</button>
|
||||
</form>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{error && <p role="alert" className="error">{error}</p>}
|
||||
</main>
|
||||
);
|
||||
return (
|
||||
<div className={`app ${terminal ? "with-terminal" : ""}`}>
|
||||
<aside className="sidebar">
|
||||
<h1>
|
||||
ShellBook<span>RUNBOOKS</span>
|
||||
</h1>
|
||||
<nav aria-label="Notebooks">
|
||||
{list.map((item) => (
|
||||
<button
|
||||
className={path === item.path ? "selected" : ""}
|
||||
key={item.path}
|
||||
onClick={() => {
|
||||
if (!dirty || window.confirm("Discard unsaved edits?"))
|
||||
void load(item.path);
|
||||
<div className="app">
|
||||
<header className="topbar">
|
||||
<span className="brand">
|
||||
<Logo />
|
||||
ShellBook
|
||||
{import.meta.env.VITE_MOCK === "1" && <span className="chip">demo</span>}
|
||||
</span>
|
||||
<HeaderNavigation page={page} onChange={setPage} />
|
||||
<span className="spacer" />
|
||||
<span
|
||||
className={`connection ${connected ? "ok" : "bad"}`}
|
||||
title={connected ? "Live updates connected" : "Live updates disconnected; reload to reconnect"}
|
||||
>
|
||||
{connected ? "Live" : "Offline · reload"}
|
||||
</span>
|
||||
<button
|
||||
aria-expanded={chat}
|
||||
className={chat ? "toggled" : ""}
|
||||
onClick={() => {
|
||||
setChat(!chat);
|
||||
setTerminal(false);
|
||||
}}
|
||||
>
|
||||
Chat
|
||||
</button>
|
||||
<button
|
||||
aria-expanded={terminal}
|
||||
className={terminal ? "toggled" : ""}
|
||||
onClick={() => {
|
||||
if (terminal) setTerminal(false);
|
||||
else openTerminal();
|
||||
}}
|
||||
>
|
||||
Terminal
|
||||
</button>
|
||||
</header>
|
||||
<div className="workspace">
|
||||
{page === "Notebooks" && (
|
||||
<aside className="sidebar" aria-label="Notebook list">
|
||||
<NotebookList
|
||||
api={api}
|
||||
list={list ?? []}
|
||||
path={path}
|
||||
version={doc?.version}
|
||||
canLeave={leave}
|
||||
onSelect={(next) => {
|
||||
if (next !== path && leave()) void load(next);
|
||||
}}
|
||||
>
|
||||
{item.title}
|
||||
<small>{item.path}</small>
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
<small className="connection">
|
||||
{import.meta.env.VITE_MOCK === "1" ? "DEMO · " : ""}
|
||||
{connected
|
||||
? "● Events connected"
|
||||
: "○ Events disconnected · reload to reconnect"}
|
||||
</small>
|
||||
</aside>
|
||||
<main>
|
||||
<div className="toolbar">
|
||||
<span>{doc?.notebook.title ?? "Loading workspace…"}</span>
|
||||
<button onClick={() => setEdit(!edit)}>
|
||||
{edit ? "Close editor" : "Edit Markdown"}
|
||||
</button>
|
||||
<button
|
||||
aria-expanded={terminal}
|
||||
onClick={() => {
|
||||
setTerminalOpened(true);
|
||||
setTerminal(!terminal);
|
||||
}}
|
||||
>
|
||||
Terminal {terminal ? "→" : "←"}
|
||||
</button>
|
||||
</div>
|
||||
{error && (
|
||||
<p className="banner error" role="alert">
|
||||
{error}
|
||||
<button onClick={() => location.reload()}>Retry</button>
|
||||
</p>
|
||||
)}
|
||||
{conflict && (
|
||||
<div className="banner error" role="alert">
|
||||
The file changed on disk. Your draft has been retained.
|
||||
<button
|
||||
onClick={() => {
|
||||
if (!dirty || window.confirm("Discard your draft and reload?"))
|
||||
void load(path);
|
||||
onChanged={async (next) => {
|
||||
const result = await api.list();
|
||||
setList(result.notebooks);
|
||||
if (next) await load(next);
|
||||
else {
|
||||
++loadSequence.current;
|
||||
setDoc(undefined);
|
||||
setSource("");
|
||||
setConflict(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Reload from disk
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{notebook && (
|
||||
<>
|
||||
<ParamsForm
|
||||
notebook={notebook}
|
||||
values={resolved.values}
|
||||
errors={resolved.errors}
|
||||
hosts={hosts}
|
||||
onChange={(name, value) =>
|
||||
setValues((previous) => ({ ...previous, [name]: value }))
|
||||
}
|
||||
/>
|
||||
<div className="notebook">
|
||||
{edit && (
|
||||
<section>
|
||||
<div className="actions">
|
||||
<strong>Markdown editor {dirty ? "· unsaved" : ""}</strong>
|
||||
<button
|
||||
className="primary"
|
||||
disabled={
|
||||
!dirty ||
|
||||
conflict ||
|
||||
notebook.diagnostics.some((d) => d.severity === "error")
|
||||
}
|
||||
onClick={() => void save()}
|
||||
>
|
||||
Save
|
||||
</button>
|
||||
</div>
|
||||
<Suspense fallback={<p>Loading editor…</p>}>
|
||||
<Editor
|
||||
key={`${path}:${doc?.version}`}
|
||||
source={source}
|
||||
onChange={setSource}
|
||||
/>
|
||||
</Suspense>
|
||||
<p className="muted">
|
||||
Live preview below. Save changes before running steps.
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
{notebook.diagnostics.map((d, i) => (
|
||||
<p role="alert" className="error" key={i}>
|
||||
{d.line && `Line ${d.line}: `}
|
||||
{d.message}
|
||||
</p>
|
||||
))}
|
||||
<div className="actions">
|
||||
</aside>
|
||||
)}
|
||||
<main className="main">
|
||||
{error && (
|
||||
<p className="banner error" role="alert">
|
||||
{error}
|
||||
<button onClick={() => location.reload()}>Retry</button>
|
||||
</p>
|
||||
)}
|
||||
{page === "Settings" && (
|
||||
<SettingsPage openTerminal={openTerminal} onSignOut={() => setAuth("login")} />
|
||||
)}
|
||||
{page === "Hosts" && <HostsPage onChange={() => { void api.hosts().then(result => setHosts(result.hosts)).catch(e => setError(String(e))); }} />}
|
||||
<div className="notebook-page" hidden={page !== "Notebooks"}>
|
||||
{conflict && (
|
||||
<div className="banner error" role="alert">
|
||||
The file changed on disk. Your draft has been retained.
|
||||
<button
|
||||
disabled={
|
||||
!connected ||
|
||||
dirty ||
|
||||
Object.keys(resolved.errors).length > 0 ||
|
||||
steps(notebook.blocks).some(
|
||||
(s) =>
|
||||
runFor(s.attrs.id)?.status === "running" ||
|
||||
pending.has(stepKey(path, s.attrs.id)),
|
||||
)
|
||||
}
|
||||
onClick={() => {
|
||||
const checks = steps(notebook.blocks).filter(
|
||||
(s) => s.kind === "check",
|
||||
);
|
||||
setCheckIds(checks.map((s) => s.attrs.id));
|
||||
checks.forEach(requestRun);
|
||||
if (!dirty || window.confirm("Discard your draft and reload?"))
|
||||
void load(path);
|
||||
}}
|
||||
>
|
||||
Run all checks
|
||||
Reload from disk
|
||||
</button>
|
||||
{checkIds.length > 0 && (
|
||||
<span role="status">
|
||||
✅{" "}
|
||||
{
|
||||
checkIds.filter((id) => runFor(id)?.status === "success")
|
||||
.length
|
||||
}{" "}
|
||||
/ {checkIds.length} · ❌{" "}
|
||||
{
|
||||
checkIds.filter((id) => runFor(id)?.status === "failure")
|
||||
.length
|
||||
}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{blocks(notebook.blocks)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{!notebook && (
|
||||
<div className="empty">
|
||||
{list === undefined
|
||||
? "Loading workspace…"
|
||||
: list.length
|
||||
? "Select a notebook."
|
||||
: "No notebooks yet. Create one with + in the sidebar, or ask Claude in Chat."}
|
||||
</div>
|
||||
)}
|
||||
{notebook && (
|
||||
<div className={`notebook-layout${paramsOpen ? "" : " params-collapsed"}`}>
|
||||
<ParamsForm
|
||||
notebook={notebook}
|
||||
values={resolved.values}
|
||||
errors={resolved.errors}
|
||||
hosts={hosts}
|
||||
groups={groups}
|
||||
open={paramsOpen}
|
||||
onToggle={(next) => {
|
||||
writeFlag("params-open", next);
|
||||
setParamsOpen(next);
|
||||
}}
|
||||
onChange={changeValue}
|
||||
onReset={() => changeValues({})}
|
||||
/>
|
||||
<article className="notebook">
|
||||
<header className="notebook-header">
|
||||
<span className="crumbs" title={path}>
|
||||
{path.split("/").map((part, i, parts) => (
|
||||
<span key={i} className={i === parts.length - 1 ? "file" : ""}>
|
||||
{part}
|
||||
</span>
|
||||
))}
|
||||
{dirty && <span className="chip warn">unsaved</span>}
|
||||
</span>
|
||||
<span className="spacer" />
|
||||
{checkIds.length > 0 && (
|
||||
<span role="status" className="check-summary">
|
||||
✅{" "}
|
||||
{checkIds.filter((id) => runFor(id)?.status === "success").length}{" "}
|
||||
/ {checkIds.length} · ❌{" "}
|
||||
{checkIds.filter((id) => runFor(id)?.status === "failure").length}
|
||||
</span>
|
||||
)}
|
||||
<button
|
||||
title={
|
||||
activeChecks.length
|
||||
? "Runs every check step; checks never change hosts"
|
||||
: "This notebook has no check steps"
|
||||
}
|
||||
disabled={
|
||||
!connected ||
|
||||
dirty ||
|
||||
activeChecks.length === 0 ||
|
||||
!activeChecks.every(runnable) ||
|
||||
checksBusy
|
||||
}
|
||||
onClick={() => {
|
||||
setCheckIds(activeChecks.map((s) => s.attrs.id));
|
||||
activeChecks.forEach(requestRun);
|
||||
}}
|
||||
>
|
||||
Run all checks
|
||||
</button>
|
||||
<button
|
||||
className={edit ? "toggled" : ""}
|
||||
onClick={() => setEdit(!edit)}
|
||||
>
|
||||
{edit ? "Close editor" : "Edit Markdown"}
|
||||
</button>
|
||||
</header>
|
||||
{edit && (
|
||||
<section className="editor-panel">
|
||||
<div className="actions">
|
||||
<strong>Markdown</strong>
|
||||
<span className="muted">
|
||||
{dirty ? "Unsaved changes · Ctrl+S saves" : "Saved"}
|
||||
</span>
|
||||
<span className="spacer" />
|
||||
{dirty && (
|
||||
<button
|
||||
onClick={() => {
|
||||
if (window.confirm("Discard your unsaved changes?") && doc) setSource(doc.source);
|
||||
}}
|
||||
>
|
||||
Discard
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
className="primary"
|
||||
disabled={!canSave}
|
||||
onClick={() => void save()}
|
||||
>
|
||||
Save
|
||||
</button>
|
||||
</div>
|
||||
<Suspense fallback={<p>Loading editor…</p>}>
|
||||
<Editor
|
||||
key={`${path}:${doc?.version}`}
|
||||
source={source}
|
||||
onChange={setSource}
|
||||
/>
|
||||
</Suspense>
|
||||
<p className="muted">
|
||||
Live preview below. Save changes before running steps.
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
{notebook.diagnostics.map((d, i) => (
|
||||
<p role="alert" className="banner error" key={i}>
|
||||
{d.line && `Line ${d.line}: `}
|
||||
{d.message}
|
||||
</p>
|
||||
))}
|
||||
{blocks(notebook.blocks)}
|
||||
</article>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
{chat && (
|
||||
<ChatPanel
|
||||
notebookPath={doc?.path}
|
||||
openNotebook={(next) => {
|
||||
if (leave()) {
|
||||
setPage("Notebooks");
|
||||
void load(next);
|
||||
}
|
||||
}}
|
||||
openTerminal={openTerminal}
|
||||
onClose={() => setChat(false)}
|
||||
/>
|
||||
)}
|
||||
</main>
|
||||
{terminalOpened && (
|
||||
<Suspense fallback={<p>Loading terminal...</p>}>
|
||||
<TerminalSlot collapsed={!terminal} />
|
||||
</Suspense>
|
||||
)}
|
||||
{terminalOpened && (
|
||||
<Suspense fallback={<p>Loading terminal…</p>}>
|
||||
<TerminalSlot collapsed={!terminal} onClose={() => setTerminal(false)} />
|
||||
</Suspense>
|
||||
)}
|
||||
</div>
|
||||
{confirm && (
|
||||
<div className="modal-backdrop">
|
||||
<section
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="confirm-title"
|
||||
>
|
||||
<h2 id="confirm-title">Confirm execution</h2>
|
||||
<p>
|
||||
Run “{confirm.stepId}” with the displayed parameters? This step
|
||||
can change the target host.
|
||||
</p>
|
||||
<Dialog title="Confirm execution" onClose={() => setConfirm(undefined)}>
|
||||
<p>
|
||||
Run “{confirm.stepId}” with the displayed parameters? This step
|
||||
can change the target host.
|
||||
</p>
|
||||
<div className="dialog-actions">
|
||||
<button onClick={() => setConfirm(undefined)}>Cancel</button>
|
||||
<button
|
||||
className="primary"
|
||||
@@ -496,65 +761,18 @@ export function App({ api }: { api: Api }) {
|
||||
>
|
||||
Confirm and run
|
||||
</button>
|
||||
</section>
|
||||
</div>
|
||||
)}
|
||||
{keyPrompt?.hostKey && (
|
||||
<div className="modal-backdrop">
|
||||
<section
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="hostkey-title"
|
||||
>
|
||||
<h2 id="hostkey-title">
|
||||
{keyPrompt.hostKey.changed
|
||||
? "⚠ HOST KEY CHANGED"
|
||||
: "Unknown SSH host key"}
|
||||
</h2>
|
||||
{keyPrompt.hostKey.changed && (
|
||||
<p className="error">
|
||||
STOP: a different key is already trusted. This may indicate a
|
||||
man-in-the-middle attack. Verify the fingerprint independently
|
||||
before accepting.
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
Verify the key for <strong>{keyPrompt.hostKey.host}</strong>{" "}
|
||||
through a trusted channel.
|
||||
</p>
|
||||
<code>{keyPrompt.hostKey.fingerprint}</code>
|
||||
<div className="actions">
|
||||
<button
|
||||
onClick={() =>
|
||||
dispatch({
|
||||
type: "run.error",
|
||||
runId: keyPrompt.runId,
|
||||
message: "Host key rejected",
|
||||
})
|
||||
}
|
||||
>
|
||||
Reject
|
||||
</button>
|
||||
<button
|
||||
onClick={() => {
|
||||
const request = requests.current.get(keyPrompt.runId)!;
|
||||
dispatch({
|
||||
type: "run.error",
|
||||
runId: keyPrompt.runId,
|
||||
message: "Retrying with accepted host key",
|
||||
});
|
||||
void start({
|
||||
...request,
|
||||
acceptHostKey: keyPrompt.hostKey!.fingerprint,
|
||||
});
|
||||
}}
|
||||
>
|
||||
Trust this fingerprint and retry
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
)}
|
||||
{keyPrompt?.hostKey && <HostKeyConfirmation
|
||||
{...keyPrompt.hostKey}
|
||||
onReject={() => dispatch({ type: "run.error", runId: keyPrompt.runId, message: "Host key rejected" })}
|
||||
onTrust={() => {
|
||||
const request = requests.current.get(keyPrompt.runId)!;
|
||||
dispatch({ type: "run.error", runId: keyPrompt.runId, message: "Retrying with accepted host key" });
|
||||
void start({ ...request, acceptHostKey: keyPrompt.hostKey!.fingerprint });
|
||||
}}
|
||||
/>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
import { useState } from "react";
|
||||
import { parseNotebook, type ParamDef } from "@shellbook/core";
|
||||
import {
|
||||
addParameter,
|
||||
afterSnippet,
|
||||
groupSnippet,
|
||||
hostSnippet,
|
||||
paramFieldSnippet,
|
||||
notebookSteps,
|
||||
stepSnippet,
|
||||
useSnippet,
|
||||
whenSnippet,
|
||||
type InsertKind,
|
||||
} from "./authoring";
|
||||
export function AuthoringToolbar({
|
||||
source,
|
||||
insert,
|
||||
replace,
|
||||
}: {
|
||||
source: string;
|
||||
insert(text: string): void;
|
||||
replace(text: string): void;
|
||||
}) {
|
||||
const notebook = parseNotebook(source);
|
||||
const hosts = notebook.params.filter((p) => p.type === "host");
|
||||
const [target, setTarget] = useState("local");
|
||||
const [param, setParam] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [type, setType] = useState<ParamDef["type"]>("string");
|
||||
const [after, setAfter] = useState("");
|
||||
const [when, setWhen] = useState("");
|
||||
const [include, setInclude] = useState(false);
|
||||
const [field, setField] = useState("");
|
||||
const steps = notebookSteps(notebook.blocks);
|
||||
const choices = notebook.params.flatMap((p) =>
|
||||
p.type === "choice" ? (p.options ?? []).map((o) => ({ param: p.name, option: o })) : [],
|
||||
);
|
||||
const selected = choices.find((c) => JSON.stringify([c.param, c.option]) === when);
|
||||
return (
|
||||
<div className="authoring">
|
||||
<label>
|
||||
Insert target
|
||||
<select value={target} onChange={(e) => setTarget(e.target.value)}>
|
||||
<option value="local">ShellBook server (local)</option>
|
||||
{hosts.map((p) => (
|
||||
<option key={p.name} value={p.name}>
|
||||
Parameter: {p.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{(
|
||||
[
|
||||
"Check step",
|
||||
"Run step",
|
||||
"Artifacts",
|
||||
"Upload",
|
||||
"Capture",
|
||||
] as InsertKind[]
|
||||
).map((kind) => (
|
||||
<button
|
||||
key={kind}
|
||||
type="button"
|
||||
onClick={() =>
|
||||
insert(stepSnippet(source, kind, target === "local", target))
|
||||
}
|
||||
>
|
||||
{kind}
|
||||
</button>
|
||||
))}
|
||||
<button type="button" onClick={() => setParam(!param)}>
|
||||
Parameter
|
||||
</button>
|
||||
<label>
|
||||
After step
|
||||
<select value={after} onChange={(e) => setAfter(e.target.value)}>
|
||||
<option value="">Choose a step</option>
|
||||
{steps.map((s) => (
|
||||
<option key={s.attrs.id} value={s.attrs.id}>
|
||||
{s.attrs.title ?? s.attrs.id}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
disabled={!steps.some((s) => s.attrs.id === after)}
|
||||
onClick={() => insert(afterSnippet(after))}
|
||||
>
|
||||
Insert after note
|
||||
</button>
|
||||
<label>
|
||||
Show when
|
||||
<select value={when} onChange={(e) => setWhen(e.target.value)}>
|
||||
<option value="">Choose an option</option>
|
||||
{choices.map((c) => (
|
||||
<option key={JSON.stringify([c.param, c.option])} value={JSON.stringify([c.param, c.option])}>
|
||||
{c.param} = {c.option}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
disabled={!selected}
|
||||
onClick={() => selected && insert(whenSnippet(selected.param, selected.option))}
|
||||
>
|
||||
Insert when section
|
||||
</button>
|
||||
<button type="button" onClick={() => insert(groupSnippet())}>
|
||||
Group
|
||||
</button>
|
||||
<label>
|
||||
Field in text
|
||||
<select value={field} onChange={(e) => setField(e.target.value)}>
|
||||
<option value="">Choose a parameter</option>
|
||||
{notebook.params.map((p) => (
|
||||
<option key={p.name} value={p.name}>
|
||||
{p.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
disabled={!notebook.params.some((p) => p.name === field)}
|
||||
onClick={() => insert(paramFieldSnippet(field))}
|
||||
>
|
||||
Insert field
|
||||
</button>
|
||||
<button type="button" onClick={() => setInclude(!include)}>
|
||||
Use notebook
|
||||
</button>
|
||||
<button type="button" onClick={() => insert(hostSnippet())}>
|
||||
Add host
|
||||
</button>
|
||||
{include && (
|
||||
<form
|
||||
aria-label="Use notebook"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
const data = new FormData(e.currentTarget);
|
||||
try {
|
||||
insert(useSnippet(String(data.get("path")), String(data.get("alias"))));
|
||||
setInclude(false);
|
||||
setError("");
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}}
|
||||
>
|
||||
<label>
|
||||
Notebook path
|
||||
<input name="path" required placeholder="infra/lxc-container.md" />
|
||||
</label>
|
||||
<label>
|
||||
Alias
|
||||
<input name="alias" required pattern="[A-Za-z_][A-Za-z0-9_]*" placeholder="ct" />
|
||||
</label>
|
||||
<button>Insert include</button>
|
||||
</form>
|
||||
)}
|
||||
{param && (
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
const data = new FormData(e.currentTarget);
|
||||
const def: ParamDef = {
|
||||
name: String(data.get("name")),
|
||||
type,
|
||||
required: data.has("required"),
|
||||
};
|
||||
if (data.get("label")) def.label = String(data.get("label"));
|
||||
if (type !== "secret" && data.get("default"))
|
||||
def.default = String(data.get("default"));
|
||||
if (type === "choice")
|
||||
def.options = String(data.get("options"))
|
||||
.split("\n")
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
try {
|
||||
replace(addParameter(source, def));
|
||||
setParam(false);
|
||||
setError("");
|
||||
} catch (err) {
|
||||
setError(String(err));
|
||||
}
|
||||
}}
|
||||
>
|
||||
<label>
|
||||
Parameter name
|
||||
<input name="name" required pattern="[A-Za-z_][A-Za-z0-9_]*" />
|
||||
</label>
|
||||
<label>
|
||||
Type
|
||||
<select
|
||||
value={type}
|
||||
onChange={(e) => setType(e.target.value as ParamDef["type"])}
|
||||
>
|
||||
{["host", "name", "path", "string", "choice", "secret"].map(
|
||||
(t) => (
|
||||
<option key={t}>{t}</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
<input type="checkbox" name="required" />
|
||||
Required
|
||||
</label>
|
||||
<label>
|
||||
Label
|
||||
<input name="label" />
|
||||
</label>
|
||||
{type !== "secret" && (
|
||||
<label>
|
||||
Default
|
||||
<input name="default" />
|
||||
</label>
|
||||
)}
|
||||
{type === "choice" && (
|
||||
<label>
|
||||
Options (one per line)
|
||||
<textarea name="options" required />
|
||||
</label>
|
||||
)}
|
||||
<button>Add parameter</button>
|
||||
</form>
|
||||
)}
|
||||
{error && <p role="alert">{error}</p>}
|
||||
<details>
|
||||
<summary>Format help</summary>
|
||||
<p>
|
||||
Parameters live in YAML frontmatter: type, required, default, label,
|
||||
options. Use {"{{name}}"} in prose and scripts. Secrets use
|
||||
environment variables ($NAME), with no default.
|
||||
</p>
|
||||
<p>
|
||||
Steps use sh fences with {'{check host="{{host}}"}'} or{" "}
|
||||
{"{run on=local confirm}"}. Checks must be read-only. Optional
|
||||
attributes: id, title, sudo, confirm, timeout (seconds), capture. Run
|
||||
steps support artifacts="file.txt" and
|
||||
upload="file.txt:/tmp/file.txt". After notes appear when their
|
||||
selected step succeeds.
|
||||
</p>
|
||||
<p>
|
||||
Chaining: {'::use{notebook="infra/lxc-container.md" as=ct with="hostname={{name}}"}'}{" "}
|
||||
includes another notebook; its parameters appear as ct.name and its
|
||||
captures as {"{{ct.address}}"}. {":::when{target=lxc}"} … {":::"} shows a
|
||||
section only for that choice. {'::host{name="{{hostname}}" address="{{address}}" capture=host}'}{" "}
|
||||
adds a created machine to Hosts. {"{{shellbook.public_key}}"} is
|
||||
ShellBook's SSH public key.
|
||||
</p>
|
||||
<p>
|
||||
Guided text: {"::param{name=host}"} on its own line shows that
|
||||
parameter's input there (same value as the panel).{" "}
|
||||
{':::group{title="Network" collapsed}'} … {":::"} is a collapsible
|
||||
section for anything; its outline is orange while needed values are
|
||||
missing, green when all are filled, grey when only optional ones remain.
|
||||
{" collapsed"} starts it closed. Groups never block steps.
|
||||
</p>
|
||||
<p>
|
||||
Artifact and upload snippets are examples: choose files and commands
|
||||
appropriate to your runbook before running.
|
||||
</p>
|
||||
</details>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import ReactMarkdown from "react-markdown";
|
||||
import type { ChatClientMessage, ChatConversation, ChatEvent } from "@shellbook/core";
|
||||
import "./chat.css";
|
||||
|
||||
export interface ChatSocket {
|
||||
onopen: ((event: Event) => void) | null; onclose: ((event: CloseEvent) => void) | null; onerror: ((event: Event) => void) | null;
|
||||
onmessage: ((event: MessageEvent) => void) | null;
|
||||
send(text: string): void; close(): void;
|
||||
}
|
||||
const connectChat = (): ChatSocket => new WebSocket(`${location.protocol === "https:" ? "wss:" : "ws:"}//${location.host}/api/chat`);
|
||||
type Message = { role: "user" | "assistant" | "tool"; text: string; path?: string };
|
||||
|
||||
/** notebookPath and openNotebook use app paths (relative to notebooks/); the chat wire uses workspace paths. */
|
||||
export function ChatPanel({ notebookPath, openNotebook, openTerminal, onClose, connect = connectChat }: {
|
||||
notebookPath?: string; openNotebook(path: string): void; openTerminal(): void; onClose?(): void; connect?: () => ChatSocket;
|
||||
}) {
|
||||
const [history, setHistory] = useState<ChatConversation[]>([]);
|
||||
const [selected, setSelected] = useState("");
|
||||
const [messages, setMessages] = useState<Message[]>([]);
|
||||
const cache = useRef(new Map<string, Message[]>());
|
||||
const selectedRef = useRef("");
|
||||
const [text, setText] = useState("");
|
||||
const [allowShell, setAllowShell] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [ready, setReady] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [login, setLogin] = useState(false);
|
||||
const [summary, setSummary] = useState("");
|
||||
const [attempt, setAttempt] = useState(0);
|
||||
const socket = useRef<ChatSocket>();
|
||||
const end = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => { end.current?.scrollIntoView?.({ block: "nearest" }); }, [messages]);
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
let connection: ChatSocket;
|
||||
try { connection = connect(); socket.current = connection; }
|
||||
catch { setError("Cannot connect to chat."); return; }
|
||||
connection.onopen = () => { if (alive) { setReady(true); setError(""); } };
|
||||
connection.onclose = connection.onerror = () => {
|
||||
if (alive) { setReady(false); setBusy(false); setError("Chat disconnected. The current turn was stopped. Reconnect to continue."); }
|
||||
};
|
||||
connection.onmessage = ({ data }) => {
|
||||
if (!alive) return;
|
||||
let event: ChatEvent; try { event = JSON.parse(data); } catch { return; }
|
||||
if (event.type === "history") setHistory(event.conversations);
|
||||
if (event.type === "conversation") {
|
||||
selectedRef.current = event.conversation.id; setSelected(event.conversation.id);
|
||||
setHistory(previous => [...previous.filter(c => c.id !== event.conversation.id), event.conversation]);
|
||||
}
|
||||
if (event.type === "delta") setMessages(previous => {
|
||||
const last = previous.at(-1);
|
||||
return last?.role === "assistant" ? [...previous.slice(0, -1), { ...last, text: last.text + event.text }] : [...previous, { role: "assistant", text: event.text }];
|
||||
});
|
||||
if (event.type === "tool") setMessages(previous => [...previous, {
|
||||
role: "tool", text: `${["Edit", "Write", "MultiEdit"].includes(event.name) ? "Editing" : event.name} ${event.path ?? ""}`.trim(), path: event.path,
|
||||
}]);
|
||||
if (event.type === "error") { setBusy(false); setError(event.message); setLogin(event.code === "login" || event.code === "missing"); }
|
||||
if (event.type === "finished") {
|
||||
setBusy(false); setSummary(event.cancelled ? "Stopped" : `Finished${event.durationMs === undefined ? "" : ` in ${(event.durationMs / 1000).toFixed(1)}s`}${event.costUsd === undefined ? "" : ` · estimated $${event.costUsd.toFixed(4)}`}`);
|
||||
}
|
||||
};
|
||||
return () => { alive = false; connection.close(); };
|
||||
}, [connect, attempt]);
|
||||
useEffect(() => { if (selected) cache.current.set(selected, messages); }, [messages, selected]);
|
||||
function choose(id: string) {
|
||||
selectedRef.current = id; setSelected(id); setMessages(cache.current.get(id) ?? []);
|
||||
setError(""); setLogin(false); setSummary(""); setAllowShell(false);
|
||||
}
|
||||
function send(message: ChatClientMessage) { try { socket.current?.send(JSON.stringify(message)); } catch { setBusy(false); setError("Cannot send chat message. Reconnect to continue."); } }
|
||||
return <aside className="chat-panel side-panel" aria-label="Chat panel">
|
||||
<header className="panel-header">
|
||||
<h2>Chat with Claude</h2>
|
||||
<span className="spacer" />
|
||||
{!ready && <button onClick={() => setAttempt(n => n + 1)}>Reconnect chat</button>}
|
||||
<button disabled={busy} onClick={() => choose("")}>New conversation</button>
|
||||
{onClose && <button className="icon" aria-label="Close chat" onClick={onClose}>×</button>}
|
||||
</header>
|
||||
{notebookPath && <p className="muted">About: <code>{notebookPath}</code></p>}
|
||||
<label>Conversation history<select aria-label="Conversation history" disabled={busy} value={selected} onChange={e => choose(e.target.value)}>
|
||||
<option value="">New conversation</option>{[...history].reverse().map(c => <option key={c.id} value={c.id}>{c.title}</option>)}
|
||||
</select></label>
|
||||
<div className="chat-messages" role="log" aria-label="Chat messages" aria-live="polite">
|
||||
{!messages.length && <p>{selected ? "Continue this conversation. Earlier messages are retained by the Claude CLI; this view shows messages from this browser session." : "Ask Claude to create or edit a notebook. Do not send secrets."}</p>}
|
||||
{messages.map((m, i) => <div key={i} className={`chat-message ${m.role}`}>
|
||||
{m.role === "tool" ? <small>{m.text} {m.path && <button onClick={() => openNotebook(m.path!.replace(/^notebooks\//, ""))}>Open notebook</button>}</small> : <><strong>{m.role === "user" ? "You" : "Claude"}</strong><ReactMarkdown>{m.text}</ReactMarkdown></>}
|
||||
</div>)}<div ref={end} />
|
||||
</div>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{login && <button onClick={openTerminal}>Open Terminal — run claude, then /login</button>}
|
||||
<p role="status">{busy ? "Claude is working…" : summary}</p>
|
||||
{!messages.length && <div className="actions">{["Create a notebook that…", "Add a check that…"].map(prompt => <button key={prompt} onClick={() => setText(prompt)}>{prompt}</button>)}</div>}
|
||||
<form onSubmit={e => { e.preventDefault(); if (!ready || busy || !text.trim()) return;
|
||||
setMessages(previous => [...previous, { role: "user", text }]); setBusy(true); setError(""); setLogin(false); setSummary("");
|
||||
send({ type: "send", conversationId: selectedRef.current || undefined, message: text, notebookPath: notebookPath && `notebooks/${notebookPath}`, allowShell }); setText("");
|
||||
}}>
|
||||
<label>Message<textarea value={text} onChange={e => setText(e.target.value)} maxLength={32000} required rows={3} /></label>
|
||||
<label className="chat-shell"><input type="checkbox" checked={allowShell} disabled={busy} onChange={e => setAllowShell(e.target.checked)} />Allow Claude to run shell commands on the ShellBook server</label>
|
||||
<small>Off by default. Enabling this allows commands as the service user, including network access. File tools otherwise stay in the workspace.</small>
|
||||
<div className="actions"><button disabled={!ready || busy || !text.trim()}>Send</button>{busy && <button type="button" onClick={() => send({ type: "cancel" })}>Stop</button>}</div>
|
||||
</form>
|
||||
</aside>;
|
||||
}
|
||||
+28
-2
@@ -1,3 +1,4 @@
|
||||
import { AuthoringToolbar } from "./AuthoringToolbar";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { basicSetup } from "codemirror";
|
||||
@@ -10,6 +11,7 @@ export function Editor({
|
||||
source: string;
|
||||
onChange(source: string): void;
|
||||
}) {
|
||||
const editor = useRef<EditorView>();
|
||||
const root = useRef<HTMLDivElement>(null);
|
||||
const change = useRef(onChange);
|
||||
change.current = onChange;
|
||||
@@ -27,9 +29,33 @@ export function Editor({
|
||||
}),
|
||||
],
|
||||
});
|
||||
return () => view.destroy();
|
||||
editor.current = view;
|
||||
return () => {
|
||||
editor.current = undefined;
|
||||
view.destroy();
|
||||
};
|
||||
// Editor lifetime matches edit mode. Parent remounts after reload.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
return <div className="editor" ref={root} />;
|
||||
return (
|
||||
<>
|
||||
<AuthoringToolbar
|
||||
source={source}
|
||||
insert={(text) => {
|
||||
const view = editor.current;
|
||||
if (!view) return;
|
||||
view.dispatch(view.state.replaceSelection(text));
|
||||
view.focus();
|
||||
}}
|
||||
replace={(text) => {
|
||||
const view = editor.current;
|
||||
if (!view) return;
|
||||
view.dispatch({
|
||||
changes: { from: 0, to: view.state.doc.length, insert: text },
|
||||
});
|
||||
}}
|
||||
/>
|
||||
<div className="editor" ref={root} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { useState, type ReactNode } from "react";
|
||||
import type { GroupInputs, ParamDef } from "@shellbook/core";
|
||||
import { paramLabel } from "./ParamsForm";
|
||||
import { readFlag, writeFlag } from "./uiPrefs";
|
||||
|
||||
/** What the outline color means, in words (color is never the only signal). */
|
||||
function statusText(inputs: GroupInputs, labelOf: (name: string) => string): string {
|
||||
if (inputs.status === "missing") {
|
||||
const names = [...inputs.missing, ...inputs.invalid];
|
||||
const shown = names.slice(0, 3).map(labelOf).join(", ");
|
||||
const more = names.length > 3 ? ` +${names.length - 3}` : "";
|
||||
return inputs.missing.length ? `needs ${shown}${more}` : `check ${shown}${more}`;
|
||||
}
|
||||
if (inputs.status === "filled") return "complete";
|
||||
if (inputs.status === "optional") return "optional";
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* A titled, collapsible container (`:::group`, and `::use` sections). The outline shows
|
||||
* whether its inputs are filled in: orange — needed values missing, green — complete,
|
||||
* grey — optional or no inputs. The open state is remembered per `storageKey`.
|
||||
*/
|
||||
export function GroupSection({
|
||||
title,
|
||||
subtitle,
|
||||
inputs,
|
||||
params,
|
||||
storageKey,
|
||||
defaultOpen = true,
|
||||
className = "",
|
||||
children,
|
||||
}: {
|
||||
title: string;
|
||||
subtitle?: string;
|
||||
inputs: GroupInputs;
|
||||
/** The notebook's parameters, for labels in the status text. */
|
||||
params: ParamDef[];
|
||||
storageKey: string;
|
||||
defaultOpen?: boolean;
|
||||
className?: string;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const flag = `group:${storageKey}`;
|
||||
const [open, setOpen] = useState(() => readFlag(flag, defaultOpen));
|
||||
const labelOf = (name: string) => {
|
||||
const def = params.find((param) => param.name === name);
|
||||
return def ? paramLabel(def) : name;
|
||||
};
|
||||
const status = statusText(inputs, labelOf);
|
||||
return (
|
||||
<section className={`group status-${inputs.status} ${className}`.trim()} aria-label={title}>
|
||||
<header>
|
||||
<button
|
||||
type="button"
|
||||
className="group-toggle"
|
||||
aria-expanded={open}
|
||||
onClick={() => {
|
||||
writeFlag(flag, !open);
|
||||
setOpen(!open);
|
||||
}}
|
||||
>
|
||||
<span className="caret" aria-hidden="true">
|
||||
{open ? "▾" : "▸"}
|
||||
</span>
|
||||
<span className="group-title">{title}</span>
|
||||
</button>
|
||||
{subtitle && <small className="muted">{subtitle}</small>}
|
||||
{status && <small className="group-status">{status}</small>}
|
||||
</header>
|
||||
<div className="group-body" hidden={!open}>
|
||||
{children}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// Feature navigation: add entries here and mount their view in App.
|
||||
export const navigationItems = ["Notebooks", "Hosts", "Settings"] as const;
|
||||
export type NavigationPage = (typeof navigationItems)[number];
|
||||
export function HeaderNavigation({
|
||||
page,
|
||||
onChange,
|
||||
}: {
|
||||
page: NavigationPage;
|
||||
onChange: (page: NavigationPage) => void;
|
||||
}) {
|
||||
return (
|
||||
<nav aria-label="Main navigation">
|
||||
{navigationItems.map((item) => (
|
||||
<button
|
||||
key={item}
|
||||
aria-current={page === item ? "page" : undefined}
|
||||
onClick={() => onChange(item)}
|
||||
>
|
||||
{item}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { useState } from "react";
|
||||
import type { HostInfo, RenderedHost } from "@shellbook/core";
|
||||
|
||||
/**
|
||||
* A notebook's `::host` block: adds the machine a notebook created (e.g. an LXC container)
|
||||
* to Hosts, so later steps can target it. Never overwrites a different existing host.
|
||||
*/
|
||||
export function HostBlockCard({
|
||||
rendered,
|
||||
existing,
|
||||
captured,
|
||||
onAdd,
|
||||
onUse,
|
||||
}: {
|
||||
rendered: RenderedHost;
|
||||
/** Host with the same name already in Hosts. */
|
||||
existing?: HostInfo;
|
||||
/** Runtime value of the block's capture, if any. */
|
||||
captured?: string;
|
||||
onAdd(host: HostInfo): Promise<void>;
|
||||
onUse(name: string): void;
|
||||
}) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const problems = Object.entries(rendered.invalid);
|
||||
const ready = !rendered.missing.length && !problems.length;
|
||||
const same =
|
||||
!!existing &&
|
||||
existing.address === rendered.address &&
|
||||
existing.user === rendered.user &&
|
||||
existing.port === rendered.port;
|
||||
async function add() {
|
||||
setBusy(true);
|
||||
setError("");
|
||||
try {
|
||||
await onAdd({
|
||||
name: rendered.name,
|
||||
address: rendered.address,
|
||||
user: rendered.user,
|
||||
port: rendered.port,
|
||||
tags: [],
|
||||
});
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<article className="step host-block" aria-label={`Add host ${rendered.name}`}>
|
||||
<header>
|
||||
<strong>Add to Hosts</strong>
|
||||
<code>
|
||||
{rendered.user}@{rendered.address}:{rendered.port}
|
||||
</code>
|
||||
<span>as {rendered.name}</span>
|
||||
</header>
|
||||
{rendered.missing.length > 0 && (
|
||||
<p className="muted">
|
||||
Available after: {rendered.missing.join(", ")}
|
||||
</p>
|
||||
)}
|
||||
{problems.map(([field, message]) => (
|
||||
<p className="error" key={field}>
|
||||
{message}
|
||||
</p>
|
||||
))}
|
||||
{ready &&
|
||||
(existing ? (
|
||||
same ? (
|
||||
captured === existing.name ? (
|
||||
<p role="status">✓ {existing.name} is in Hosts</p>
|
||||
) : (
|
||||
<button onClick={() => onUse(existing.name)}>
|
||||
Use existing host {existing.name}
|
||||
</button>
|
||||
)
|
||||
) : (
|
||||
<p className="error" role="alert">
|
||||
A different host named {rendered.name} already exists. Choose
|
||||
another name or change it under Hosts.
|
||||
</p>
|
||||
)
|
||||
) : (
|
||||
<button className="primary" disabled={busy} onClick={() => void add()}>
|
||||
{busy ? "Adding…" : "Add to Hosts"}
|
||||
</button>
|
||||
))}
|
||||
{error && (
|
||||
<p className="error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<p className="muted">
|
||||
The first connection asks you to confirm the new server's host key.
|
||||
</p>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
export function HostKeyConfirmation({
|
||||
host,
|
||||
fingerprint,
|
||||
changed,
|
||||
busy = false,
|
||||
onReject,
|
||||
onTrust,
|
||||
}: {
|
||||
host: string;
|
||||
fingerprint: string;
|
||||
changed: boolean;
|
||||
busy?: boolean;
|
||||
onReject: () => void;
|
||||
onTrust: () => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="modal-backdrop">
|
||||
<section role="dialog" aria-modal="true" aria-labelledby="hostkey-title">
|
||||
<h2 id="hostkey-title">
|
||||
{changed ? "WARNING: HOST KEY CHANGED" : "Unknown SSH host key"}
|
||||
</h2>
|
||||
{changed && (
|
||||
<p className="error">
|
||||
STOP: a different key is already trusted. This may indicate a
|
||||
man-in-the-middle attack. Verify the fingerprint independently
|
||||
before accepting.
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
Verify the key for <strong>{host}</strong> through a trusted channel.
|
||||
</p>
|
||||
<code>{fingerprint}</code>
|
||||
<div className="actions">
|
||||
<button disabled={busy} onClick={onReject}>
|
||||
Reject
|
||||
</button>
|
||||
<button disabled={busy} onClick={onTrust}>
|
||||
Trust this fingerprint and retry
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,565 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import type {
|
||||
HostInfo,
|
||||
HostInventoryResponse,
|
||||
HostActionRequest,
|
||||
HostActionResponse,
|
||||
HostCredentialInput,
|
||||
} from "@shellbook/core";
|
||||
import { json } from "./api";
|
||||
import "./hosts.css";
|
||||
import { HostKeyConfirmation } from "./HostKeyConfirmation";
|
||||
import { CopyButton, Dialog, Menu } from "./ui";
|
||||
const base = "/host-management";
|
||||
const url = (name: string) => `${base}/${encodeURIComponent(name)}`;
|
||||
const credentialNames: Record<string, string> = {
|
||||
shellbook: "ShellBook key",
|
||||
password: "Password",
|
||||
privateKey: "Private key",
|
||||
certificate: "Certificate",
|
||||
};
|
||||
const empty: HostInfo = {
|
||||
name: "",
|
||||
address: "",
|
||||
user: "root",
|
||||
port: 22,
|
||||
tags: [],
|
||||
};
|
||||
export function HostsPage({ onChange }: { onChange?: () => void }) {
|
||||
const [inventory, setInventory] = useState<HostInventoryResponse>();
|
||||
const [draft, setDraft] = useState<HostInfo>({ ...empty });
|
||||
const [editVersion, setEditVersion] = useState("");
|
||||
const [editing, setEditing] = useState<string>();
|
||||
/** The add/edit server dialog is open. */
|
||||
const [form, setForm] = useState(false);
|
||||
const [credentialHost, setCredentialHost] = useState<string>();
|
||||
const [type, setType] = useState<HostCredentialInput["type"]>("shellbook");
|
||||
const [password, setPassword] = useState("");
|
||||
const [privateKey, setPrivateKey] = useState("");
|
||||
const [passphrase, setPassphrase] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
const [status, setStatus] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [install, setInstall] = useState<{ host: string; script: string }>();
|
||||
const [trust, setTrust] = useState<{
|
||||
host: string;
|
||||
request: HostActionRequest;
|
||||
key: { fingerprint: string; changed: boolean };
|
||||
}>();
|
||||
const load = useCallback(
|
||||
async () => setInventory(await json<HostInventoryResponse>(base)),
|
||||
[],
|
||||
);
|
||||
useEffect(() => {
|
||||
void load().catch(() =>
|
||||
setError("Cannot load hosts or ShellBook public key."),
|
||||
);
|
||||
const changed = () => {
|
||||
void load().catch(() => setError("Cannot reload hosts."));
|
||||
};
|
||||
window.addEventListener("shellbook:hosts-changed", changed);
|
||||
return () => window.removeEventListener("shellbook:hosts-changed", changed);
|
||||
}, [load]);
|
||||
async function perform(work: () => Promise<void>) {
|
||||
setBusy(true);
|
||||
setError("");
|
||||
setStatus("");
|
||||
try {
|
||||
await work();
|
||||
} catch (e) {
|
||||
const message = e instanceof Error ? e.message : String(e);
|
||||
setError(
|
||||
(e as { status?: number }).status === 409
|
||||
? `${message}. Reload hosts before retrying.`
|
||||
: message,
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
async function action(host: string, request: HostActionRequest) {
|
||||
const response = await json<HostActionResponse>(
|
||||
`${url(host)}/action`,
|
||||
"POST",
|
||||
request,
|
||||
);
|
||||
if ("hostKey" in response)
|
||||
setTrust({ host, request, key: response.hostKey });
|
||||
else {
|
||||
setTrust(undefined);
|
||||
setInstall(undefined);
|
||||
setStatus(
|
||||
`${host}: ${response.exitCode === 0 ? "success" : `failed (exit ${response.exitCode})`}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
const closeForm = () => {
|
||||
setForm(false);
|
||||
setEditing(undefined);
|
||||
setDraft({ ...empty });
|
||||
};
|
||||
const closeCredentials = () => {
|
||||
setCredentialHost(undefined);
|
||||
setPassword("");
|
||||
setPrivateKey("");
|
||||
setPassphrase("");
|
||||
};
|
||||
return (
|
||||
<section className="page hosts-page" aria-label="Server management">
|
||||
<header className="page-header">
|
||||
<div>
|
||||
<h1>Hosts</h1>
|
||||
<p className="muted">
|
||||
Servers ShellBook connects to over SSH, and how it signs in.
|
||||
</p>
|
||||
</div>
|
||||
<span className="spacer" />
|
||||
<button disabled={busy} onClick={() => void perform(load)}>
|
||||
Reload
|
||||
</button>
|
||||
<button
|
||||
className="primary"
|
||||
disabled={!inventory}
|
||||
onClick={() => {
|
||||
setEditing(undefined);
|
||||
setDraft({ ...empty });
|
||||
setForm(true);
|
||||
}}
|
||||
>
|
||||
Add server
|
||||
</button>
|
||||
</header>
|
||||
{error && !form && !credentialHost && (
|
||||
<p role="alert" className="banner error">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{status && (
|
||||
<p role="status" className="banner ok">
|
||||
{status}
|
||||
</p>
|
||||
)}
|
||||
{inventory && (
|
||||
<>
|
||||
<div className="host-list">
|
||||
{!inventory.hosts.length && (
|
||||
<p className="empty">
|
||||
No servers yet. Add one, or run a notebook such as
|
||||
infra/lxc-container.md that adds the machine it creates.
|
||||
</p>
|
||||
)}
|
||||
{inventory.hosts.map((host) => (
|
||||
<article key={host.name} className="host-row" aria-label={host.name}>
|
||||
<div className="host-main">
|
||||
<h2>{host.name}</h2>
|
||||
<code>
|
||||
{host.user}@{host.address}
|
||||
{host.port === 22 ? "" : `:${host.port}`}
|
||||
</code>
|
||||
</div>
|
||||
<div className="host-meta">
|
||||
{host.tags.map((tag) => (
|
||||
<span key={tag} className={`chip ${tag === "prod" ? "warn" : ""}`}>
|
||||
{tag}
|
||||
</span>
|
||||
))}
|
||||
<span
|
||||
className="chip"
|
||||
title={[
|
||||
host.credential.fingerprint,
|
||||
host.credential.setAt && `set ${host.credential.setAt}`,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · ")}
|
||||
>
|
||||
{credentialNames[host.credential.type] ?? host.credential.type}
|
||||
</span>
|
||||
</div>
|
||||
<div className="actions">
|
||||
<button
|
||||
disabled={busy}
|
||||
aria-label={`Test connection to ${host.name}`}
|
||||
onClick={() =>
|
||||
void perform(() => action(host.name, { action: "test" }))
|
||||
}
|
||||
>
|
||||
Test
|
||||
</button>
|
||||
<button
|
||||
disabled={busy}
|
||||
aria-label={`Edit ${host.name}`}
|
||||
onClick={() => {
|
||||
setEditing(host.name);
|
||||
setEditVersion(inventory.version);
|
||||
setDraft({
|
||||
name: host.name,
|
||||
address: host.address,
|
||||
user: host.user,
|
||||
port: host.port,
|
||||
tags: host.tags,
|
||||
});
|
||||
setError("");
|
||||
setForm(true);
|
||||
}}
|
||||
>
|
||||
Edit
|
||||
</button>
|
||||
<button
|
||||
disabled={busy}
|
||||
aria-label={`SSH credentials for ${host.name}`}
|
||||
onClick={() => {
|
||||
setCredentialHost(host.name);
|
||||
setType("shellbook");
|
||||
setPassword("");
|
||||
setPrivateKey("");
|
||||
setPassphrase("");
|
||||
}}
|
||||
>
|
||||
Credentials
|
||||
</button>
|
||||
<Menu label={`More actions for ${host.name}`}>
|
||||
{(close) => (
|
||||
<>
|
||||
<button
|
||||
role="menuitem"
|
||||
disabled={busy || host.credential.type !== "password"}
|
||||
title={
|
||||
host.credential.type === "password"
|
||||
? undefined
|
||||
: "Needs a saved password"
|
||||
}
|
||||
onClick={() => {
|
||||
close();
|
||||
void perform(async () => {
|
||||
const { script } = await json<{ script: string }>(
|
||||
`${url(host.name)}/install-key`,
|
||||
);
|
||||
setInstall({ host: host.name, script });
|
||||
});
|
||||
}}
|
||||
>
|
||||
Install ShellBook key on {host.name}
|
||||
</button>
|
||||
<button
|
||||
role="menuitem"
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
close();
|
||||
if (
|
||||
window.confirm(
|
||||
`Forget trusted SSH host key for ${host.name}? The next connection requires verification.`,
|
||||
)
|
||||
)
|
||||
void perform(async () => {
|
||||
await json(`${url(host.name)}/known-key`, "DELETE");
|
||||
setStatus("Host key forgotten");
|
||||
});
|
||||
}}
|
||||
>
|
||||
Forget host key
|
||||
</button>
|
||||
<button
|
||||
role="menuitem"
|
||||
className="danger"
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
close();
|
||||
if (
|
||||
window.confirm(
|
||||
`Delete ${host.name} and its stored credential?`,
|
||||
)
|
||||
)
|
||||
void perform(async () => {
|
||||
await json(url(host.name), "DELETE", {
|
||||
baseVersion: inventory.version,
|
||||
});
|
||||
await load();
|
||||
onChange?.();
|
||||
});
|
||||
}}
|
||||
>
|
||||
Delete {host.name}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</Menu>
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
<details className="card public-key">
|
||||
<summary>ShellBook public key</summary>
|
||||
<p className="muted">
|
||||
Add it to <code>~/.ssh/authorized_keys</code> on a server, or save
|
||||
the server's password under Credentials and use “Install
|
||||
ShellBook key” from its ⋯ menu.
|
||||
</p>
|
||||
<pre>{inventory.publicKey}</pre>
|
||||
<div className="actions">
|
||||
<CopyButton label="Copy public key" text={() => inventory.publicKey} />
|
||||
</div>
|
||||
<p className="muted">{inventory.certificateSupport.reason}</p>
|
||||
</details>
|
||||
{form && (
|
||||
<Dialog
|
||||
title={editing ? `Edit ${editing}` : "Add server"}
|
||||
onClose={closeForm}
|
||||
>
|
||||
<form
|
||||
className="grid-form"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void perform(async () => {
|
||||
await json(
|
||||
editing ? url(editing) : base,
|
||||
editing ? "PUT" : "POST",
|
||||
{
|
||||
host: draft,
|
||||
baseVersion: editing ? editVersion : inventory.version,
|
||||
},
|
||||
);
|
||||
closeForm();
|
||||
await load();
|
||||
onChange?.();
|
||||
});
|
||||
}}
|
||||
>
|
||||
<label>
|
||||
Name
|
||||
<input
|
||||
required
|
||||
pattern="[A-Za-z0-9._-]+"
|
||||
placeholder="web-1"
|
||||
value={draft.name}
|
||||
onChange={(e) => setDraft({ ...draft, name: e.target.value })}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Address
|
||||
<input
|
||||
required
|
||||
placeholder="10.0.0.5 or host.example.org"
|
||||
value={draft.address}
|
||||
onChange={(e) =>
|
||||
setDraft({ ...draft, address: e.target.value })
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
SSH user
|
||||
<input
|
||||
required
|
||||
value={draft.user}
|
||||
onChange={(e) => setDraft({ ...draft, user: e.target.value })}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Port
|
||||
<input
|
||||
required
|
||||
type="number"
|
||||
min="1"
|
||||
max="65535"
|
||||
value={draft.port}
|
||||
onChange={(e) =>
|
||||
setDraft({ ...draft, port: Number(e.target.value) })
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="full">
|
||||
Tags (comma separated; “prod” asks before every run)
|
||||
<input
|
||||
value={draft.tags.join(",")}
|
||||
onChange={(e) =>
|
||||
setDraft({
|
||||
...draft,
|
||||
tags: e.target.value
|
||||
.split(",")
|
||||
.map((t) => t.trim())
|
||||
.filter(Boolean),
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
{error && (
|
||||
<p role="alert" className="error full">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<div className="dialog-actions full">
|
||||
<button type="button" onClick={closeForm}>
|
||||
Cancel
|
||||
</button>
|
||||
<button className="primary" disabled={busy}>
|
||||
Save server
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</Dialog>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{credentialHost && (
|
||||
<Dialog
|
||||
title={`SSH credentials for ${credentialHost}`}
|
||||
onClose={closeCredentials}
|
||||
>
|
||||
<p className="muted">
|
||||
Saved secrets cannot be read back. Blank fields do not represent the
|
||||
existing credential.
|
||||
</p>
|
||||
<form
|
||||
className="stack"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
const credential: HostCredentialInput =
|
||||
type === "password"
|
||||
? { type, password }
|
||||
: type === "privateKey"
|
||||
? { type, privateKey, passphrase }
|
||||
: { type };
|
||||
setPassword("");
|
||||
setPrivateKey("");
|
||||
setPassphrase("");
|
||||
void perform(async () => {
|
||||
await json(
|
||||
`${url(credentialHost)}/credential`,
|
||||
"PUT",
|
||||
credential,
|
||||
);
|
||||
setCredentialHost(undefined);
|
||||
await load();
|
||||
});
|
||||
}}
|
||||
>
|
||||
<label>
|
||||
Authentication
|
||||
<select
|
||||
value={type}
|
||||
onChange={(e) => setType(e.target.value as typeof type)}
|
||||
>
|
||||
<option value="shellbook">
|
||||
ShellBook key (remove stored credential)
|
||||
</option>
|
||||
<option value="password">Password</option>
|
||||
<option value="privateKey">Private key</option>
|
||||
<option disabled>OpenSSH certificate (unavailable)</option>
|
||||
</select>
|
||||
</label>
|
||||
{type === "password" && (
|
||||
<label>
|
||||
SSH password
|
||||
<input
|
||||
required
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
{type === "privateKey" && (
|
||||
<>
|
||||
<label>
|
||||
Private key
|
||||
<textarea
|
||||
required
|
||||
rows={6}
|
||||
value={privateKey}
|
||||
onChange={(e) => setPrivateKey(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Upload private key
|
||||
<input
|
||||
type="file"
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file)
|
||||
void perform(async () => {
|
||||
if (file.size > 65536)
|
||||
throw new Error("Key exceeds 64 KiB");
|
||||
setPrivateKey(await file.text());
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Key passphrase (optional)
|
||||
<input
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
value={passphrase}
|
||||
onChange={(e) => setPassphrase(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
</>
|
||||
)}
|
||||
{error && (
|
||||
<p role="alert" className="error">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<div className="dialog-actions">
|
||||
<button type="button" onClick={closeCredentials}>
|
||||
Cancel
|
||||
</button>
|
||||
<button className="primary" disabled={busy}>
|
||||
Save authentication
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</Dialog>
|
||||
)}
|
||||
{install && (
|
||||
<Dialog
|
||||
wide
|
||||
title={`Install ShellBook key on ${install.host}`}
|
||||
onClose={() => setInstall(undefined)}
|
||||
>
|
||||
<p className="muted">
|
||||
This exact script runs using the stored password. After success,
|
||||
select ShellBook key in SSH credentials to remove the saved
|
||||
password.
|
||||
</p>
|
||||
<pre className="script">{install.script}</pre>
|
||||
<div className="dialog-actions">
|
||||
<button onClick={() => setInstall(undefined)}>
|
||||
Cancel installation
|
||||
</button>
|
||||
<button
|
||||
className="primary"
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
void perform(() =>
|
||||
action(install.host, {
|
||||
action: "install-key",
|
||||
script: install.script,
|
||||
}),
|
||||
)
|
||||
}
|
||||
>
|
||||
Run displayed script
|
||||
</button>
|
||||
</div>
|
||||
</Dialog>
|
||||
)}
|
||||
{trust && (
|
||||
<HostKeyConfirmation
|
||||
host={trust.host}
|
||||
{...trust.key}
|
||||
busy={busy}
|
||||
onReject={() => setTrust(undefined)}
|
||||
onTrust={() =>
|
||||
void perform(() =>
|
||||
action(trust.host, {
|
||||
...trust.request,
|
||||
acceptHostKey: trust.key.fingerprint,
|
||||
}),
|
||||
)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
import "./notebooks.css";
|
||||
import { useState } from "react";
|
||||
import type { NotebookSummary } from "@shellbook/core";
|
||||
import type { Api } from "./api";
|
||||
import { newNotebook } from "./authoring";
|
||||
import { Dialog, Menu } from "./ui";
|
||||
type Node = { folders: Map<string, Node>; files: NotebookSummary[] };
|
||||
function tree(list: NotebookSummary[]): Node {
|
||||
const root: Node = { folders: new Map(), files: [] };
|
||||
for (const file of list) {
|
||||
let node = root;
|
||||
for (const part of file.path.split("/").slice(0, -1)) {
|
||||
if (!node.folders.has(part))
|
||||
node.folders.set(part, { folders: new Map(), files: [] });
|
||||
node = node.folders.get(part)!;
|
||||
}
|
||||
node.files.push(file);
|
||||
}
|
||||
return root;
|
||||
}
|
||||
export function NotebookList({
|
||||
api,
|
||||
list,
|
||||
path,
|
||||
version,
|
||||
onSelect,
|
||||
onChanged,
|
||||
canLeave,
|
||||
}: {
|
||||
api: Api;
|
||||
list: NotebookSummary[];
|
||||
path: string;
|
||||
version?: string;
|
||||
onSelect(path: string): void;
|
||||
onChanged(path?: string): Promise<void>;
|
||||
canLeave(): boolean;
|
||||
}) {
|
||||
const [search, setSearch] = useState("");
|
||||
const [action, setAction] = useState<
|
||||
"new" | "rename" | "duplicate" | "delete"
|
||||
>();
|
||||
const [error, setError] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const choose = (op: "rename" | "duplicate" | "delete") => {
|
||||
setAction(op);
|
||||
setError("");
|
||||
};
|
||||
const render = (node: Node) => (
|
||||
<>
|
||||
{[...node.folders]
|
||||
.sort(([a], [b]) => a.localeCompare(b))
|
||||
.map(([name, child]) => (
|
||||
<details key={name} open>
|
||||
<summary>{name}</summary>
|
||||
{render(child)}
|
||||
</details>
|
||||
))}
|
||||
{node.files.map((item) => (
|
||||
<div
|
||||
className={`notebook-item ${item.path === path ? "selected" : ""}`}
|
||||
key={item.path}
|
||||
>
|
||||
<button
|
||||
aria-current={item.path === path ? "page" : undefined}
|
||||
title={item.path}
|
||||
onClick={() => onSelect(item.path)}
|
||||
>
|
||||
{item.title}
|
||||
</button>
|
||||
{item.path === path && (
|
||||
<Menu label={`Actions for ${item.title}`}>
|
||||
{(close) =>
|
||||
(["rename", "duplicate", "delete"] as const).map((op) => (
|
||||
<button
|
||||
key={op}
|
||||
role="menuitem"
|
||||
className={op === "delete" ? "danger" : ""}
|
||||
onClick={() => {
|
||||
close();
|
||||
choose(op);
|
||||
}}
|
||||
>
|
||||
{op === "rename"
|
||||
? "Rename / move"
|
||||
: op === "duplicate"
|
||||
? "Duplicate"
|
||||
: "Delete"}
|
||||
</button>
|
||||
))
|
||||
}
|
||||
</Menu>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
const shown = list.filter((n) =>
|
||||
`${n.path} ${n.title}`.toLowerCase().includes(search.toLowerCase()),
|
||||
);
|
||||
return (
|
||||
<>
|
||||
<div className="sidebar-tools">
|
||||
<input
|
||||
type="search"
|
||||
aria-label="Search notebooks"
|
||||
placeholder="Search notebooks"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
/>
|
||||
<button
|
||||
className="icon"
|
||||
aria-label="New notebook"
|
||||
title="New notebook"
|
||||
onClick={() => {
|
||||
setAction("new");
|
||||
setError("");
|
||||
}}
|
||||
>
|
||||
+
|
||||
</button>
|
||||
</div>
|
||||
<nav aria-label="Notebooks">
|
||||
{render(tree(shown))}
|
||||
{!shown.length && (
|
||||
<p className="muted">
|
||||
{list.length ? "No notebook matches." : "No notebooks yet."}
|
||||
</p>
|
||||
)}
|
||||
</nav>
|
||||
{action && (
|
||||
<Dialog
|
||||
title={
|
||||
action === "new"
|
||||
? "New notebook"
|
||||
: action === "rename"
|
||||
? "Rename or move notebook"
|
||||
: action === "duplicate"
|
||||
? "Duplicate notebook"
|
||||
: "Delete notebook"
|
||||
}
|
||||
onClose={() => {
|
||||
if (!busy) setAction(undefined);
|
||||
}}
|
||||
>
|
||||
<form
|
||||
className="stack"
|
||||
key={`${action}:${path}`}
|
||||
aria-label="Manage notebook"
|
||||
onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
if (busy) return;
|
||||
const data = new FormData(e.currentTarget);
|
||||
if (!canLeave()) return;
|
||||
setBusy(true);
|
||||
setError("");
|
||||
try {
|
||||
let next: string | undefined;
|
||||
if (action === "new") {
|
||||
const folder = String(data.get("folder")).trim();
|
||||
let name = String(data.get("name")).trim();
|
||||
if (!name.endsWith(".md")) name += ".md";
|
||||
const result = await api.create(
|
||||
(folder ? folder + "/" : "") + name,
|
||||
newNotebook(String(data.get("title"))),
|
||||
);
|
||||
next = result.path;
|
||||
} else {
|
||||
if (!version)
|
||||
throw new Error("Reload the notebook before changing it");
|
||||
if (action === "delete")
|
||||
await api.deleteNotebook(path, version);
|
||||
else
|
||||
next = (
|
||||
await api.move(
|
||||
path,
|
||||
String(data.get("path")).trim(),
|
||||
version,
|
||||
action === "duplicate",
|
||||
)
|
||||
).path;
|
||||
}
|
||||
await onChanged(next);
|
||||
setAction(undefined);
|
||||
} catch (err) {
|
||||
setError(
|
||||
`${String(err)}. Refresh the list and retry if the notebook changed.`,
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{action === "delete" ? (
|
||||
<p>
|
||||
Delete <code>{path}</code>? This cannot be undone.
|
||||
</p>
|
||||
) : (
|
||||
action !== "new" && (
|
||||
<p className="muted">
|
||||
From <code>{path}</code>
|
||||
</p>
|
||||
)
|
||||
)}
|
||||
{action === "new" ? (
|
||||
<>
|
||||
<label>
|
||||
Name
|
||||
<input name="name" required placeholder="debian-upgrade" />
|
||||
</label>
|
||||
<label>
|
||||
Folder (optional)
|
||||
<input name="folder" placeholder="operations/linux" />
|
||||
</label>
|
||||
<label>
|
||||
Title
|
||||
<input name="title" required />
|
||||
</label>
|
||||
</>
|
||||
) : (
|
||||
action !== "delete" && (
|
||||
<label>
|
||||
Destination path
|
||||
<input
|
||||
name="path"
|
||||
defaultValue={
|
||||
action === "duplicate"
|
||||
? path.replace(/\.md$/, "-copy.md")
|
||||
: path
|
||||
}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
)
|
||||
)}
|
||||
{error && (
|
||||
<p role="alert" className="error">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<div className="dialog-actions">
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => setAction(undefined)}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
className={action === "delete" ? "danger" : "primary"}
|
||||
disabled={busy}
|
||||
>
|
||||
{action === "delete" ? "Confirm delete" : "Apply"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</Dialog>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
+225
-47
@@ -1,69 +1,247 @@
|
||||
import type { HostInfo, Notebook, ParamValues } from "@shellbook/core";
|
||||
import { useEffect, useState } from "react";
|
||||
import type { HostInfo, InputStatus, Notebook, ParamDef, ParamValues } from "@shellbook/core";
|
||||
import { readFlag, writeFlag } from "./uiPrefs";
|
||||
|
||||
/** An included notebook (`::use`) whose parameters the form shows as a group. */
|
||||
export interface ParamGroup {
|
||||
scope: string;
|
||||
title: string;
|
||||
/** Input status of the included notebook (core groupInputs), shown as the outline color. */
|
||||
status?: InputStatus;
|
||||
}
|
||||
|
||||
const groupFlag = (title: string) => `params-group:${title}`;
|
||||
|
||||
/** The label a parameter is shown with; included ones without a label use their local name. */
|
||||
export const paramLabel = (param: ParamDef) =>
|
||||
param.label ?? (param.scope ? param.name.slice(param.scope.length + 1) : param.name);
|
||||
|
||||
/**
|
||||
* One parameter input, used by the parameter panel and by `::param` fields in the text.
|
||||
* `idPrefix` keeps element ids unique when the same parameter appears in both places.
|
||||
*/
|
||||
export function ParamField({
|
||||
param,
|
||||
value,
|
||||
error,
|
||||
hosts,
|
||||
idPrefix = "param",
|
||||
onChange,
|
||||
}: {
|
||||
param: ParamDef;
|
||||
value: string | undefined;
|
||||
error: string | undefined;
|
||||
hosts: HostInfo[];
|
||||
idPrefix?: string;
|
||||
onChange(name: string, value: string): void;
|
||||
}) {
|
||||
const id = `${idPrefix}-${param.name}`;
|
||||
const label = paramLabel(param);
|
||||
const common = {
|
||||
id,
|
||||
required: param.required,
|
||||
value: value ?? "",
|
||||
"aria-labelledby": `${id}-label`,
|
||||
"aria-invalid": !!error,
|
||||
// Red only for a wrong value; an empty field just still needs one.
|
||||
className: error && value ? "invalid" : undefined,
|
||||
"aria-describedby": error ? `${id}-error` : undefined,
|
||||
onChange: (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => onChange(param.name, e.target.value),
|
||||
};
|
||||
return (
|
||||
<label htmlFor={id}>
|
||||
<span id={`${id}-label`} title={label}>
|
||||
{label}
|
||||
{param.required && <b title="Required"> *</b>}
|
||||
</span>
|
||||
{param.type === "host" || param.type === "choice" ? (
|
||||
<select {...common}>
|
||||
<option value="">Select…</option>
|
||||
{(param.type === "host" ? hosts.map((h) => h.name) : (param.options ?? [])).map((option) => (
|
||||
<option key={option}>{option}</option>
|
||||
))}
|
||||
</select>
|
||||
) : (
|
||||
<input
|
||||
{...common}
|
||||
type={param.type === "secret" ? "password" : "text"}
|
||||
autoComplete={param.type === "secret" ? "new-password" : "off"}
|
||||
spellCheck={false}
|
||||
/>
|
||||
)}
|
||||
{error && (
|
||||
// An empty field only needs a value: say so quietly; a wrong value is an error.
|
||||
<small id={`${id}-error`} className={value ? "error" : "muted"}>
|
||||
{error}
|
||||
</small>
|
||||
)}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
export function ParamsForm({
|
||||
notebook,
|
||||
values,
|
||||
errors,
|
||||
hosts,
|
||||
groups = [],
|
||||
open = true,
|
||||
onToggle,
|
||||
onChange,
|
||||
onReset,
|
||||
}: {
|
||||
notebook: Notebook;
|
||||
values: ParamValues;
|
||||
errors: Record<string, string>;
|
||||
hosts: HostInfo[];
|
||||
/** Active included notebooks; parameters of inactive ones are hidden. */
|
||||
groups?: ParamGroup[];
|
||||
/** Collapsed, the form shows a one-line summary of the values instead of the fields. */
|
||||
open?: boolean;
|
||||
onToggle?(open: boolean): void;
|
||||
onChange(name: string, value: string): void;
|
||||
/** Clears the values typed for this notebook. */
|
||||
onReset?(): void;
|
||||
}) {
|
||||
// Group collapse choices are remembered per included notebook title.
|
||||
const [groupOpen, setGroupOpen] = useState<Record<string, boolean>>({});
|
||||
const isGroupOpen = (title: string) => groupOpen[title] ?? readFlag(groupFlag(title), true);
|
||||
const toggleGroup = (title: string, next: boolean) => {
|
||||
writeFlag(groupFlag(title), next);
|
||||
setGroupOpen((current) => ({ ...current, [title]: next }));
|
||||
};
|
||||
// A summary chip opens its field and moves focus there once it is rendered.
|
||||
const [focus, setFocus] = useState<string>();
|
||||
useEffect(() => {
|
||||
if (!focus) return;
|
||||
document.getElementById(`param-${focus}`)?.focus();
|
||||
setFocus(undefined);
|
||||
}, [focus]);
|
||||
|
||||
const top = notebook.params.filter((param) => !param.scope);
|
||||
const grouped = groups
|
||||
.map((group) => ({ group, params: notebook.params.filter((param) => param.scope === group.scope) }))
|
||||
.filter((entry) => entry.params.length);
|
||||
const shown = [...top, ...grouped.flatMap((entry) => entry.params)];
|
||||
if (!shown.length) return null;
|
||||
const missingOf = (params: ParamDef[]) =>
|
||||
params.filter((param) => param.required && !values[param.name]).length;
|
||||
const missing = missingOf(shown);
|
||||
const labelOf = paramLabel;
|
||||
|
||||
const reveal = (param: ParamDef) => {
|
||||
if (!open) onToggle?.(true);
|
||||
const group = grouped.find((entry) => entry.group.scope === param.scope);
|
||||
if (group && !isGroupOpen(group.group.title)) toggleGroup(group.group.title, true);
|
||||
setFocus(param.name);
|
||||
};
|
||||
/**
|
||||
* What needs attention: missing required values and values changed from their default,
|
||||
* each a button that opens its field. Untouched defaults are only counted.
|
||||
*/
|
||||
const summary = (params: ParamDef[], expand: () => void) => {
|
||||
const listed = params.filter((param) =>
|
||||
values[param.name] ? values[param.name] !== param.default : param.required,
|
||||
);
|
||||
const defaults = params.filter((param) => values[param.name] && values[param.name] === param.default).length;
|
||||
if (!listed.length && !defaults) return null;
|
||||
return (
|
||||
<span className="param-summary">
|
||||
{listed.map((param) => {
|
||||
const value = values[param.name];
|
||||
const label = labelOf(param);
|
||||
return (
|
||||
<button
|
||||
key={param.name}
|
||||
type="button"
|
||||
className={`param-chip${value ? "" : " pending"}${errors[param.name] && value ? " invalid" : ""}`}
|
||||
title={`${label}: ${errors[param.name] ?? "edit"}`}
|
||||
onClick={() => reveal(param)}
|
||||
>
|
||||
<span className="param-chip-label">{label}</span>
|
||||
<span className="param-chip-value">
|
||||
{!value ? "missing" : param.type === "secret" ? "••••" : value}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
{defaults > 0 && (
|
||||
<button type="button" className="link param-defaults" onClick={expand}>
|
||||
{listed.length ? "+ " : ""}
|
||||
{defaults} at default
|
||||
</button>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
const field = (param: ParamDef) => (
|
||||
<ParamField
|
||||
key={param.name}
|
||||
param={param}
|
||||
value={values[param.name]}
|
||||
error={errors[param.name]}
|
||||
hosts={hosts}
|
||||
onChange={onChange}
|
||||
/>
|
||||
);
|
||||
|
||||
return (
|
||||
<form
|
||||
className="params"
|
||||
className={`params${open ? "" : " collapsed"}`}
|
||||
aria-label="Notebook parameters"
|
||||
onSubmit={(e) => e.preventDefault()}
|
||||
>
|
||||
{notebook.params.map((param) => {
|
||||
const id = `param-${param.name}`;
|
||||
const common = {
|
||||
id,
|
||||
required: param.required,
|
||||
value: values[param.name] ?? "",
|
||||
"aria-labelledby": `${id}-label`,
|
||||
"aria-invalid": !!errors[param.name],
|
||||
"aria-describedby": errors[param.name] ? `${id}-error` : undefined,
|
||||
onChange: (
|
||||
e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>,
|
||||
) => onChange(param.name, e.target.value),
|
||||
};
|
||||
return (
|
||||
<label key={param.name} htmlFor={id}>
|
||||
<span id={`${id}-label`}>
|
||||
{param.label ?? param.name}
|
||||
{param.required && <b title="Required"> *</b>}
|
||||
</span>
|
||||
{param.type === "host" || param.type === "choice" ? (
|
||||
<select {...common}>
|
||||
<option value="">Select…</option>
|
||||
{(param.type === "host"
|
||||
? hosts.map((h) => h.name)
|
||||
: (param.options ?? [])
|
||||
).map((option) => (
|
||||
<option key={option}>{option}</option>
|
||||
))}
|
||||
</select>
|
||||
) : (
|
||||
<input
|
||||
{...common}
|
||||
type={param.type === "secret" ? "password" : "text"}
|
||||
autoComplete={param.type === "secret" ? "new-password" : "off"}
|
||||
spellCheck={false}
|
||||
/>
|
||||
)}
|
||||
{errors[param.name] && (
|
||||
<small id={`${id}-error`} className="error">
|
||||
{errors[param.name]}
|
||||
</small>
|
||||
)}
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
<header>
|
||||
<h2>
|
||||
<button
|
||||
type="button"
|
||||
className="params-toggle"
|
||||
aria-expanded={open}
|
||||
title={open ? "Collapse parameters" : "Expand parameters"}
|
||||
onClick={() => onToggle?.(!open)}
|
||||
>
|
||||
<span className="caret" aria-hidden="true">{open ? "▾" : "▸"}</span>
|
||||
Parameters
|
||||
</button>
|
||||
</h2>
|
||||
<small className={missing ? "pending" : "ok"}>
|
||||
{missing ? `${missing} required missing` : "All required set"}
|
||||
</small>
|
||||
{!open && summary(shown, () => onToggle?.(true))}
|
||||
{onReset && open && (
|
||||
<button type="button" className="link" onClick={onReset}>
|
||||
Reset
|
||||
</button>
|
||||
)}
|
||||
</header>
|
||||
{open && top.map(field)}
|
||||
{open &&
|
||||
grouped.map(({ group, params }) => {
|
||||
const expanded = isGroupOpen(group.title);
|
||||
const groupMissing = missingOf(params);
|
||||
return (
|
||||
<fieldset
|
||||
key={group.scope}
|
||||
className={`status-${group.status ?? "none"}${expanded ? "" : " collapsed"}`}
|
||||
aria-label={group.title}
|
||||
>
|
||||
<legend>
|
||||
<button
|
||||
type="button"
|
||||
className="params-toggle"
|
||||
aria-expanded={expanded}
|
||||
onClick={() => toggleGroup(group.title, !expanded)}
|
||||
>
|
||||
<span className="caret" aria-hidden="true">{expanded ? "▾" : "▸"}</span>
|
||||
{group.title}
|
||||
{groupMissing > 0 && <small className="pending"> · {groupMissing} missing</small>}
|
||||
</button>
|
||||
</legend>
|
||||
{expanded ? params.map(field) : summary(params, () => toggleGroup(group.title, true))}
|
||||
</fieldset>
|
||||
);
|
||||
})}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
import { useState } from "react";
|
||||
import type { ChangePasswordRequest, SetupRequest } from "@shellbook/core";
|
||||
export function PasswordForm({
|
||||
setup = false,
|
||||
submit,
|
||||
}: {
|
||||
setup?: boolean;
|
||||
submit: (body: ChangePasswordRequest & SetupRequest) => Promise<void>;
|
||||
}) {
|
||||
const [token, setToken] = useState("");
|
||||
const [currentPassword, setCurrent] = useState("");
|
||||
const [newPassword, setNew] = useState("");
|
||||
const [confirmPassword, setConfirm] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState("");
|
||||
return (
|
||||
<form
|
||||
onSubmit={async (event) => {
|
||||
event.preventDefault();
|
||||
if (newPassword !== confirmPassword) {
|
||||
setMessage("Passwords do not match");
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
setMessage("");
|
||||
try {
|
||||
await submit({
|
||||
token,
|
||||
currentPassword,
|
||||
newPassword,
|
||||
confirmPassword,
|
||||
});
|
||||
setToken("");
|
||||
setCurrent("");
|
||||
setNew("");
|
||||
setConfirm("");
|
||||
setMessage("Password saved. Other sessions have been signed out.");
|
||||
} catch {
|
||||
setMessage(
|
||||
"Unable to save. Check your credentials and try again; too many attempts require waiting a minute.",
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{setup ? (
|
||||
<label>
|
||||
Setup token
|
||||
<input
|
||||
required
|
||||
autoComplete="off"
|
||||
value={token}
|
||||
onChange={(e) => setToken(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
) : (
|
||||
<label>
|
||||
Current password
|
||||
<input
|
||||
required
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
value={currentPassword}
|
||||
onChange={(e) => setCurrent(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
<label>
|
||||
New password
|
||||
<input
|
||||
required
|
||||
type="password"
|
||||
minLength={12}
|
||||
autoComplete="new-password"
|
||||
value={newPassword}
|
||||
onChange={(e) => setNew(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Confirm password
|
||||
<input
|
||||
required
|
||||
type="password"
|
||||
minLength={12}
|
||||
autoComplete="new-password"
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirm(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<p>Use at least 12 characters (maximum 4096 bytes).</p>
|
||||
<button disabled={busy}>
|
||||
{setup ? "Set up ShellBook" : "Change password"}
|
||||
</button>
|
||||
{message && <p role="status">{message}</p>}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import type {
|
||||
ClaudeStatusResponse,
|
||||
SystemInfoResponse,
|
||||
SessionSettingsResponse,
|
||||
} from "@shellbook/core";
|
||||
import { settingsApi } from "./settingsApi";
|
||||
import { PasswordForm } from "./PasswordForm";
|
||||
import { UpdatePanel } from "./UpdatePanel";
|
||||
|
||||
function duration(seconds: number): string {
|
||||
const days = seconds / 86400;
|
||||
return days >= 1
|
||||
? `${Number.isInteger(days) ? days : days.toFixed(1)} day${days === 1 ? "" : "s"}`
|
||||
: `${Math.round(seconds / 3600)} hours`;
|
||||
}
|
||||
|
||||
export function SettingsPage({
|
||||
openTerminal,
|
||||
onSignOut,
|
||||
}: {
|
||||
openTerminal: () => void;
|
||||
/** Called after this browser signed out. */
|
||||
onSignOut?: () => void;
|
||||
}) {
|
||||
const [info, setInfo] = useState<SystemInfoResponse>();
|
||||
const [claude, setClaude] = useState<ClaudeStatusResponse | "error">();
|
||||
const [session, setSession] = useState<SessionSettingsResponse>();
|
||||
const [message, setMessage] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
const failed = () => {
|
||||
if (active) setMessage("Unable to load settings. Sign in again or retry.");
|
||||
};
|
||||
// Independent requests: the slower Claude check must not hold back the rest.
|
||||
settingsApi.system().then((i) => active && setInfo(i), failed);
|
||||
settingsApi.session().then((s) => active && setSession(s), failed);
|
||||
settingsApi.claude().then(
|
||||
(c) => active && setClaude(c),
|
||||
() => active && setClaude("error"),
|
||||
);
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, []);
|
||||
return (
|
||||
<div className="page settings-page">
|
||||
<header className="page-header">
|
||||
<div>
|
||||
<h1>Settings</h1>
|
||||
<p className="muted">Sign-in, the Claude CLI and this installation.</p>
|
||||
</div>
|
||||
</header>
|
||||
{message && (
|
||||
<p role="status" className="banner">
|
||||
{message}
|
||||
</p>
|
||||
)}
|
||||
<section className="card">
|
||||
<h2>Password and sessions</h2>
|
||||
<PasswordForm submit={settingsApi.password} />
|
||||
<hr />
|
||||
{session && (
|
||||
<p className="muted">
|
||||
Sessions last {duration(session.lifetimeSeconds)} (
|
||||
{session.lifetimeSeconds} seconds).
|
||||
</p>
|
||||
)}
|
||||
<div className="actions">
|
||||
<button
|
||||
disabled={busy}
|
||||
onClick={async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await settingsApi.revoke();
|
||||
setMessage(
|
||||
"Other sessions signed out. This browser remains signed in.",
|
||||
);
|
||||
} catch {
|
||||
setMessage("Unable to sign out sessions. Try again.");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Sign out all sessions
|
||||
</button>
|
||||
{onSignOut && (
|
||||
<button
|
||||
disabled={busy}
|
||||
onClick={async () => {
|
||||
try {
|
||||
await settingsApi.logout();
|
||||
onSignOut();
|
||||
} catch {
|
||||
setMessage("Unable to sign out. Try again.");
|
||||
}
|
||||
}}
|
||||
>
|
||||
Sign out this browser
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
<section className="card">
|
||||
<h2>Claude CLI</h2>
|
||||
{claude === undefined ? (
|
||||
<p className="muted">Checking the Claude CLI…</p>
|
||||
) : claude === "error" ? (
|
||||
<p className="error">Unable to check the Claude CLI.</p>
|
||||
) : (
|
||||
<ul className="checklist">
|
||||
<li className={claude.available ? "ok" : "bad"}>
|
||||
{claude.available
|
||||
? `Available: ${claude.version}`
|
||||
: "Claude is unavailable on PATH or did not respond."}
|
||||
</li>
|
||||
<li className={claude.loginAppearsPresent ? "ok" : "bad"}>
|
||||
{claude.loginAppearsPresent
|
||||
? "Credentials file exists; login may be available."
|
||||
: "No credentials file found."}
|
||||
</li>
|
||||
</ul>
|
||||
)}
|
||||
<p className="muted">
|
||||
Run <code>claude</code> in the terminal, then <code>/login</code>.
|
||||
Credentials are checked for existence only.
|
||||
</p>
|
||||
<div className="actions">
|
||||
<button onClick={openTerminal}>Open terminal to log in</button>
|
||||
</div>
|
||||
</section>
|
||||
<section className="card">
|
||||
<h2>About this installation</h2>
|
||||
{info ? (
|
||||
<dl className="facts">
|
||||
<dt>ShellBook version</dt>
|
||||
<dd>{info.version}</dd>
|
||||
<dt>Workspace</dt>
|
||||
<dd>
|
||||
<code>{info.workspacePath}</code>
|
||||
</dd>
|
||||
<dt>Data directory</dt>
|
||||
<dd>
|
||||
<code>{info.dataDirPath}</code>
|
||||
</dd>
|
||||
<dt>Node version</dt>
|
||||
<dd>{info.nodeVersion}</dd>
|
||||
</dl>
|
||||
) : (
|
||||
<p className="muted">Loading…</p>
|
||||
)}
|
||||
</section>
|
||||
<UpdatePanel />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { PasswordForm } from "./PasswordForm";
|
||||
import { settingsApi } from "./settingsApi";
|
||||
import { Logo } from "./ui";
|
||||
export function SetupScreen({ onComplete }: { onComplete: () => void }) {
|
||||
return (
|
||||
<main className="login">
|
||||
<h1>
|
||||
<Logo size={48} />
|
||||
Set up ShellBook
|
||||
</h1>
|
||||
<p>
|
||||
Enter the one-time token from the setup-token file in the server data
|
||||
directory.
|
||||
</p>
|
||||
<PasswordForm
|
||||
setup
|
||||
submit={async (body) => {
|
||||
await settingsApi.setup(body);
|
||||
onComplete();
|
||||
}}
|
||||
/>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
+40
-36
@@ -1,10 +1,10 @@
|
||||
import { ArtifactDownload } from "./ArtifactDownload";
|
||||
import { useState } from "react";
|
||||
import hljs from "highlight.js/lib/core";
|
||||
import bash from "highlight.js/lib/languages/bash";
|
||||
import type { HostInfo, RenderedStep, Step } from "@shellbook/core";
|
||||
import type { DownloadState, RunState } from "./events";
|
||||
import { sshCommand } from "./ssh";
|
||||
import { CopyButton } from "./ui";
|
||||
hljs.registerLanguage("bash", bash);
|
||||
|
||||
function Script({ script }: { script: string }) {
|
||||
@@ -28,6 +28,20 @@ function Script({ script }: { script: string }) {
|
||||
</pre>
|
||||
);
|
||||
}
|
||||
/** One short hint for what a step still needs, without repeating a name. */
|
||||
export function stepProblems(rendered: RenderedStep): string[] {
|
||||
const problems: string[] = [];
|
||||
if (rendered.missing.length)
|
||||
problems.push(`Fill in ${rendered.missing.join(", ")} to run this step.`);
|
||||
const unresolvedHost = !!rendered.host?.includes("{{");
|
||||
for (const [name, error] of Object.entries(rendered.invalid)) {
|
||||
if (rendered.missing.includes(name)) continue;
|
||||
// The target follows from a missing value; the hint above already covers it.
|
||||
if (name === "host" && unresolvedHost && rendered.missing.length) continue;
|
||||
problems.push(`${name}: ${error}`);
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
export function StepCard({
|
||||
step,
|
||||
rendered,
|
||||
@@ -47,56 +61,47 @@ export function StepCard({
|
||||
connected?: boolean;
|
||||
onArtifactState?(runId: string, name: string, state: DownloadState): void;
|
||||
}) {
|
||||
const [notice, setNotice] = useState("");
|
||||
const invalid =
|
||||
rendered.missing.length > 0 || Object.keys(rendered.invalid).length > 0;
|
||||
const problems = stepProblems(rendered);
|
||||
const invalid = problems.length > 0;
|
||||
const busy = run?.status === "running" || run?.status === "hostKey";
|
||||
async function copy(ssh: boolean) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(
|
||||
ssh && host
|
||||
? sshCommand(host, rendered.script, step.attrs.sudo)
|
||||
: rendered.script,
|
||||
);
|
||||
setNotice("Copied");
|
||||
} catch {
|
||||
setNotice("Copy failed. Select and copy the script manually.");
|
||||
}
|
||||
}
|
||||
const target = rendered.local
|
||||
? "ShellBook server"
|
||||
: rendered.host && !rendered.host.includes("{{")
|
||||
? host
|
||||
? `${host.user}@${host.name}`
|
||||
: rendered.host
|
||||
: "no host selected";
|
||||
return (
|
||||
<article
|
||||
className={`step ${run?.status ?? ""}`}
|
||||
className={`step ${step.kind} ${run?.status ?? ""}`}
|
||||
aria-label={step.attrs.title ?? step.attrs.id}
|
||||
>
|
||||
<header>
|
||||
<span className="badge">{step.kind}</span>
|
||||
<span className={`badge kind-${step.kind}`}>{step.kind}</span>
|
||||
<h3>{step.attrs.title ?? step.attrs.id}</h3>
|
||||
<span className="target">
|
||||
{rendered.local
|
||||
? "local · ShellBook server"
|
||||
: (rendered.host ?? "No host selected")}
|
||||
</span>
|
||||
{step.attrs.sudo && <span className="badge">sudo</span>}
|
||||
{(step.attrs.confirm ||
|
||||
(step.kind === "run" && host?.tags.includes("prod"))) && (
|
||||
<span className="badge">confirm</span>
|
||||
<span className="badge warn">confirm</span>
|
||||
)}
|
||||
<span className={`target ${host || rendered.local ? "" : "unset"}`} title="Runs on">
|
||||
→ {target}
|
||||
</span>
|
||||
</header>
|
||||
<Script script={rendered.script} />
|
||||
{invalid && (
|
||||
<p className="error" role="status">
|
||||
{rendered.missing.length > 0 &&
|
||||
`Missing: ${rendered.missing.join(", ")}. `}
|
||||
{Object.entries(rendered.invalid)
|
||||
.map(([name, error]) => `${name}: ${error}`)
|
||||
.join("; ")}
|
||||
<p className="hint" role="status">
|
||||
{problems.join(" ")}
|
||||
</p>
|
||||
)}
|
||||
<div className="actions">
|
||||
<button onClick={() => void copy(false)}>Copy</button>
|
||||
<button disabled={!host || invalid} onClick={() => void copy(true)}>
|
||||
Copy as ssh one-liner
|
||||
</button>
|
||||
<CopyButton text={() => rendered.script} />
|
||||
<CopyButton
|
||||
label="Copy ssh command"
|
||||
title="An ssh one-liner for your own terminal"
|
||||
disabled={!host || invalid}
|
||||
text={() => sshCommand(host!, rendered.script, step.attrs.sudo)}
|
||||
/>
|
||||
<span className="spacer" />
|
||||
<button
|
||||
className="primary"
|
||||
@@ -106,10 +111,9 @@ export function StepCard({
|
||||
{busy ? "Running…" : step.kind === "check" ? "Check" : "Run"}
|
||||
</button>
|
||||
</div>
|
||||
{notice && <small role="status">{notice}</small>}
|
||||
{run && (
|
||||
<section className="result" aria-label="Run output">
|
||||
<div role="status">
|
||||
<div role="status" className="result-status">
|
||||
{run.status === "success"
|
||||
? "✅ Succeeded"
|
||||
: run.status === "failure"
|
||||
|
||||
@@ -9,8 +9,10 @@ import type { TerminalClientMessage } from "@shellbook/core";
|
||||
export function TerminalSlot({
|
||||
collapsed = false,
|
||||
connect = terminalTransport,
|
||||
onClose,
|
||||
}: {
|
||||
collapsed?: boolean;
|
||||
onClose?: () => void;
|
||||
connect?: (session: string) => TerminalTransport;
|
||||
}) {
|
||||
const container = useRef<HTMLDivElement>(null);
|
||||
@@ -105,18 +107,26 @@ export function TerminalSlot({
|
||||
if (!collapsed) refit.current();
|
||||
}, [collapsed]);
|
||||
return (
|
||||
<aside className="terminal" aria-label="Terminal panel" hidden={collapsed}>
|
||||
<h2>Terminal · main</h2>
|
||||
<p>
|
||||
Run `claude` here — it edits notebooks in this workspace; the view
|
||||
reloads live.
|
||||
</p>
|
||||
<div className="actions">
|
||||
<span role="status">{state}</span>
|
||||
<aside className="terminal side-panel" aria-label="Terminal panel" hidden={collapsed}>
|
||||
<header className="panel-header">
|
||||
<h2>Terminal</h2>
|
||||
<span role="status" className={`dot-status ${state === "Connected" ? "ok" : state === "Disconnected" ? "bad" : ""}`}>
|
||||
{state}
|
||||
</span>
|
||||
{state === "Disconnected" && (
|
||||
<button onClick={() => setAttempt((n) => n + 1)}>Reconnect</button>
|
||||
)}
|
||||
</div>
|
||||
<span className="spacer" />
|
||||
{onClose && (
|
||||
<button className="icon" aria-label="Close terminal" onClick={onClose}>
|
||||
×
|
||||
</button>
|
||||
)}
|
||||
</header>
|
||||
<p className="muted">
|
||||
tmux session “main” on the ShellBook server. Run <code>claude</code>{" "}
|
||||
here; notebook edits show up live.
|
||||
</p>
|
||||
<div className="terminal-screen" ref={container} />
|
||||
</aside>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import type { UpdateCheckResponse, UpdateStatusResponse } from "@shellbook/core";
|
||||
import { settingsApi } from "./settingsApi";
|
||||
import { Dialog } from "./ui";
|
||||
|
||||
type UpdateApi = Pick<typeof settingsApi, "updateStatus" | "checkUpdate" | "startUpdate">;
|
||||
|
||||
/** How long a requested update may take to show up in systemd before we say so. */
|
||||
const START_TIMEOUT_MS = 30_000;
|
||||
/** systemd timestamps have second resolution; allow for that and small clock steps. */
|
||||
const START_SLACK_MS = 5_000;
|
||||
|
||||
type Watch =
|
||||
| { phase: "starting" | "running" | "restarting"; since: number }
|
||||
| { phase: "done" | "failed" | "stalled" };
|
||||
|
||||
const when = (iso: string | null) => (iso ? new Date(iso).toLocaleString() : "");
|
||||
|
||||
/**
|
||||
* Settings card that starts ShellBook's own update. The server only requests it; systemd
|
||||
* runs the updater as root and restarts the service, so this card keeps polling through
|
||||
* the restart and then offers a reload for the new web app.
|
||||
*/
|
||||
export function UpdatePanel({ api = settingsApi, pollMs = 2000 }: { api?: UpdateApi; pollMs?: number }) {
|
||||
const [status, setStatus] = useState<UpdateStatusResponse | "error">();
|
||||
const [check, setCheck] = useState<UpdateCheckResponse | "checking" | "error">();
|
||||
const [watch, setWatch] = useState<Watch>();
|
||||
const [confirming, setConfirming] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const logRef = useRef<HTMLPreElement>(null);
|
||||
|
||||
// Initial load; an update already running (e.g. after a reload) is followed as well.
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
api.updateStatus().then(
|
||||
(next) => {
|
||||
if (!active) return;
|
||||
setStatus(next);
|
||||
if (next.state === "running") setWatch({ phase: "running", since: Date.parse(next.startedAt ?? "") || Date.now() });
|
||||
},
|
||||
() => active && setStatus("error"),
|
||||
);
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [api]);
|
||||
|
||||
const following = watch && (watch.phase === "starting" || watch.phase === "running" || watch.phase === "restarting");
|
||||
const since = watch && "since" in watch ? watch.since : 0;
|
||||
const poll = useCallback(async () => {
|
||||
let next: UpdateStatusResponse;
|
||||
try {
|
||||
next = await api.updateStatus();
|
||||
} catch {
|
||||
// The update restarts ShellBook; the API is gone for a moment.
|
||||
setWatch((current) => (current && "since" in current ? { ...current, phase: "restarting" } : current));
|
||||
return;
|
||||
}
|
||||
setStatus(next);
|
||||
const started = next.startedAt !== null && Date.parse(next.startedAt) >= since - START_SLACK_MS;
|
||||
if (next.state === "running") setWatch({ phase: "running", since });
|
||||
else if (!started)
|
||||
setWatch(Date.now() - since > START_TIMEOUT_MS ? { phase: "stalled" } : { phase: "starting", since });
|
||||
else setWatch({ phase: next.state === "succeeded" ? "done" : "failed" });
|
||||
}, [api, since]);
|
||||
useEffect(() => {
|
||||
if (!following) return;
|
||||
const timer = setInterval(() => void poll(), pollMs);
|
||||
return () => clearInterval(timer);
|
||||
}, [following, poll, pollMs]);
|
||||
|
||||
// Keep the newest log lines in view while an update runs.
|
||||
const log = status && status !== "error" ? status.log : "";
|
||||
useEffect(() => {
|
||||
if (following && logRef.current) logRef.current.scrollTop = logRef.current.scrollHeight;
|
||||
}, [log, following]);
|
||||
|
||||
const start = async () => {
|
||||
setConfirming(false);
|
||||
setError("");
|
||||
try {
|
||||
const { requestedAt } = await api.startUpdate();
|
||||
setWatch({ phase: "starting", since: Date.parse(requestedAt) });
|
||||
} catch {
|
||||
setError("Unable to start the update. It may already be running; reload this page.");
|
||||
}
|
||||
};
|
||||
|
||||
if (status === undefined)
|
||||
return (
|
||||
<section className="card">
|
||||
<h2>Updates</h2>
|
||||
<p className="muted">Loading…</p>
|
||||
</section>
|
||||
);
|
||||
if (status === "error")
|
||||
return (
|
||||
<section className="card">
|
||||
<h2>Updates</h2>
|
||||
<p className="error">Unable to load the update status.</p>
|
||||
</section>
|
||||
);
|
||||
|
||||
return (
|
||||
<section className="card update-panel" aria-label="Updates">
|
||||
<h2>Updates</h2>
|
||||
<dl className="facts">
|
||||
<dt>Installed</dt>
|
||||
<dd>{status.current ? <code>{status.current}</code> : "unknown (not a git checkout)"}</dd>
|
||||
{status.available && status.startedAt && !following && (
|
||||
<>
|
||||
<dt>Last update</dt>
|
||||
<dd>
|
||||
{status.state === "failed" ? "failed" : status.state === "succeeded" ? "succeeded" : status.state},{" "}
|
||||
{when(status.finishedAt ?? status.startedAt)}
|
||||
</dd>
|
||||
</>
|
||||
)}
|
||||
</dl>
|
||||
{!status.available ? (
|
||||
<p className="muted">
|
||||
Updating from the web UI is not set up on this installation. Run <code>shellbook-update</code> as root in the
|
||||
container (from the Proxmox host: <code>pct exec <ctid> -- shellbook-update</code>); that run also
|
||||
adds the button here.
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
{watch && (
|
||||
<p role="status" className={`banner${watch.phase === "failed" || watch.phase === "stalled" ? " error" : ""}`}>
|
||||
{watch.phase === "starting" && "Starting the update…"}
|
||||
{watch.phase === "running" && "Updating… This takes a few minutes; ShellBook restarts at the end."}
|
||||
{watch.phase === "restarting" && "ShellBook is restarting…"}
|
||||
{watch.phase === "done" && (
|
||||
<>
|
||||
Update finished{status.current ? ` (${status.current})` : ""}. Reload to use the new version.
|
||||
<button className="primary" onClick={() => location.reload()}>
|
||||
Reload
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{watch.phase === "failed" && "The update failed. The log below shows why."}
|
||||
{watch.phase === "stalled" &&
|
||||
"The update did not start. Check systemctl status shellbook-update.path in the container."}
|
||||
</p>
|
||||
)}
|
||||
{error && <p className="banner error">{error}</p>}
|
||||
{check === "error" && <p className="error">Unable to reach the repository.</p>}
|
||||
{check && check !== "checking" && check !== "error" && (
|
||||
check.pinned ? (
|
||||
<p className="muted">This installation is pinned to a fixed version and is not updated from the branch.</p>
|
||||
) : check.changes.length === 0 ? (
|
||||
<p className="ok">Up to date{check.latest ? ` (${check.latest})` : ""}.</p>
|
||||
) : (
|
||||
<div>
|
||||
<p>
|
||||
{check.changes.length === 1 ? "1 new change" : `${check.changes.length} new changes`} (
|
||||
<code>{check.current}</code> → <code>{check.latest}</code>):
|
||||
</p>
|
||||
<ul className="changes">
|
||||
{check.changes.map((change) => (
|
||||
<li key={change.commit}>
|
||||
<code>{change.commit}</code> {change.subject}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
<div className="actions">
|
||||
<button
|
||||
disabled={following || check === "checking"}
|
||||
onClick={() => {
|
||||
setCheck("checking");
|
||||
api.checkUpdate().then(setCheck, () => setCheck("error"));
|
||||
}}
|
||||
>
|
||||
{check === "checking" ? "Checking…" : "Check for updates"}
|
||||
</button>
|
||||
<button className="primary" disabled={following} onClick={() => setConfirming(true)}>
|
||||
Update now
|
||||
</button>
|
||||
</div>
|
||||
{status.log && (following || watch?.phase === "failed" || watch?.phase === "done" || !watch) && (
|
||||
<details open={following || watch?.phase === "failed"}>
|
||||
<summary>{following ? "Update output" : "Output of the last update"}</summary>
|
||||
<pre ref={logRef} className="update-log">
|
||||
{status.log}
|
||||
</pre>
|
||||
</details>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{confirming && (
|
||||
<Dialog title="Update ShellBook?" onClose={() => setConfirming(false)}>
|
||||
<p>
|
||||
Downloads the installer from the repository, pulls the newest version, rebuilds and restarts ShellBook. Running
|
||||
steps are interrupted by the restart; terminal sessions keep running.
|
||||
</p>
|
||||
<div className="dialog-actions">
|
||||
<button onClick={() => setConfirming(false)}>Cancel</button>
|
||||
<button className="primary" onClick={() => void start()}>
|
||||
Update now
|
||||
</button>
|
||||
</div>
|
||||
</Dialog>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
+48
-4
@@ -1,4 +1,7 @@
|
||||
import type {
|
||||
HostInfo,
|
||||
HostInventoryResponse,
|
||||
SaveHostRequest,
|
||||
NotebookListResponse,
|
||||
HostsResponse,
|
||||
NotebookResponse,
|
||||
@@ -9,11 +12,24 @@ import type {
|
||||
} from "@shellbook/core";
|
||||
|
||||
export class HttpError extends Error {
|
||||
constructor(public status: number) {
|
||||
super(`Request failed (${status})`);
|
||||
constructor(
|
||||
public status: number,
|
||||
serverMessage?: string,
|
||||
) {
|
||||
super(serverMessage || `Request failed (${status})`);
|
||||
}
|
||||
}
|
||||
async function json<T>(
|
||||
/** Deliberate errors (4xx, 502, 503) carry a user-facing `message`; unexpected 500s may expose internals. */
|
||||
async function serverMessage(response: Response): Promise<string | undefined> {
|
||||
if (response.status === 500) return undefined;
|
||||
try {
|
||||
const body = (await response.json()) as { message?: unknown };
|
||||
return typeof body.message === "string" ? body.message.slice(0, 500) : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
export async function json<T>(
|
||||
path: string,
|
||||
method = "GET",
|
||||
body?: unknown,
|
||||
@@ -24,12 +40,24 @@ async function json<T>(
|
||||
headers: body === undefined ? {} : { "Content-Type": "application/json" },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
});
|
||||
if (!response.ok) throw new HttpError(response.status);
|
||||
if (!response.ok)
|
||||
throw new HttpError(response.status, await serverMessage(response));
|
||||
return response.status === 204
|
||||
? (undefined as T)
|
||||
: (response.json() as Promise<T>);
|
||||
}
|
||||
export interface Api {
|
||||
create(
|
||||
path: string,
|
||||
source: string,
|
||||
): Promise<{ path: string; version: string }>;
|
||||
move(
|
||||
path: string,
|
||||
target: string,
|
||||
baseVersion: string,
|
||||
duplicate?: boolean,
|
||||
): Promise<{ path: string; version: string }>;
|
||||
deleteNotebook(path: string, baseVersion: string): Promise<unknown>;
|
||||
me(): Promise<unknown>;
|
||||
login(password: string): Promise<unknown>;
|
||||
list(): Promise<NotebookListResponse>;
|
||||
@@ -41,6 +69,8 @@ export interface Api {
|
||||
baseVersion: string,
|
||||
): Promise<SaveNotebookResponse>;
|
||||
run(request: StartRunRequest): Promise<StartRunResponse>;
|
||||
/** Add a host to the inventory (a notebook's `::host` block); 409 if the name is taken. */
|
||||
addHost(host: HostInfo): Promise<void>;
|
||||
events(
|
||||
receive: (event: ServerEvent) => void,
|
||||
connection: (connected: boolean) => void,
|
||||
@@ -48,6 +78,15 @@ export interface Api {
|
||||
artifact(runId: string, name: string): string;
|
||||
}
|
||||
export const liveApi: Api = {
|
||||
create: (path, source) => json("/notebooks", "POST", { path, source }),
|
||||
move: (path, target, baseVersion, duplicate = false) =>
|
||||
json(
|
||||
`/notebooks/${encodeURIComponent(path)}/${duplicate ? "duplicate" : "rename"}`,
|
||||
"POST",
|
||||
{ path: target, baseVersion },
|
||||
),
|
||||
deleteNotebook: (path, baseVersion) =>
|
||||
json(`/notebooks/${encodeURIComponent(path)}`, "DELETE", { baseVersion }),
|
||||
me: () => json("/auth/me"),
|
||||
login: (password) => json("/auth/login", "POST", { password }),
|
||||
list: () => json("/notebooks"),
|
||||
@@ -59,6 +98,11 @@ export const liveApi: Api = {
|
||||
baseVersion,
|
||||
}),
|
||||
run: (request) => json("/runs", "POST", request),
|
||||
async addHost(host) {
|
||||
const { version } = await json<HostInventoryResponse>("/host-management");
|
||||
const request: SaveHostRequest = { host, baseVersion: version };
|
||||
await json("/host-management", "POST", request);
|
||||
},
|
||||
artifact: (id, name) =>
|
||||
`/api/runs/${encodeURIComponent(id)}/artifacts/${encodeURIComponent(name)}`,
|
||||
events(receive, connection) {
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import { isMap, parseDocument } from "yaml";
|
||||
import {
|
||||
includePath,
|
||||
parseNotebook,
|
||||
type Block,
|
||||
type ParamDef,
|
||||
type Step,
|
||||
} from "@shellbook/core";
|
||||
export function notebookSteps(blocks: Block[]): Step[] {
|
||||
return blocks.flatMap((b) =>
|
||||
b.type === "step" ? [b.step] : "blocks" in b ? notebookSteps(b.blocks) : [],
|
||||
);
|
||||
}
|
||||
const attr = (value: string) =>
|
||||
'"' +
|
||||
value
|
||||
.replace(/\\/g, "\\\\")
|
||||
.replace(/"/g, '\\"')
|
||||
.replace(/[\r\n]/g, " ") +
|
||||
'"';
|
||||
export type InsertKind =
|
||||
| "Check step"
|
||||
| "Run step"
|
||||
| "Artifacts"
|
||||
| "Upload"
|
||||
| "Capture";
|
||||
export function stepSnippet(
|
||||
source: string,
|
||||
kind: InsertKind,
|
||||
local: boolean,
|
||||
host = "host",
|
||||
): string {
|
||||
const ids = new Set(
|
||||
notebookSteps(parseNotebook(source).blocks).map((s) => s.attrs.id),
|
||||
);
|
||||
let n = 1;
|
||||
while (ids.has(`step-${n}`)) n++;
|
||||
const check = kind === "Check step" || kind === "Capture";
|
||||
const extra =
|
||||
kind === "Artifacts"
|
||||
? ' artifacts="result.txt"'
|
||||
: kind === "Upload"
|
||||
? ' upload="result.txt:/tmp/result.txt"'
|
||||
: kind === "Capture"
|
||||
? " capture=result"
|
||||
: "";
|
||||
const script =
|
||||
kind === "Artifacts"
|
||||
? "printf '%s\\n' 'Example result' > result.txt"
|
||||
: kind === "Upload"
|
||||
? "# Use the uploaded /tmp/result.txt here\n:"
|
||||
: check
|
||||
? "uname -s"
|
||||
: "# Replace with your command\n:";
|
||||
return `\n\n\`\`\`sh {${check ? "check" : "run"} ${local ? "on=local" : `host=${attr(`{{${host}}}`)}`} id=step-${n} title=${attr(kind)}${check ? "" : " confirm"}${extra}}\n${script}\n\`\`\`\n`;
|
||||
}
|
||||
export function afterSnippet(id: string): string {
|
||||
return `\n\n:::after{step=${attr(id)}}\nAdd follow-up instructions here.\n:::\n`;
|
||||
}
|
||||
/** A section shown (and runnable) only while a choice parameter has this value. */
|
||||
export function whenSnippet(param: string, value: string): string {
|
||||
return `\n\n:::when{${param}=${attr(value)}}\nShown only when ${param} is ${value.replace(/[\r\n]/g, " ")}.\n:::\n`;
|
||||
}
|
||||
/** Include another notebook; its parameters and steps are namespaced as alias.name. */
|
||||
export function useSnippet(path: string, alias: string): string {
|
||||
if (!includePath(path)) throw new Error("Notebook path must be dir/name.md relative to notebooks/");
|
||||
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(alias) || alias === "shellbook")
|
||||
throw new Error("Alias must use letters, digits or _ (not shellbook)");
|
||||
return `\n\n::use{notebook=${attr(path)} as=${alias}}\n`;
|
||||
}
|
||||
/** A titled, collapsible container; its outline shows whether its inputs are filled in. */
|
||||
export function groupSnippet(title = "Group title"): string {
|
||||
return `
|
||||
|
||||
:::group{title=${attr(title)}}
|
||||
Explain this part here.
|
||||
:::
|
||||
`;
|
||||
}
|
||||
/** The parameter's input field at this point of the text. */
|
||||
export function paramFieldSnippet(name: string): string {
|
||||
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new Error("Invalid parameter name");
|
||||
return `
|
||||
|
||||
::param{name=${name}}
|
||||
`;
|
||||
}
|
||||
/** Add the machine a notebook created to Hosts; replace the example templates. */
|
||||
export function hostSnippet(): string {
|
||||
return '\n\n::host{name="{{hostname}}" address="{{address}}" user=root port=22 capture=host}\n';
|
||||
}
|
||||
export function addParameter(source: string, def: ParamDef): string {
|
||||
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(def.name))
|
||||
throw new Error("Invalid parameter name");
|
||||
const match =
|
||||
/^(?:\uFEFF)?---\r?\n([\s\S]*?)\r?\n(?:---|\.\.\.)[^\S\r\n]*(?:\r?\n|$)/.exec(
|
||||
source,
|
||||
);
|
||||
const doc = parseDocument(match?.[1] ?? "{}");
|
||||
if (doc.errors.length || !isMap(doc.contents))
|
||||
throw new Error("Fix frontmatter YAML first");
|
||||
if (doc.hasIn(["params", def.name]))
|
||||
throw new Error("Parameter already exists");
|
||||
if (doc.has("params") && !isMap(doc.get("params", true)))
|
||||
throw new Error("params must be a mapping");
|
||||
if (!doc.has("params")) doc.set("params", doc.createNode({}));
|
||||
const { name, ...fields } = def;
|
||||
if (def.type === "secret" && def.default !== undefined)
|
||||
throw new Error("Secrets cannot have defaults");
|
||||
doc.setIn(["params", name], doc.createNode(fields));
|
||||
const next = `---\n${doc.toString()}---\n${match ? source.slice(match[0].length) : source}`;
|
||||
const errors = parseNotebook(next).diagnostics;
|
||||
if (errors.length) throw new Error(errors.map((d) => d.message).join("; "));
|
||||
return next;
|
||||
}
|
||||
export function newNotebook(title: string): string {
|
||||
const doc = parseDocument("{}");
|
||||
doc.set("title", title.trim() || "New notebook");
|
||||
doc.set(
|
||||
"params",
|
||||
doc.createNode({
|
||||
host: { type: "host", required: true, label: "Target server" },
|
||||
}),
|
||||
);
|
||||
let source = `---\n${doc.toString()}---\n\n# ${title.replace(/[\r\n]/g, " ").trim() || "New notebook"}\n`;
|
||||
source += stepSnippet(source, "Check step", false);
|
||||
return source + stepSnippet(source, "Run step", false);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
.chat-panel select,
|
||||
.chat-panel textarea {
|
||||
width: 100%;
|
||||
}
|
||||
.chat-messages {
|
||||
flex: 1;
|
||||
min-height: 120px;
|
||||
overflow-y: auto;
|
||||
overflow-wrap: anywhere;
|
||||
border-top: 1px solid var(--line);
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.chat-messages pre {
|
||||
overflow-x: auto;
|
||||
}
|
||||
.chat-message {
|
||||
padding: 0.6rem 0;
|
||||
border-bottom: 1px solid #64748b55;
|
||||
}
|
||||
.chat-message.user {
|
||||
opacity: 0.85;
|
||||
}
|
||||
.chat-panel label.chat-shell {
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
.chat-panel form {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.chat-panel form .actions {
|
||||
margin: 8px 0 0;
|
||||
}
|
||||
.chat-panel > p {
|
||||
margin: 0;
|
||||
}
|
||||
+14
-1
@@ -41,10 +41,23 @@ export type Action =
|
||||
state: DownloadState;
|
||||
}
|
||||
| ServerEvent
|
||||
| { type: "requested"; runId: string; request: StartRunRequest };
|
||||
| { type: "requested"; runId: string; request: StartRunRequest }
|
||||
/** A runtime value set in the browser, e.g. by a `::host` block's capture. */
|
||||
| { type: "runtime.set"; notebookPath: string; name: string; value: string };
|
||||
export function eventReducer(state: Session, event: Action): Session {
|
||||
if (event.type === "file.changed" || event.type === "file.deleted")
|
||||
return state;
|
||||
if (event.type === "runtime.set")
|
||||
return {
|
||||
...state,
|
||||
runtime: {
|
||||
...state.runtime,
|
||||
[event.notebookPath]: {
|
||||
...state.runtime[event.notebookPath],
|
||||
[event.name]: event.value,
|
||||
},
|
||||
},
|
||||
};
|
||||
if (event.type === "requested" || event.type === "run.started") {
|
||||
const info = event.type === "requested" ? event.request : event;
|
||||
const previous = state.runs[event.runId];
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
.host-list {
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 8px;
|
||||
background: var(--panel);
|
||||
margin: 16px 0;
|
||||
}
|
||||
.host-list .empty {
|
||||
padding: 32px 20px;
|
||||
margin: 0;
|
||||
}
|
||||
.host-row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1.3fr) minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 12px 16px;
|
||||
}
|
||||
.host-row + .host-row {
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
.host-main {
|
||||
min-width: 0;
|
||||
}
|
||||
.host-main h2 {
|
||||
font-size: 15px;
|
||||
margin: 0 0 2px;
|
||||
}
|
||||
.host-main code {
|
||||
color: var(--muted);
|
||||
font-size: 12.5px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.host-meta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
.host-row .actions {
|
||||
margin: 0;
|
||||
flex-wrap: nowrap;
|
||||
}
|
||||
.public-key pre {
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
background: var(--code);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 5px;
|
||||
padding: 10px 12px;
|
||||
font-size: 12px;
|
||||
}
|
||||
@media (max-width: 760px) {
|
||||
.host-row {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
.host-row .actions {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
}
|
||||
+50
-24
@@ -1,10 +1,19 @@
|
||||
import type { ServerEvent, StartRunRequest } from "@shellbook/core";
|
||||
import type { Api } from "../api";
|
||||
import { HttpError } from "../api";
|
||||
import { parseNotebook, renderStep } from "@shellbook/core";
|
||||
import initial from "./ssh-key.md?raw";
|
||||
let source = initial;
|
||||
let version = 1;
|
||||
import { findStep, parseNotebook, renderStep } from "@shellbook/core";
|
||||
import sshKey from "./ssh-key.md?raw";
|
||||
import adminUser from "../../../../templates/workspace/notebooks/admin-user.md?raw";
|
||||
// Demo notebooks, editable in this browser session only.
|
||||
const files: Record<string, { title: string; source: string; version: number }> = {
|
||||
"ssh-key.md": { title: "New server SSH key", source: sshKey, version: 1 },
|
||||
"admin-user.md": { title: "Create an admin user", source: adminUser, version: 1 },
|
||||
};
|
||||
const file = (path: string) => {
|
||||
const entry = files[path];
|
||||
if (!entry) throw new HttpError(404);
|
||||
return entry;
|
||||
};
|
||||
let counter = 0;
|
||||
const listeners = new Set<(event: ServerEvent) => void>();
|
||||
const emit = (event: ServerEvent) =>
|
||||
@@ -31,23 +40,42 @@ const artifactUrl = URL.createObjectURL(
|
||||
}),
|
||||
);
|
||||
export const mockApi: Api = {
|
||||
create: async () => {
|
||||
throw new Error("Notebook management requires a live workspace");
|
||||
},
|
||||
move: async () => {
|
||||
throw new Error("Notebook management requires a live workspace");
|
||||
},
|
||||
deleteNotebook: async () => {
|
||||
throw new Error("Notebook management requires a live workspace");
|
||||
},
|
||||
me: async () => ({ authenticated: true }),
|
||||
login: async () => undefined,
|
||||
list: async () => ({
|
||||
notebooks: [{ path: "ssh-key.md", title: "New server SSH key" }],
|
||||
notebooks: Object.entries(files).map(([path, entry]) => ({ path, title: entry.title })),
|
||||
}),
|
||||
hosts: async () => ({ hosts }),
|
||||
notebook: async (path) => ({
|
||||
path,
|
||||
source,
|
||||
notebook: parseNotebook(source),
|
||||
version: String(version),
|
||||
}),
|
||||
save: async (_path, next, base) => {
|
||||
if (base !== String(version)) throw new HttpError(409);
|
||||
source = next;
|
||||
version++;
|
||||
return { version: String(version) };
|
||||
notebook: async (path) => {
|
||||
const { source, version } = file(path);
|
||||
return {
|
||||
path,
|
||||
source,
|
||||
notebook: parseNotebook(source),
|
||||
includes: [],
|
||||
builtins: { "shellbook.public_key": "ssh-ed25519 AAAADEMO shellbook" },
|
||||
version: String(version),
|
||||
};
|
||||
},
|
||||
addHost: async (host) => {
|
||||
if (hosts.some((h) => h.name === host.name)) throw new HttpError(409, "Host already exists");
|
||||
hosts.push({ ...host });
|
||||
},
|
||||
save: async (path, next, base) => {
|
||||
const entry = file(path);
|
||||
if (base !== String(entry.version)) throw new HttpError(409);
|
||||
entry.source = next;
|
||||
entry.version++;
|
||||
return { version: String(entry.version) };
|
||||
},
|
||||
events: (receive, connected) => {
|
||||
listeners.add(receive);
|
||||
@@ -58,14 +86,12 @@ export const mockApi: Api = {
|
||||
},
|
||||
artifact: () => artifactUrl,
|
||||
run: async (request: StartRunRequest) => {
|
||||
const notebook = parseNotebook(source);
|
||||
const block = notebook.blocks.find(
|
||||
(b) => b.type === "step" && b.step.attrs.id === request.stepId,
|
||||
);
|
||||
if (!block || block.type !== "step") throw new Error("Unknown demo step");
|
||||
const notebook = parseNotebook(file(request.notebookPath).source);
|
||||
const step = findStep(notebook.blocks, request.stepId);
|
||||
if (!step) throw new Error("Unknown demo step");
|
||||
const rendered = renderStep(
|
||||
notebook,
|
||||
block.step,
|
||||
step,
|
||||
request.params,
|
||||
request.runtime,
|
||||
hosts.map((h) => h.name),
|
||||
@@ -116,8 +142,8 @@ export const mockApi: Api = {
|
||||
request.stepId === "keygen"
|
||||
? rendered.artifacts.filter((name) => !name.endsWith(".pub"))
|
||||
: [],
|
||||
captured: block.step.attrs.capture
|
||||
? { name: block.step.attrs.capture, value: "demo-value" }
|
||||
captured: step.attrs.capture
|
||||
? { name: step.attrs.capture, value: "demo-value" }
|
||||
: undefined,
|
||||
});
|
||||
}, 850);
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/* Authoring toolbar above the Markdown editor. */
|
||||
.authoring {
|
||||
display: flex;
|
||||
align-items: end;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
margin: 0.75rem 0;
|
||||
}
|
||||
.authoring label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
font-size: 12px;
|
||||
}
|
||||
.authoring form,
|
||||
.authoring details {
|
||||
flex-basis: 100%;
|
||||
}
|
||||
.authoring input,
|
||||
.authoring select {
|
||||
width: auto;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { Notebook, ParamValues } from "@shellbook/core";
|
||||
|
||||
/**
|
||||
* Remembers the parameter values typed for a notebook in this browser, so a reload or a
|
||||
* return visit keeps them. Secrets are never stored, and only declared params are kept.
|
||||
*/
|
||||
const key = (path: string) => `shellbook:params:${path}`;
|
||||
|
||||
function storable(notebook: Notebook, values: ParamValues): ParamValues {
|
||||
const kept: ParamValues = {};
|
||||
for (const def of notebook.params) {
|
||||
const value = Object.hasOwn(values, def.name) ? values[def.name] : undefined;
|
||||
if (def.type !== "secret" && value) kept[def.name] = value;
|
||||
}
|
||||
return kept;
|
||||
}
|
||||
|
||||
export function recallValues(path: string, notebook: Notebook): ParamValues {
|
||||
try {
|
||||
const stored: unknown = JSON.parse(localStorage.getItem(key(path)) ?? "{}");
|
||||
if (!stored || typeof stored !== "object" || Array.isArray(stored)) return {};
|
||||
const strings = Object.fromEntries(
|
||||
Object.entries(stored).filter((entry): entry is [string, string] => typeof entry[1] === "string"),
|
||||
);
|
||||
return storable(notebook, strings);
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export function rememberValues(path: string, notebook: Notebook, values: ParamValues): void {
|
||||
try {
|
||||
const kept = storable(notebook, values);
|
||||
if (Object.keys(kept).length) localStorage.setItem(key(path), JSON.stringify(kept));
|
||||
else localStorage.removeItem(key(path));
|
||||
} catch {
|
||||
// Storage may be unavailable (private mode); values then last for this page only.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { NavigationPage } from "./HeaderNavigation";
|
||||
|
||||
/** The page and open notebook, kept in the URL hash so reloads and links keep them. */
|
||||
export interface Route {
|
||||
page: NavigationPage;
|
||||
notebook?: string;
|
||||
}
|
||||
|
||||
const pages: Record<string, NavigationPage> = {
|
||||
notebooks: "Notebooks",
|
||||
hosts: "Hosts",
|
||||
settings: "Settings",
|
||||
};
|
||||
|
||||
export function parseRoute(hash: string): Route {
|
||||
const [, page = "", ...rest] = hash.replace(/^#/, "").split("/");
|
||||
const known = pages[page];
|
||||
if (!known) return { page: "Notebooks" };
|
||||
if (known !== "Notebooks" || !rest.length) return { page: known };
|
||||
try {
|
||||
const notebook = rest.map(decodeURIComponent).join("/");
|
||||
return notebook ? { page: known, notebook } : { page: known };
|
||||
} catch {
|
||||
return { page: known };
|
||||
}
|
||||
}
|
||||
|
||||
export function routeHash(route: Route): string {
|
||||
const page = route.page.toLowerCase();
|
||||
return route.page === "Notebooks" && route.notebook
|
||||
? `#/${page}/${route.notebook.split("/").map(encodeURIComponent).join("/")}`
|
||||
: `#/${page}`;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import type {
|
||||
SetupStatusResponse,
|
||||
SetupRequest,
|
||||
ChangePasswordRequest,
|
||||
SessionSettingsResponse,
|
||||
ClaudeStatusResponse,
|
||||
SystemInfoResponse,
|
||||
UpdateCheckResponse,
|
||||
UpdateStartResponse,
|
||||
UpdateStatusResponse,
|
||||
} from "@shellbook/core";
|
||||
import { HttpError } from "./api";
|
||||
async function request<T>(path: string, body?: unknown): Promise<T> {
|
||||
const response = await fetch(`/api${path}`, {
|
||||
method: body === undefined ? "GET" : "POST",
|
||||
credentials: "same-origin",
|
||||
headers: body === undefined ? {} : { "Content-Type": "application/json" },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
});
|
||||
if (!response.ok) throw new HttpError(response.status);
|
||||
return response.status === 204
|
||||
? (undefined as T)
|
||||
: (response.json() as Promise<T>);
|
||||
}
|
||||
export const settingsApi = {
|
||||
setupStatus: () => request<SetupStatusResponse>("/auth/setup"),
|
||||
setup: (body: SetupRequest) => request<void>("/auth/setup", body),
|
||||
password: (body: ChangePasswordRequest) =>
|
||||
request<void>("/settings/password", body),
|
||||
revoke: () => request<void>("/settings/sessions/revoke", {}),
|
||||
logout: () => request<void>("/auth/logout", {}),
|
||||
session: () => request<SessionSettingsResponse>("/settings/session"),
|
||||
claude: () => request<ClaudeStatusResponse>("/settings/claude"),
|
||||
system: () => request<SystemInfoResponse>("/settings/system"),
|
||||
updateStatus: () => request<UpdateStatusResponse>("/settings/update"),
|
||||
checkUpdate: () => request<UpdateCheckResponse>("/settings/update/check", {}),
|
||||
startUpdate: () => request<UpdateStartResponse>("/settings/update", {}),
|
||||
};
|
||||
+1116
-423
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,18 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { HttpError, json } from "../api";
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
it("keeps the server's error message and status", async () => {
|
||||
vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ statusCode: 502, error: "Bad Gateway", message: "SSH authentication failed: check the user and the saved password or key" }), { status: 502, headers: { "Content-Type": "application/json" } })));
|
||||
const error = (await json("/x").catch((e: HttpError) => e)) as HttpError;
|
||||
expect(error).toBeInstanceOf(HttpError);
|
||||
expect(error.status).toBe(502);
|
||||
expect(error.message).toBe("SSH authentication failed: check the user and the saved password or key");
|
||||
});
|
||||
it("falls back to the status when the body is not JSON", async () => {
|
||||
vi.stubGlobal("fetch", vi.fn(async () => new Response("<html>", { status: 500 })));
|
||||
expect(((await json("/x").catch((e: HttpError) => e)) as HttpError).message).toBe("Request failed (500)");
|
||||
});
|
||||
it("does not surface messages of unexpected server errors", async () => {
|
||||
vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ statusCode: 500, message: "EACCES: permission denied, open '/var/lib/shellbook/x'" }), { status: 500 })));
|
||||
expect(((await json("/x").catch((e: HttpError) => e)) as HttpError).message).toBe("Request failed (500)");
|
||||
});
|
||||
@@ -33,6 +33,15 @@ function harness() {
|
||||
let receive: (event: ServerEvent) => void = () => {};
|
||||
let id = 0;
|
||||
const api: Api = {
|
||||
create: async () => {
|
||||
throw new Error("Notebook management requires a live workspace");
|
||||
},
|
||||
move: async () => {
|
||||
throw new Error("Notebook management requires a live workspace");
|
||||
},
|
||||
deleteNotebook: async () => {
|
||||
throw new Error("Notebook management requires a live workspace");
|
||||
},
|
||||
me: vi.fn().mockResolvedValue({}),
|
||||
login: vi.fn().mockResolvedValue(undefined),
|
||||
list: vi.fn().mockResolvedValue({
|
||||
@@ -53,9 +62,12 @@ function harness() {
|
||||
path: "ssh-key.md",
|
||||
source,
|
||||
notebook: parseNotebook(source),
|
||||
includes: [],
|
||||
builtins: {},
|
||||
version: "1",
|
||||
}),
|
||||
save: vi.fn().mockResolvedValue({ version: "2" }),
|
||||
addHost: vi.fn().mockResolvedValue(undefined),
|
||||
run: vi.fn(async (_request: StartRunRequest) => ({ runId: String(++id) })),
|
||||
events: (callback, connected) => {
|
||||
receive = callback;
|
||||
@@ -206,6 +218,8 @@ it("retains edits made while a file reload is in flight", async () => {
|
||||
path: "ssh-key.md",
|
||||
source,
|
||||
notebook: parseNotebook(source),
|
||||
includes: [],
|
||||
builtins: {},
|
||||
version: "2",
|
||||
}),
|
||||
);
|
||||
@@ -238,6 +252,8 @@ Key generation failed. Retry safely.
|
||||
path: "ssh-key.md",
|
||||
source: captureSource,
|
||||
notebook: parseNotebook(captureSource),
|
||||
includes: [],
|
||||
builtins: {},
|
||||
version: "1",
|
||||
});
|
||||
await ready(api);
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { parseNotebook } from "@shellbook/core";
|
||||
import { parse } from "yaml";
|
||||
import {
|
||||
addParameter,
|
||||
afterSnippet,
|
||||
newNotebook,
|
||||
notebookSteps,
|
||||
stepSnippet,
|
||||
type InsertKind,
|
||||
} from "../authoring";
|
||||
it.each([
|
||||
"Check step",
|
||||
"Run step",
|
||||
"Artifacts",
|
||||
"Upload",
|
||||
"Capture",
|
||||
] as InsertKind[])(
|
||||
"generates valid %s fences for both targets and unique ids",
|
||||
(kind) => {
|
||||
for (const local of [true, false]) {
|
||||
let source = newNotebook('Title: "quoted"');
|
||||
source += stepSnippet(source, kind, local);
|
||||
source += stepSnippet(source, kind, local);
|
||||
source += afterSnippet(
|
||||
notebookSteps(parseNotebook(source).blocks)[0]!.attrs.id,
|
||||
);
|
||||
expect(parseNotebook(source).diagnostics).toEqual([]);
|
||||
expect(notebookSteps(parseNotebook(source).blocks)).toHaveLength(4);
|
||||
}
|
||||
},
|
||||
);
|
||||
it("preserves other YAML, comments, body and existing params", () => {
|
||||
const source =
|
||||
"---\n# keep comment\ntitle: Original\ncustom: {nested: [one, two]}\nparams:\n host: {type: host}\n---\n\n# Body\n";
|
||||
const next = addParameter(source, {
|
||||
name: "mode",
|
||||
type: "choice",
|
||||
required: true,
|
||||
options: ["a", "b"],
|
||||
default: "a",
|
||||
label: "Mode",
|
||||
});
|
||||
expect(parseNotebook(next).diagnostics).toEqual([]);
|
||||
expect(next).toContain("# keep comment");
|
||||
expect(next).toContain("\n\n# Body\n");
|
||||
const yaml = parse(next.split("---")[1]!);
|
||||
expect(yaml.custom).toEqual({ nested: ["one", "two"] });
|
||||
expect(yaml.params.host).toEqual({ type: "host" });
|
||||
expect(yaml.params.mode.options).toEqual(["a", "b"]);
|
||||
expect(() =>
|
||||
addParameter(next, { name: "host", type: "host", required: true }),
|
||||
).toThrow("already exists");
|
||||
});
|
||||
it("adds frontmatter when absent and rejects invalid YAML or secret defaults", () => {
|
||||
expect(
|
||||
parseNotebook(
|
||||
addParameter("# Title\n", {
|
||||
name: "token",
|
||||
type: "secret",
|
||||
required: true,
|
||||
}),
|
||||
).diagnostics,
|
||||
).toEqual([]);
|
||||
expect(() =>
|
||||
addParameter("---\nx: [\n---\n", {
|
||||
name: "a",
|
||||
type: "string",
|
||||
required: false,
|
||||
}),
|
||||
).toThrow();
|
||||
expect(() =>
|
||||
addParameter("# Title", {
|
||||
name: "token",
|
||||
type: "secret",
|
||||
required: true,
|
||||
default: "bad",
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("generates valid chaining snippets", async () => {
|
||||
const { whenSnippet, useSnippet, hostSnippet } = await import("../authoring");
|
||||
const base = "---\nparams:\n target: {type: choice, options: [existing, lxc]}\n hostname: {type: name}\n address: {type: string}\n---\n";
|
||||
const source = base + whenSnippet("target", "lxc") + useSnippet("infra/lxc-container.md", "ct") + hostSnippet();
|
||||
const notebook = parseNotebook(source);
|
||||
expect(notebook.diagnostics).toEqual([]);
|
||||
expect(notebook.blocks.map((b) => b.type).filter((t) => t !== "markdown")).toEqual(["when", "use", "host"]);
|
||||
expect(() => useSnippet("../x.md", "ct")).toThrow("dir/name.md");
|
||||
expect(() => useSnippet("x.md", "shellbook")).toThrow("Alias");
|
||||
});
|
||||
it("generates valid group and parameter field snippets", async () => {
|
||||
const { groupSnippet, paramFieldSnippet } = await import("../authoring");
|
||||
const base = "---\nparams:\n hostname: {type: name}\n---\n";
|
||||
const notebook = parseNotebook(base + groupSnippet('Say "hi"') + paramFieldSnippet("hostname"));
|
||||
expect(notebook.diagnostics).toEqual([]);
|
||||
expect(notebook.blocks.filter((b) => b.type !== "markdown")).toEqual([
|
||||
expect.objectContaining({ type: "group", title: 'Say "hi"', collapsed: false }),
|
||||
expect.objectContaining({ type: "param", name: "hostname" }),
|
||||
]);
|
||||
expect(() => paramFieldSnippet("a b")).toThrow("Invalid parameter name");
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { expect, it, vi } from "vitest";
|
||||
vi.mock("../Editor", () => ({ Editor: () => null }));
|
||||
import { App } from "../App";
|
||||
import type { Api } from "../api";
|
||||
import type { HostInfo, ServerEvent, StartRunRequest } from "@shellbook/core";
|
||||
import { composeNotebook, parseNotebook } from "@shellbook/core";
|
||||
|
||||
const lxc = `---
|
||||
title: LXC container
|
||||
params:
|
||||
proxmox: {type: host, required: true}
|
||||
hostname: {type: name, required: true}
|
||||
---
|
||||
\`\`\`sh {run host="{{proxmox}}" id=create title="Create container" capture=address}
|
||||
pct create --hostname {{hostname}} --key {{shellbook.public_key}}
|
||||
\`\`\`
|
||||
|
||||
::host{name="{{hostname}}" address="{{address}}" capture=host}
|
||||
`;
|
||||
const service = `---
|
||||
title: Web server
|
||||
params:
|
||||
target: {type: choice, options: [existing, lxc], default: existing}
|
||||
host: {type: host, required: true, default: "{{ct.host}}"}
|
||||
---
|
||||
:::when{target=lxc}
|
||||
::use{notebook="infra/lxc.md" as=ct with="hostname=web-ct"}
|
||||
:::
|
||||
|
||||
\`\`\`sh {check host="{{host}}" id=installed title="Is nginx installed"}
|
||||
command -v nginx
|
||||
\`\`\`
|
||||
`;
|
||||
const files: Record<string, string> = { "infra/lxc.md": lxc };
|
||||
const composed = composeNotebook("web.md", parseNotebook(service), p => files[p] === undefined ? undefined : parseNotebook(files[p]!));
|
||||
|
||||
function harness() {
|
||||
let receive: (event: ServerEvent) => void = () => {};
|
||||
const hosts: HostInfo[] = [{ name: "pve", address: "10.0.0.2", user: "root", port: 22, tags: [] }];
|
||||
const api: Api = {
|
||||
create: vi.fn(), move: vi.fn(), deleteNotebook: vi.fn(),
|
||||
me: vi.fn().mockResolvedValue({}),
|
||||
login: vi.fn(),
|
||||
list: vi.fn().mockResolvedValue({ notebooks: [{ path: "web.md", title: "Web server" }] }),
|
||||
hosts: vi.fn(async () => ({ hosts: [...hosts] })),
|
||||
notebook: vi.fn().mockResolvedValue({
|
||||
path: "web.md", source: service, notebook: composed, includes: ["infra/lxc.md"],
|
||||
builtins: { "shellbook.public_key": "ssh-ed25519 AAAA shellbook" }, version: "1",
|
||||
}),
|
||||
save: vi.fn(),
|
||||
run: vi.fn(async (_request: StartRunRequest) => ({ runId: "1" })),
|
||||
addHost: vi.fn(async (host: HostInfo) => { hosts.push(host); }),
|
||||
events: (callback, connected) => { receive = callback; connected(true); return () => {}; },
|
||||
artifact: () => "/download",
|
||||
};
|
||||
return { api, emit: (event: ServerEvent) => act(() => receive(event)) };
|
||||
}
|
||||
|
||||
it("shows the included notebook and its parameters only for the selected option", async () => {
|
||||
const { api } = harness();
|
||||
render(<App api={api} />);
|
||||
const target = await screen.findByLabelText("target");
|
||||
expect(screen.queryByRole("article", { name: "Create container" })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("group", { name: "LXC container (ct)" })).not.toBeInTheDocument();
|
||||
fireEvent.change(target, { target: { value: "lxc" } });
|
||||
const group = screen.getByRole("group", { name: "LXC container (ct)" });
|
||||
expect(within(group).getByLabelText("hostname *")).toHaveValue("web-ct");
|
||||
fireEvent.change(within(group).getByLabelText("proxmox *"), { target: { value: "pve" } });
|
||||
const create = screen.getByRole("article", { name: "Create container" });
|
||||
expect(create).toHaveTextContent("pct create --hostname web-ct --key 'ssh-ed25519 AAAA shellbook'");
|
||||
// The parent's host waits for the container; the parent's checks cannot run yet.
|
||||
expect(screen.getByText("Available after the step that sets ct.host")).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Run all checks" })).toBeDisabled();
|
||||
});
|
||||
|
||||
it("adds the created container to Hosts and feeds it into the parent's steps", async () => {
|
||||
const { api, emit } = harness();
|
||||
render(<App api={api} />);
|
||||
fireEvent.change(await screen.findByLabelText("target"), { target: { value: "lxc" } });
|
||||
fireEvent.change(screen.getByLabelText("proxmox *"), { target: { value: "pve" } });
|
||||
const card = screen.getByRole("article", { name: "Add host web-ct" });
|
||||
expect(card).toHaveTextContent("Available after: ct.address");
|
||||
fireEvent.click(within(screen.getByRole("article", { name: "Create container" })).getByRole("button", { name: "Run" }));
|
||||
await waitFor(() => expect(api.run).toHaveBeenCalledTimes(1));
|
||||
const request = vi.mocked(api.run).mock.calls[0]![0];
|
||||
expect(request).toMatchObject({ stepId: "ct.create", params: { target: "lxc", "ct.proxmox": "pve", "ct.hostname": "web-ct" } });
|
||||
// Builtins are the server's; the client never sends them.
|
||||
expect(request.runtime).toEqual({});
|
||||
emit({ type: "run.finished", runId: "1", exitCode: 0, durationMs: 5, artifacts: [], captured: { name: "ct.address", value: "10.0.30.160" } });
|
||||
fireEvent.click(within(card).getByRole("button", { name: "Add to Hosts" }));
|
||||
await waitFor(() => expect(api.addHost).toHaveBeenCalledWith({ name: "web-ct", address: "10.0.30.160", user: "root", port: 22, tags: [] }));
|
||||
expect(await within(card).findByRole("status")).toHaveTextContent("web-ct is in Hosts");
|
||||
expect(screen.getByLabelText("host *")).toHaveValue("web-ct");
|
||||
expect(screen.getByRole("article", { name: "Is nginx installed" })).toHaveTextContent("web-ct");
|
||||
expect(screen.getByRole("button", { name: "Run all checks" })).toBeEnabled();
|
||||
});
|
||||
|
||||
it("collapses an included group to a remembered summary whose chips open the field", async () => {
|
||||
const { api } = harness();
|
||||
const view = render(<App api={api} />);
|
||||
fireEvent.change(await screen.findByLabelText("target"), { target: { value: "lxc" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "LXC container (ct) · 1 missing", expanded: true }));
|
||||
const group = screen.getByRole("group", { name: "LXC container (ct)" });
|
||||
expect(within(group).queryByLabelText("proxmox *")).not.toBeInTheDocument();
|
||||
// Untouched defaults are only counted; what needs attention is listed.
|
||||
expect(within(group).queryByRole("button", { name: /hostname/ })).not.toBeInTheDocument();
|
||||
expect(within(group).getByRole("button", { name: "+ 1 at default" })).toBeInTheDocument();
|
||||
view.unmount();
|
||||
render(<App api={harness().api} />);
|
||||
fireEvent.change(await screen.findByLabelText("target"), { target: { value: "lxc" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: /proxmox.*missing/ }));
|
||||
await waitFor(() => expect(screen.getByLabelText("proxmox *")).toHaveFocus());
|
||||
// The rest of the form was never collapsed.
|
||||
expect(screen.getByLabelText("target")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("reloads when an included notebook changes", async () => {
|
||||
const { api, emit } = harness();
|
||||
render(<App api={api} />);
|
||||
await screen.findByLabelText("target");
|
||||
expect(api.notebook).toHaveBeenCalledTimes(1);
|
||||
emit({ type: "file.changed", path: "infra/lxc.md" });
|
||||
await waitFor(() => expect(api.notebook).toHaveBeenCalledTimes(2));
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import { ChatPanel, type ChatSocket } from "../ChatPanel";
|
||||
import type { ChatEvent } from "@shellbook/core";
|
||||
|
||||
function setup() {
|
||||
const socket: ChatSocket = { onopen: null, onclose: null, onerror: null, onmessage: null, send: vi.fn(), close: vi.fn() };
|
||||
const openNotebook = vi.fn(), openTerminal = vi.fn();
|
||||
const view = render(<ChatPanel notebookPath="setup/current.md" connect={() => socket} openNotebook={openNotebook} openTerminal={openTerminal} />);
|
||||
act(() => socket.onopen?.(new Event("open")));
|
||||
const emit = (event: ChatEvent) => act(() => socket.onmessage?.({ data: JSON.stringify(event) } as MessageEvent));
|
||||
return { socket, emit, openNotebook, openTerminal, ...view };
|
||||
}
|
||||
it("sends notebook context, defaults shell off, streams Markdown, opens edited notebooks and stops", () => {
|
||||
const { socket, emit, openNotebook } = setup();
|
||||
fireEvent.change(screen.getByLabelText("Message"), { target: { value: "Create nginx" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send" }));
|
||||
expect(socket.send).toHaveBeenCalledWith(JSON.stringify({ type: "send", message: "Create nginx", notebookPath: "notebooks/setup/current.md", allowShell: false }));
|
||||
emit({ type: "delta", text: "Hello **" }); emit({ type: "delta", text: "world**" });
|
||||
expect(screen.getByText("world").tagName).toBe("STRONG");
|
||||
emit({ type: "tool", name: "Edit", path: "notebooks/nginx.md" });
|
||||
fireEvent.click(screen.getByText("Open notebook")); expect(openNotebook).toHaveBeenCalledWith("nginx.md");
|
||||
fireEvent.click(screen.getByText("Stop")); expect(socket.send).toHaveBeenLastCalledWith('{"type":"cancel"}');
|
||||
emit({ type: "finished", durationMs: 1000, costUsd: .01 }); expect(screen.getByRole("status")).toHaveTextContent("Finished in 1.0s");
|
||||
});
|
||||
it("offers terminal login recovery and closes the socket on unmount", () => {
|
||||
const { emit, openTerminal, unmount, socket } = setup();
|
||||
emit({ type: "error", code: "login", message: "Please log in" });
|
||||
fireEvent.click(screen.getByRole("button", { name: /Open Terminal/ })); expect(openTerminal).toHaveBeenCalledOnce();
|
||||
expect(screen.getByRole("alert")).toHaveTextContent("Please log in");
|
||||
unmount(); expect(socket.close).toHaveBeenCalledOnce();
|
||||
});
|
||||
it("resumes history, enables shell explicitly and resets it for new conversations", () => {
|
||||
const { emit, socket } = setup();
|
||||
emit({ type: "history", conversations: [{ id: "saved", title: "Earlier notebook", createdAt: "now", updatedAt: "now" }] });
|
||||
fireEvent.change(screen.getByLabelText("Conversation history"), { target: { value: "saved" } });
|
||||
fireEvent.click(screen.getByLabelText(/Allow Claude/));
|
||||
fireEvent.click(screen.getByText("Add a check that…"));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send" }));
|
||||
expect(JSON.parse((socket.send as ReturnType<typeof vi.fn>).mock.calls[0]![0])).toMatchObject({ conversationId: "saved", allowShell: true });
|
||||
expect(screen.getByText("New conversation", { selector: "button" })).toBeDisabled();
|
||||
emit({ type: "finished" }); fireEvent.click(screen.getByText("New conversation", { selector: "button" }));
|
||||
expect(screen.getByLabelText(/Allow Claude/)).not.toBeChecked();
|
||||
});
|
||||
it("handles a disconnect and disables sending", () => {
|
||||
const { socket } = setup(); act(() => socket.onclose?.(new CloseEvent("close")));
|
||||
expect(screen.getByRole("alert")).toHaveTextContent("disconnected");
|
||||
expect(screen.getByRole("button", { name: "Reconnect chat" })).toBeInTheDocument();
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
import { fireEvent, render, screen, within } from "@testing-library/react";
|
||||
import { beforeEach, expect, it, vi } from "vitest";
|
||||
vi.mock("../Editor", () => ({ Editor: () => null }));
|
||||
import { App } from "../App";
|
||||
import type { Api } from "../api";
|
||||
import { parseNotebook } from "@shellbook/core";
|
||||
|
||||
const source = `---
|
||||
title: Guided setup
|
||||
params:
|
||||
host: {type: host, required: true, label: Target server}
|
||||
user: {type: name, label: Login user}
|
||||
note: {type: string}
|
||||
---
|
||||
# Guided setup
|
||||
|
||||
:::group{title="1. Connect"}
|
||||
Pick the server first:
|
||||
|
||||
::param{name=host}
|
||||
|
||||
\`\`\`sh {check host="{{host}}" id=whoami title="Who am I"}
|
||||
id {{user}}
|
||||
\`\`\`
|
||||
:::
|
||||
|
||||
:::group{title="2. Notes" collapsed}
|
||||
::param{name=note}
|
||||
:::
|
||||
`;
|
||||
|
||||
function api(): Api {
|
||||
return {
|
||||
create: vi.fn(), move: vi.fn(), deleteNotebook: vi.fn(),
|
||||
me: vi.fn().mockResolvedValue({}),
|
||||
login: vi.fn(),
|
||||
list: vi.fn().mockResolvedValue({ notebooks: [{ path: "guide.md", title: "Guided setup" }] }),
|
||||
hosts: vi.fn().mockResolvedValue({ hosts: [{ name: "pve", address: "10.0.0.2", user: "root", port: 22, tags: [] }] }),
|
||||
notebook: vi.fn().mockResolvedValue({
|
||||
path: "guide.md", source, notebook: parseNotebook(source), includes: [], builtins: {}, version: "1",
|
||||
}),
|
||||
save: vi.fn(),
|
||||
run: vi.fn(),
|
||||
addHost: vi.fn(),
|
||||
events: (_callback, connected) => { connected(true); return () => {}; },
|
||||
artifact: () => "/download",
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => localStorage.clear());
|
||||
|
||||
it("shows parameter fields in the text, bound to the same value as the panel", async () => {
|
||||
render(<App api={api()} />);
|
||||
const connect = await screen.findByRole("region", { name: "1. Connect" });
|
||||
const inline = within(connect).getByLabelText(/Target server/);
|
||||
const panel = within(screen.getByRole("form", { name: "Notebook parameters" })).getByLabelText(/Target server/);
|
||||
expect(inline).not.toBe(panel);
|
||||
fireEvent.change(inline, { target: { value: "pve" } });
|
||||
expect(panel).toHaveValue("pve");
|
||||
fireEvent.change(panel, { target: { value: "" } });
|
||||
expect(inline).toHaveValue("");
|
||||
});
|
||||
|
||||
it("colors a group by the state of its inputs and says so in text", async () => {
|
||||
render(<App api={api()} />);
|
||||
const connect = await screen.findByRole("region", { name: "1. Connect" });
|
||||
// The check needs host (required) and user (referenced by the script).
|
||||
expect(connect).toHaveClass("status-missing");
|
||||
expect(within(connect).getByText("needs Target server, Login user")).toBeInTheDocument();
|
||||
fireEvent.change(within(connect).getByLabelText(/Target server/), { target: { value: "pve" } });
|
||||
expect(connect).toHaveTextContent("needs Login user");
|
||||
fireEvent.change(within(screen.getByRole("form", { name: "Notebook parameters" })).getByLabelText(/Login user/), {
|
||||
target: { value: "admin" },
|
||||
});
|
||||
expect(connect).toHaveClass("status-filled");
|
||||
expect(within(connect).getByText("complete")).toBeInTheDocument();
|
||||
// Only optional inputs: grey.
|
||||
expect(screen.getByRole("region", { name: "2. Notes" })).toHaveClass("status-optional");
|
||||
});
|
||||
|
||||
it("collapses groups, starts collapsed ones closed and remembers the choice", async () => {
|
||||
const { unmount } = render(<App api={api()} />);
|
||||
const notes = await screen.findByRole("region", { name: "2. Notes" });
|
||||
const toggle = within(notes).getByRole("button", { name: "2. Notes" });
|
||||
expect(toggle).toHaveAttribute("aria-expanded", "false");
|
||||
expect(within(notes).getByLabelText("note", { selector: "input" })).not.toBeVisible();
|
||||
fireEvent.click(toggle);
|
||||
expect(within(notes).getByLabelText("note", { selector: "input" })).toBeVisible();
|
||||
const connect = screen.getByRole("region", { name: "1. Connect" });
|
||||
fireEvent.click(within(connect).getByRole("button", { name: "1. Connect" }));
|
||||
expect(within(connect).getByText("Who am I")).not.toBeVisible();
|
||||
unmount();
|
||||
|
||||
render(<App api={api()} />);
|
||||
const again = await screen.findByRole("region", { name: "1. Connect" });
|
||||
expect(within(again).getByRole("button", { name: "1. Connect" })).toHaveAttribute("aria-expanded", "false");
|
||||
expect(within(screen.getByRole("region", { name: "2. Notes" })).getByRole("button", { name: "2. Notes" }))
|
||||
.toHaveAttribute("aria-expanded", "true");
|
||||
});
|
||||
@@ -0,0 +1,133 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { HostsPage } from "../HostsPage";
|
||||
import { json } from "../api";
|
||||
vi.mock("../api", () => ({ json: vi.fn() }));
|
||||
const inventory = {
|
||||
hosts: [
|
||||
{
|
||||
name: "demo",
|
||||
address: "example.org",
|
||||
user: "ops",
|
||||
port: 22,
|
||||
tags: [],
|
||||
credential: { type: "password" },
|
||||
},
|
||||
],
|
||||
version: "v1",
|
||||
publicKey: "ssh-ed25519 AAA",
|
||||
certificateSupport: {
|
||||
available: false,
|
||||
reason: "Certificates unavailable in ssh2",
|
||||
},
|
||||
};
|
||||
afterEach(() => vi.resetAllMocks());
|
||||
it("adds hosts with accessible fields and optimistic version", async () => {
|
||||
vi.mocked(json).mockResolvedValue(inventory);
|
||||
render(<HostsPage />);
|
||||
await screen.findByText("demo");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Add server" }));
|
||||
expect(screen.getByRole("dialog", { name: "Add server" })).toBeInTheDocument();
|
||||
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "new" } });
|
||||
fireEvent.change(screen.getByLabelText("Address"), {
|
||||
target: { value: "::1" },
|
||||
});
|
||||
fireEvent.click(screen.getByText("Save server"));
|
||||
await waitFor(() =>
|
||||
expect(json).toHaveBeenCalledWith("/host-management", "POST", {
|
||||
baseVersion: "v1",
|
||||
host: { name: "new", address: "::1", user: "root", port: 22, tags: [] },
|
||||
}),
|
||||
);
|
||||
});
|
||||
it("sends credentials once and clears password fields", async () => {
|
||||
vi.mocked(json).mockResolvedValue(inventory);
|
||||
render(<HostsPage />);
|
||||
await screen.findByText("demo");
|
||||
fireEvent.click(screen.getByRole("button", { name: "SSH credentials for demo" }));
|
||||
fireEvent.change(screen.getByLabelText("Authentication"), {
|
||||
target: { value: "password" },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText("SSH password"), {
|
||||
target: { value: "never-read-back" },
|
||||
});
|
||||
fireEvent.click(screen.getByText("Save authentication"));
|
||||
await waitFor(() =>
|
||||
expect(json).toHaveBeenCalledWith(
|
||||
"/host-management/demo/credential",
|
||||
"PUT",
|
||||
{ type: "password", password: "never-read-back" },
|
||||
),
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByLabelText("SSH password")).not.toBeInTheDocument(),
|
||||
);
|
||||
expect(document.body.textContent).not.toContain("never-read-back");
|
||||
});
|
||||
it("requires fingerprint confirmation and resends the displayed installation script", async () => {
|
||||
vi.mocked(json).mockImplementation(async (url, method, body) => {
|
||||
if (url.endsWith("/install-key")) return { script: "literal script" };
|
||||
if (url.endsWith("/action"))
|
||||
return (body as { acceptHostKey?: string }).acceptHostKey
|
||||
? { exitCode: 0 }
|
||||
: {
|
||||
hostKey: {
|
||||
fingerprint: "SHA256:test",
|
||||
changed: true,
|
||||
host: "demo",
|
||||
},
|
||||
};
|
||||
return inventory;
|
||||
});
|
||||
render(<HostsPage />);
|
||||
await screen.findByText("demo");
|
||||
fireEvent.click(screen.getByRole("button", { name: "More actions for demo" }));
|
||||
fireEvent.click(screen.getByRole("menuitem", { name: "Install ShellBook key on demo" }));
|
||||
await screen.findByText("literal script");
|
||||
expect(json).not.toHaveBeenCalledWith(
|
||||
"/host-management/demo/action",
|
||||
expect.anything(),
|
||||
expect.anything(),
|
||||
);
|
||||
fireEvent.click(screen.getByText("Run displayed script"));
|
||||
await screen.findByText("WARNING: HOST KEY CHANGED");
|
||||
fireEvent.click(screen.getByText("Trust this fingerprint and retry"));
|
||||
await screen.findByText("demo: success");
|
||||
expect(json).toHaveBeenLastCalledWith(
|
||||
"/host-management/demo/action",
|
||||
"POST",
|
||||
{
|
||||
action: "install-key",
|
||||
script: "literal script",
|
||||
acceptHostKey: "SHA256:test",
|
||||
},
|
||||
);
|
||||
});
|
||||
it("loads external changes without silently changing the version of an open edit", async () => {
|
||||
vi.mocked(json).mockResolvedValue(inventory);
|
||||
render(<HostsPage />);
|
||||
await screen.findByText("demo");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Edit demo" }));
|
||||
vi.mocked(json).mockResolvedValue({ ...inventory, version: "v2" });
|
||||
window.dispatchEvent(new Event("shellbook:hosts-changed"));
|
||||
await waitFor(() => expect(json).toHaveBeenCalledTimes(2));
|
||||
fireEvent.click(screen.getByText("Save server"));
|
||||
await waitFor(() =>
|
||||
expect(json).toHaveBeenCalledWith(
|
||||
"/host-management/demo",
|
||||
"PUT",
|
||||
expect.objectContaining({ baseVersion: "v1" }),
|
||||
),
|
||||
);
|
||||
});
|
||||
it("shows the server's reason for a failed connection test without a conflict hint", async () => {
|
||||
vi.mocked(json).mockImplementation(async (url) => {
|
||||
if (url.endsWith("/action")) throw Object.assign(new Error("SSH authentication failed: check the user and the saved password or key"), { status: 502 });
|
||||
return inventory;
|
||||
});
|
||||
render(<HostsPage />);
|
||||
await screen.findByText("demo");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Test connection to demo" }));
|
||||
const alert = await screen.findByText(/SSH authentication failed/);
|
||||
expect(alert.textContent).toBe("SSH authentication failed: check the user and the saved password or key");
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import { parseNotebook } from "@shellbook/core";
|
||||
import { AuthoringToolbar } from "../AuthoringToolbar";
|
||||
import { NotebookList } from "../NotebookList";
|
||||
import { newNotebook } from "../authoring";
|
||||
import type { Api } from "../api";
|
||||
it("inserts snippets and adds parameters through forms", () => {
|
||||
const insert = vi.fn(),
|
||||
replace = vi.fn();
|
||||
render(
|
||||
<AuthoringToolbar
|
||||
source={newNotebook("Example")}
|
||||
insert={insert}
|
||||
replace={replace}
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Run step" }));
|
||||
expect(insert.mock.calls[0]![0]).toContain("on=local");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Parameter" }));
|
||||
fireEvent.change(screen.getByLabelText("Parameter name"), {
|
||||
target: { value: "package" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "Add parameter" }));
|
||||
expect(
|
||||
parseNotebook(replace.mock.calls[0]![0]).params.some(
|
||||
(p) => p.name === "package",
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
it("shows a folder tree, filters, creates and navigates", async () => {
|
||||
const create = vi
|
||||
.fn()
|
||||
.mockResolvedValue({ path: "ops/new.md", version: "1" });
|
||||
const changed = vi.fn().mockResolvedValue(undefined);
|
||||
render(
|
||||
<NotebookList
|
||||
api={{ create } as unknown as Api}
|
||||
list={[
|
||||
{ path: "ops/a.md", title: "Alpha" },
|
||||
{ path: "b.md", title: "Beta" },
|
||||
]}
|
||||
path=""
|
||||
onSelect={vi.fn()}
|
||||
onChanged={changed}
|
||||
canLeave={() => true}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByText("ops")).toBeInTheDocument();
|
||||
fireEvent.change(screen.getByLabelText("Search notebooks"), {
|
||||
target: { value: "Alpha" },
|
||||
});
|
||||
expect(screen.queryByText("Beta")).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "New notebook" }));
|
||||
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "new" } });
|
||||
fireEvent.change(screen.getByLabelText("Folder (optional)"), {
|
||||
target: { value: "ops" },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText("Title"), {
|
||||
target: { value: "New" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "Apply" }));
|
||||
await waitFor(() => expect(changed).toHaveBeenCalledWith("ops/new.md"));
|
||||
expect(create.mock.calls[0]![0]).toBe("ops/new.md");
|
||||
expect(parseNotebook(create.mock.calls[0]![1]).diagnostics).toEqual([]);
|
||||
});
|
||||
it("requires explicit delete confirmation and uses the displayed version", async () => {
|
||||
const remove = vi.fn().mockResolvedValue({ deleted: true });
|
||||
const changed = vi.fn().mockResolvedValue(undefined);
|
||||
render(
|
||||
<NotebookList
|
||||
api={
|
||||
{
|
||||
notebook: async () => ({ version: "latest" }),
|
||||
deleteNotebook: remove,
|
||||
} as unknown as Api
|
||||
}
|
||||
list={[{ path: "a.md", title: "A" }]}
|
||||
path="a.md"
|
||||
version="latest"
|
||||
onSelect={vi.fn()}
|
||||
onChanged={changed}
|
||||
canLeave={() => true}
|
||||
/>,
|
||||
);
|
||||
// The open notebook has an actions menu; deleting asks again in a dialog.
|
||||
fireEvent.click(screen.getByRole("button", { name: "Actions for A" }));
|
||||
fireEvent.click(screen.getByRole("menuitem", { name: "Delete" }));
|
||||
expect(screen.getByRole("dialog", { name: "Delete notebook" })).toHaveTextContent("a.md");
|
||||
expect(remove).not.toHaveBeenCalled();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Confirm delete" }));
|
||||
await waitFor(() => expect(remove).toHaveBeenCalledWith("a.md", "latest"));
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { PasswordForm } from "../PasswordForm";
|
||||
import { SetupScreen } from "../SetupScreen";
|
||||
import { SettingsPage } from "../SettingsPage";
|
||||
import { HeaderNavigation } from "../HeaderNavigation";
|
||||
import { settingsApi } from "../settingsApi";
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
function fill(label: string, value: string) {
|
||||
fireEvent.change(screen.getByLabelText(label), { target: { value } });
|
||||
}
|
||||
it("validates confirmation and clears credentials after setup", async () => {
|
||||
const submit = vi.fn().mockResolvedValue(undefined);
|
||||
render(<PasswordForm setup submit={submit} />);
|
||||
fill("Setup token", "token");
|
||||
fill("New password", "long password here");
|
||||
fill("Confirm password", "wrong password here");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Set up ShellBook" }));
|
||||
expect(await screen.findByText("Passwords do not match")).toBeInTheDocument();
|
||||
expect(submit).not.toHaveBeenCalled();
|
||||
fill("Confirm password", "long password here");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Set up ShellBook" }));
|
||||
await waitFor(() =>
|
||||
expect(submit).toHaveBeenCalledWith({
|
||||
token: "token",
|
||||
currentPassword: "",
|
||||
newPassword: "long password here",
|
||||
confirmPassword: "long password here",
|
||||
}),
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(screen.getByLabelText("New password")).toHaveValue(""),
|
||||
);
|
||||
});
|
||||
it("submits setup and enters the app", async () => {
|
||||
vi.spyOn(settingsApi, "setup").mockResolvedValue();
|
||||
const done = vi.fn();
|
||||
render(<SetupScreen onComplete={done} />);
|
||||
fill("Setup token", "token");
|
||||
fill("New password", "long password here");
|
||||
fill("Confirm password", "long password here");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Set up ShellBook" }));
|
||||
await waitFor(() => expect(done).toHaveBeenCalledOnce());
|
||||
});
|
||||
it("shows password failure and preserves the form for retry", async () => {
|
||||
render(
|
||||
<PasswordForm submit={vi.fn().mockRejectedValue(new Error("invalid"))} />,
|
||||
);
|
||||
fill("Current password", "wrong");
|
||||
fill("New password", "long password here");
|
||||
fill("Confirm password", "long password here");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Change password" }));
|
||||
expect(await screen.findByRole("status")).toHaveTextContent("Unable to save");
|
||||
});
|
||||
it("renders system/session/Claude information and opens the terminal", async () => {
|
||||
vi.spyOn(settingsApi, "system").mockResolvedValue({
|
||||
version: "1.2",
|
||||
workspacePath: "/workspace",
|
||||
dataDirPath: "/data",
|
||||
nodeVersion: "v22",
|
||||
});
|
||||
vi.spyOn(settingsApi, "session").mockResolvedValue({
|
||||
lifetimeSeconds: 86400,
|
||||
});
|
||||
vi.spyOn(settingsApi, "claude").mockResolvedValue({
|
||||
available: true,
|
||||
version: "Claude 1",
|
||||
loginAppearsPresent: true,
|
||||
});
|
||||
vi.spyOn(settingsApi, "updateStatus").mockResolvedValue({
|
||||
available: true,
|
||||
state: "idle",
|
||||
current: "abc1234",
|
||||
startedAt: null,
|
||||
finishedAt: null,
|
||||
log: "",
|
||||
});
|
||||
const revoke = vi.spyOn(settingsApi, "revoke").mockResolvedValue();
|
||||
const open = vi.fn();
|
||||
render(<SettingsPage openTerminal={open} />);
|
||||
expect(await screen.findByText("/workspace")).toBeInTheDocument();
|
||||
expect(await screen.findByRole("button", { name: "Update now" })).toBeInTheDocument();
|
||||
expect(screen.getByText(/86400 seconds/)).toBeInTheDocument();
|
||||
expect(screen.getByText("Available: Claude 1")).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByText("Open terminal to log in"));
|
||||
expect(open).toHaveBeenCalledOnce();
|
||||
fireEvent.click(screen.getByText("Sign out all sessions"));
|
||||
await waitFor(() => expect(revoke).toHaveBeenCalledOnce());
|
||||
expect(await screen.findByRole("status")).toHaveTextContent(
|
||||
"This browser remains signed in",
|
||||
);
|
||||
});
|
||||
it("provides the shared feature navigation", () => {
|
||||
const change = vi.fn();
|
||||
render(<HeaderNavigation page="Notebooks" onChange={change} />);
|
||||
fireEvent.click(screen.getByText("Settings"));
|
||||
expect(change).toHaveBeenCalledWith("Settings");
|
||||
expect(screen.getByText("Hosts")).toBeInTheDocument();
|
||||
expect(screen.getByText("Notebooks")).toHaveAttribute("aria-current", "page");
|
||||
});
|
||||
@@ -1,4 +1,9 @@
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import { cleanup } from "@testing-library/react";
|
||||
import { afterEach } from "vitest";
|
||||
afterEach(cleanup);
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
// The app keeps its route in the URL and typed values in localStorage.
|
||||
localStorage.clear();
|
||||
history.replaceState(null, "", "/");
|
||||
});
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { expect, it, vi } from "vitest";
|
||||
vi.mock("../Editor", () => ({
|
||||
Editor: ({ source, onChange }: { source: string; onChange(value: string): void }) => (
|
||||
<textarea aria-label="Notebook Markdown" value={source} onChange={(e) => onChange(e.target.value)} />
|
||||
),
|
||||
}));
|
||||
import { parseNotebook } from "@shellbook/core";
|
||||
import type { RenderedStep } from "@shellbook/core";
|
||||
import { App } from "../App";
|
||||
import type { Api } from "../api";
|
||||
import { parseRoute, routeHash } from "../route";
|
||||
import { recallValues, rememberValues } from "../paramMemory";
|
||||
import { stepProblems } from "../StepCard";
|
||||
import { Dialog } from "../ui";
|
||||
import source from "../mock/ssh-key.md?raw";
|
||||
|
||||
const secretBook = parseNotebook(`---
|
||||
params:
|
||||
host: { type: host }
|
||||
token: { type: secret }
|
||||
---
|
||||
# T
|
||||
`);
|
||||
|
||||
it("round-trips page and notebook routes, including encoded segments", () => {
|
||||
for (const route of [
|
||||
{ page: "Hosts" as const },
|
||||
{ page: "Settings" as const },
|
||||
{ page: "Notebooks" as const, notebook: "ops/linux/a b#1.md" },
|
||||
])
|
||||
expect(parseRoute(routeHash(route))).toEqual(route);
|
||||
expect(routeHash({ page: "Notebooks", notebook: "a b.md" })).toBe("#/notebooks/a%20b.md");
|
||||
expect(parseRoute("")).toEqual({ page: "Notebooks" });
|
||||
expect(parseRoute("#/unknown/x")).toEqual({ page: "Notebooks" });
|
||||
expect(parseRoute("#/notebooks/%E0%A4%A")).toEqual({ page: "Notebooks" });
|
||||
});
|
||||
|
||||
it("remembers typed values but never secrets or undeclared names", () => {
|
||||
rememberValues("a.md", secretBook, { host: "web", token: "s3cret", other: "x" });
|
||||
expect(localStorage.getItem("shellbook:params:a.md")).not.toContain("s3cret");
|
||||
expect(recallValues("a.md", secretBook)).toEqual({ host: "web" });
|
||||
// Stored data is untrusted: a secret written by hand is still dropped.
|
||||
localStorage.setItem("shellbook:params:a.md", JSON.stringify({ token: "x", host: 1 }));
|
||||
expect(recallValues("a.md", secretBook)).toEqual({});
|
||||
localStorage.setItem("shellbook:params:a.md", "not json");
|
||||
expect(recallValues("a.md", secretBook)).toEqual({});
|
||||
rememberValues("a.md", secretBook, {});
|
||||
expect(localStorage.getItem("shellbook:params:a.md")).toBeNull();
|
||||
});
|
||||
|
||||
it("names a missing value once instead of repeating it as an invalid host", () => {
|
||||
const rendered: RenderedStep = {
|
||||
stepId: "s", kind: "check", local: false, host: "{{host}}", script: "id",
|
||||
artifacts: [], uploads: [], missing: ["host"],
|
||||
invalid: { host: "Unknown or missing target host" },
|
||||
};
|
||||
expect(stepProblems(rendered)).toEqual(["Fill in host to run this step."]);
|
||||
expect(stepProblems({ ...rendered, host: "gone", missing: [], invalid: { host: "Unknown or missing target host", port: "bad" } }))
|
||||
.toEqual(["host: Unknown or missing target host", "port: bad"]);
|
||||
});
|
||||
|
||||
it("closes dialogs with Escape", () => {
|
||||
const close = vi.fn();
|
||||
render(<Dialog title="Example" onClose={close}><input aria-label="Field" /></Dialog>);
|
||||
expect(screen.getByLabelText("Field")).toHaveFocus();
|
||||
fireEvent.keyDown(document, { key: "Escape" });
|
||||
expect(close).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
function api(): Api {
|
||||
const notebook = (path: string) => ({ path, source, notebook: parseNotebook(source), includes: [], builtins: {}, version: "1" });
|
||||
return {
|
||||
create: vi.fn(), move: vi.fn(), deleteNotebook: vi.fn(),
|
||||
me: vi.fn().mockResolvedValue({}),
|
||||
login: vi.fn(),
|
||||
list: vi.fn().mockResolvedValue({ notebooks: [{ path: "a.md", title: "A" }, { path: "ops/b.md", title: "B" }] }),
|
||||
hosts: vi.fn().mockResolvedValue({ hosts: [{ name: "staging", user: "admin", address: "x", port: 22, tags: [] }] }),
|
||||
notebook: vi.fn(async (path: string) => notebook(path)),
|
||||
save: vi.fn().mockResolvedValue({ version: "2" }),
|
||||
addHost: vi.fn(),
|
||||
run: vi.fn(),
|
||||
events: (_callback, connected) => { connected(true); return () => {}; },
|
||||
artifact: () => "",
|
||||
};
|
||||
}
|
||||
|
||||
it("opens the notebook named in the URL, keeps typed values across reloads and shows the route", async () => {
|
||||
history.replaceState(null, "", "/#/notebooks/ops/b.md");
|
||||
const first = api();
|
||||
const view = render(<App api={first} />);
|
||||
fireEvent.change(await screen.findByLabelText("Target server *"), { target: { value: "staging" } });
|
||||
expect(first.notebook).toHaveBeenCalledWith("ops/b.md");
|
||||
expect(first.notebook).not.toHaveBeenCalledWith("a.md");
|
||||
await waitFor(() => expect(location.hash).toBe("#/notebooks/ops/b.md"));
|
||||
view.unmount();
|
||||
render(<App api={api()} />);
|
||||
await waitFor(() => expect(screen.getByLabelText("Target server *")).toHaveValue("staging"));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Reset" }));
|
||||
expect(screen.getByLabelText("Target server *")).toHaveValue("");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Hosts" }));
|
||||
await waitFor(() => expect(location.hash).toBe("#/hosts"));
|
||||
});
|
||||
|
||||
it("collapses the parameter form to a remembered summary whose chips open their field", async () => {
|
||||
const view = render(<App api={api()} />);
|
||||
fireEvent.change(await screen.findByLabelText("Target server *"), { target: { value: "staging" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Parameters", expanded: true }));
|
||||
expect(screen.queryByLabelText("Target server *")).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: /Target server.*staging/ })).toBeInTheDocument();
|
||||
view.unmount();
|
||||
render(<App api={api()} />);
|
||||
const chip = await screen.findByRole("button", { name: /Target server.*staging/ });
|
||||
expect(screen.getByRole("button", { name: "Parameters", expanded: false })).toBeInTheDocument();
|
||||
fireEvent.click(chip);
|
||||
await waitFor(() => expect(screen.getByLabelText("Target server *")).toHaveFocus());
|
||||
expect(screen.getByRole("button", { name: "Parameters", expanded: true })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("saves the draft with Ctrl+S", async () => {
|
||||
const live = api();
|
||||
render(<App api={live} />);
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Edit Markdown" }));
|
||||
fireEvent.change(await screen.findByLabelText("Notebook Markdown"), { target: { value: source + "\nMore\n" } });
|
||||
fireEvent.keyDown(window, { key: "s", ctrlKey: true });
|
||||
await waitFor(() => expect(live.save).toHaveBeenCalledWith("a.md", source + "\nMore\n", "1"));
|
||||
});
|
||||
@@ -0,0 +1,115 @@
|
||||
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import type { UpdateStatusResponse } from "@shellbook/core";
|
||||
import { UpdatePanel } from "../UpdatePanel";
|
||||
|
||||
const idle: UpdateStatusResponse = {
|
||||
available: true,
|
||||
state: "idle",
|
||||
current: "abc1234",
|
||||
startedAt: null,
|
||||
finishedAt: null,
|
||||
log: "",
|
||||
};
|
||||
|
||||
function fakeApi(statuses: (UpdateStatusResponse | Error)[]) {
|
||||
let index = 0;
|
||||
return {
|
||||
// Returns the statuses in order and then keeps returning the last one.
|
||||
updateStatus: vi.fn(async () => {
|
||||
const next = statuses[Math.min(index++, statuses.length - 1)]!;
|
||||
if (next instanceof Error) throw next;
|
||||
return next;
|
||||
}),
|
||||
checkUpdate: vi.fn(),
|
||||
startUpdate: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
it("explains the manual update when the trigger is not installed", async () => {
|
||||
const api = fakeApi([{ ...idle, available: false }]);
|
||||
render(<UpdatePanel api={api} />);
|
||||
expect(await screen.findByText("abc1234")).toBeInTheDocument();
|
||||
expect(screen.getByText(/not set up on this installation/)).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Update now" })).toBeNull();
|
||||
});
|
||||
|
||||
it("lists the commits an update would bring, or says it is up to date", async () => {
|
||||
const api = fakeApi([idle]);
|
||||
api.checkUpdate
|
||||
.mockResolvedValueOnce({
|
||||
current: "abc1234",
|
||||
latest: "def5678",
|
||||
pinned: false,
|
||||
changes: [
|
||||
{ commit: "def5678", subject: "feat(web): newer" },
|
||||
{ commit: "bbb0000", subject: "fix: older" },
|
||||
],
|
||||
})
|
||||
.mockResolvedValueOnce({ current: "def5678", latest: "def5678", pinned: false, changes: [] })
|
||||
.mockResolvedValueOnce({ current: "abc1234", latest: null, pinned: true, changes: [] })
|
||||
.mockRejectedValueOnce(new Error("502"));
|
||||
render(<UpdatePanel api={api} />);
|
||||
const check = await screen.findByRole("button", { name: "Check for updates" });
|
||||
fireEvent.click(check);
|
||||
expect(await screen.findByText(/2 new changes/)).toBeInTheDocument();
|
||||
expect(screen.getByText("feat(web): newer")).toBeInTheDocument();
|
||||
fireEvent.click(check);
|
||||
expect(await screen.findByText("Up to date (def5678).")).toBeInTheDocument();
|
||||
fireEvent.click(check);
|
||||
expect(await screen.findByText(/pinned to a fixed version/)).toBeInTheDocument();
|
||||
fireEvent.click(check);
|
||||
expect(await screen.findByText("Unable to reach the repository.")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("asks first, then follows the update through the restart and offers a reload", async () => {
|
||||
const requestedAt = new Date().toISOString();
|
||||
const startedAt = new Date(Date.parse(requestedAt) + 1000).toISOString();
|
||||
const api = fakeApi([
|
||||
idle,
|
||||
{ ...idle, state: "running", startedAt, log: "Pulling…\nBuilding…" },
|
||||
new Error("502"),
|
||||
{ ...idle, state: "succeeded", current: "def5678", startedAt, finishedAt: startedAt, log: "Done" },
|
||||
]);
|
||||
api.startUpdate.mockResolvedValue({ requestedAt });
|
||||
render(<UpdatePanel api={api} pollMs={5} />);
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Update now" }));
|
||||
// Nothing starts before the confirmation.
|
||||
const dialog = screen.getByRole("dialog", { name: "Update ShellBook?" });
|
||||
expect(api.startUpdate).not.toHaveBeenCalled();
|
||||
fireEvent.click(within(dialog).getByRole("button", { name: "Update now" }));
|
||||
await waitFor(() => expect(api.startUpdate).toHaveBeenCalledOnce());
|
||||
expect(await screen.findByText(/Building…/)).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Update now" })).toBeDisabled();
|
||||
await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent("Update finished (def5678)"));
|
||||
expect(screen.getByRole("button", { name: "Reload" })).toBeInTheDocument();
|
||||
// The restart in between was shown instead of an error.
|
||||
expect(screen.queryByText(/Unable to load/)).toBeNull();
|
||||
});
|
||||
|
||||
it("does not mistake the previous run for the requested one", async () => {
|
||||
const requestedAt = new Date().toISOString();
|
||||
const old = new Date(Date.parse(requestedAt) - 3_600_000).toISOString();
|
||||
const api = fakeApi([{ ...idle, state: "succeeded", startedAt: old, finishedAt: old, log: "old run" }]);
|
||||
api.startUpdate.mockResolvedValue({ requestedAt });
|
||||
render(<UpdatePanel api={api} pollMs={5} />);
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Update now" }));
|
||||
fireEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Update now" }));
|
||||
await waitFor(() => expect(api.updateStatus.mock.calls.length).toBeGreaterThan(3));
|
||||
expect(screen.getByRole("status")).toHaveTextContent("Starting the update…");
|
||||
});
|
||||
|
||||
it("shows a failed update with its log", async () => {
|
||||
const requestedAt = new Date().toISOString();
|
||||
const api = fakeApi([
|
||||
idle,
|
||||
{ ...idle, state: "failed", startedAt: requestedAt, finishedAt: requestedAt, log: "pnpm: build failed" },
|
||||
]);
|
||||
api.startUpdate.mockResolvedValue({ requestedAt });
|
||||
render(<UpdatePanel api={api} pollMs={5} />);
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Update now" }));
|
||||
fireEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Update now" }));
|
||||
await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent("The update failed"));
|
||||
expect(screen.getByText("pnpm: build failed")).toBeVisible();
|
||||
expect(screen.getByRole("button", { name: "Update now" })).toBeEnabled();
|
||||
});
|
||||
@@ -0,0 +1,155 @@
|
||||
import { useEffect, useId, useRef, useState, type ReactNode } from "react";
|
||||
|
||||
/** Modal dialog: Escape and the backdrop cancel; focus moves into it on open. */
|
||||
/** The ShellBook mark (public/shellbook.svg); decorative next to the product name. */
|
||||
export function Logo({ size = 22 }: { size?: number }) {
|
||||
return <img className="logo" src="/shellbook.svg" width={size} height={size} alt="" />;
|
||||
}
|
||||
|
||||
export function Dialog({
|
||||
title,
|
||||
onClose,
|
||||
children,
|
||||
wide = false,
|
||||
}: {
|
||||
title: string;
|
||||
onClose(): void;
|
||||
children: ReactNode;
|
||||
wide?: boolean;
|
||||
}) {
|
||||
const id = useId();
|
||||
const box = useRef<HTMLElement>(null);
|
||||
const close = useRef(onClose);
|
||||
close.current = onClose;
|
||||
useEffect(() => {
|
||||
const previous = document.activeElement as HTMLElement | null;
|
||||
const first = box.current?.querySelector<HTMLElement>(
|
||||
"input:not([type=hidden]), select, textarea, button:not(.dialog-close)",
|
||||
);
|
||||
first?.focus();
|
||||
const key = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") close.current();
|
||||
};
|
||||
document.addEventListener("keydown", key);
|
||||
return () => {
|
||||
document.removeEventListener("keydown", key);
|
||||
previous?.focus?.();
|
||||
};
|
||||
}, []);
|
||||
return (
|
||||
<div
|
||||
className="modal-backdrop"
|
||||
onMouseDown={(e) => {
|
||||
if (e.target === e.currentTarget) onClose();
|
||||
}}
|
||||
>
|
||||
<section
|
||||
ref={box}
|
||||
className={wide ? "dialog wide" : "dialog"}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby={id}
|
||||
>
|
||||
<header>
|
||||
<h2 id={id}>{title}</h2>
|
||||
<button type="button" className="dialog-close icon" aria-label="Close" onClick={onClose}>
|
||||
×
|
||||
</button>
|
||||
</header>
|
||||
{children}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** A small popup menu; closes on outside click, Escape, or after choosing an item. */
|
||||
export function Menu({
|
||||
label,
|
||||
text = "⋯",
|
||||
children,
|
||||
}: {
|
||||
label: string;
|
||||
text?: ReactNode;
|
||||
children: (close: () => void) => ReactNode;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const root = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const outside = (e: MouseEvent) => {
|
||||
if (!root.current?.contains(e.target as Node)) setOpen(false);
|
||||
};
|
||||
const key = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") setOpen(false);
|
||||
};
|
||||
document.addEventListener("mousedown", outside);
|
||||
document.addEventListener("keydown", key);
|
||||
return () => {
|
||||
document.removeEventListener("mousedown", outside);
|
||||
document.removeEventListener("keydown", key);
|
||||
};
|
||||
}, [open]);
|
||||
return (
|
||||
<div className="menu" ref={root}>
|
||||
<button
|
||||
type="button"
|
||||
className="icon"
|
||||
aria-label={label}
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={open}
|
||||
onClick={() => setOpen(!open)}
|
||||
>
|
||||
{text}
|
||||
</button>
|
||||
{open && (
|
||||
<div className="menu-items" role="menu" aria-label={label}>
|
||||
{children(() => setOpen(false))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Copies text and briefly confirms on the button itself. */
|
||||
export function CopyButton({
|
||||
text,
|
||||
label = "Copy",
|
||||
disabled,
|
||||
title,
|
||||
}: {
|
||||
text: () => string;
|
||||
label?: string;
|
||||
disabled?: boolean;
|
||||
title?: string;
|
||||
}) {
|
||||
const [state, setState] = useState<"" | "done" | "failed">("");
|
||||
useEffect(() => {
|
||||
if (!state) return;
|
||||
const timer = setTimeout(() => setState(""), 1800);
|
||||
return () => clearTimeout(timer);
|
||||
}, [state]);
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
disabled={disabled}
|
||||
title={title}
|
||||
onClick={async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text());
|
||||
setState("done");
|
||||
} catch {
|
||||
setState("failed");
|
||||
}
|
||||
}}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
{state && (
|
||||
<small role="status" className={state === "failed" ? "error" : "ok"}>
|
||||
{state === "done" ? "Copied" : "Copy failed. Select and copy manually."}
|
||||
</small>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Per-browser layout preferences (collapsed panels and the like). Never holds data that
|
||||
* must persist reliably; storage may be missing or blocked, which falls back to defaults.
|
||||
*/
|
||||
const key = (name: string) => `shellbook:ui:${name}`;
|
||||
|
||||
export function readFlag(name: string, fallback: boolean): boolean {
|
||||
try {
|
||||
const stored = localStorage.getItem(key(name));
|
||||
return stored === null ? fallback : stored === "1";
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
export function writeFlag(name: string, value: boolean): void {
|
||||
try {
|
||||
localStorage.setItem(key(name), value ? "1" : "0");
|
||||
} catch {
|
||||
// Unavailable storage only means the choice lasts for this page.
|
||||
}
|
||||
}
|
||||
+43
-13
@@ -4,8 +4,15 @@ Access is root-equivalent across managed hosts. Restrict CT port 8080 to the
|
||||
Traefik host with the Proxmox firewall; use HTTPS and limit the router to your
|
||||
LAN/Tailscale addresses. No password is set initially: API access fails closed.
|
||||
|
||||
1. Copy `deploy/` to the Proxmox VE 9 host. As root run
|
||||
`bash deploy/proxmox/create-ct.sh`. Defaults: unprivileged Debian 13 CT 501,
|
||||
1. On the Proxmox VE 9 host, as root, run (installs or updates; nothing stays on the host):
|
||||
|
||||
```bash
|
||||
bash -c "$(curl -fsSL https://git.finalfactory.de/FinalFactory/ShellBook/raw/branch/main/deploy/proxmox/bootstrap.sh)"
|
||||
```
|
||||
|
||||
It unpacks the repository into a temporary directory, runs
|
||||
`deploy/proxmox/create-ct.sh` from it, and removes it again; the installer files
|
||||
pushed into the CT are removed too. Defaults: unprivileged Debian 13 CT 501,
|
||||
2 cores, 2 GiB RAM, 16 GiB disk, DHCP on vmbr0, onboot, nesting and TUN.
|
||||
Overrides: `CTID`, `CT_STORAGE`, `TEMPLATE_STORAGE`, `CT_BRIDGE`, `CT_IP`
|
||||
(Proxmox ip syntax), `CT_HOSTNAME`, `CT_CORES`, `CT_MEMORY`, `CT_DISK_GB`.
|
||||
@@ -15,10 +22,13 @@ LAN/Tailscale addresses. No password is set initially: API access fails closed.
|
||||
`SHELLBOOK_PORT`, `SHELLBOOK_TRUSTED_PROXIES` (comma-separated proxy IPs),
|
||||
and `TS_AUTHKEY` in the host environment. Auth keys are transferred in a
|
||||
mode-0600 temporary file and removed, never stored in the service env.
|
||||
3. In the CT run the printed password command. It also accepts one password
|
||||
line on stdin; do not pass passwords as arguments. Source-checkout command:
|
||||
`SHELLBOOK_DATA_DIR=/var/lib/shellbook pnpm --filter @shellbook/server set-password`.
|
||||
4. Run `claude` as shellbook and use `/login`. Authorize
|
||||
3. Open the address the installer prints and enter the one-time setup token it prints
|
||||
(also `cat /var/lib/shellbook/setup-token` in the CT) with a new password (at least
|
||||
12 characters). The token survives restart, is deleted after setup, and the server
|
||||
never logs it; only the installer shows it to the admin running it.
|
||||
Alternative password CLI: `SHELLBOOK_DATA_DIR=/var/lib/shellbook pnpm --filter @shellbook/server set-password`
|
||||
from the checkout (hidden prompt or one password line on stdin; never arguments).
|
||||
4. Unless a Claude login already exists: Settings > "Open terminal to log in", then `/login`. Authorize
|
||||
`/home/shellbook/.ssh/id_ed25519.pub` on managed hosts. The service user has
|
||||
no sudo access. Initialize notebooks manually if templates were absent.
|
||||
5. Install the Traefik example in its file-provider directory and replace the
|
||||
@@ -28,16 +38,35 @@ LAN/Tailscale addresses. No password is set initially: API access fails closed.
|
||||
detection (and thus Secure cookies). TLS terminates at Traefik.
|
||||
|
||||
Standalone CT installation: run `bash deploy/install.sh` as root on Debian 13.
|
||||
The installer can be rerun; it preserves env, password, workspace, SSH key and
|
||||
session signing secret. It builds the checkout but does not pull on rerun.
|
||||
Updates: `bash /opt/shellbook/deploy/update.sh` (root). Failure before restart
|
||||
leaves the running service in place. Check `journalctl -u shellbook`.
|
||||
|
||||
Updates: `shellbook-update` as root in the CT (from the Proxmox host:
|
||||
`pct exec 501 -- shellbook-update`), or rerun the bootstrap command. It downloads
|
||||
the installer from the repository (`/etc/shellbook/installer-url`, override with
|
||||
`SHELLBOOK_INSTALLER_URL`) and reruns it: pull (fast-forward; a `SHELLBOOK_REF`
|
||||
pin is kept), install, build, restart, health check. Env, password, workspace,
|
||||
SSH key, Claude login and session secret are preserved. Root never executes
|
||||
scripts from `/opt/shellbook`, which the service user (and the terminal panel)
|
||||
can modify. A failed build leaves the running service in place; check
|
||||
`journalctl -u shellbook`.
|
||||
|
||||
Settings → Updates shows the installed commit, checks the repository for new
|
||||
commits, and starts the same update with **Update now**, following its output
|
||||
through the restart. The button needs the trigger units the installer adds
|
||||
(`shellbook-update.path` watches `/var/lib/shellbook/update-request` and starts
|
||||
`shellbook-update.service` as root; output in `/var/log/shellbook-update.log`). Older
|
||||
installations get them with one `shellbook-update` run from the CLI. If the button
|
||||
does nothing, check `systemctl status shellbook-update.path shellbook-update`.
|
||||
|
||||
Configuration is `/etc/shellbook/env`; data is `/var/lib/shellbook` (back it up
|
||||
along with workspace and service-user home). `SHELLBOOK_SESSION_SECONDS` defaults
|
||||
to 2592000 (30 days). Cookies survive restart. Logout clears the browser cookie;
|
||||
password changes do not revoke existing cookies. For emergency revocation stop
|
||||
the service, delete `session-secret` from the data directory and start it again.
|
||||
Settings supports changing the password and signing out all sessions; both revoke
|
||||
older cookies and close active WebSockets, while the current browser receives a fresh
|
||||
cookie. CLI password changes invalidate cookies on their next request. For emergency
|
||||
revocation stop the service, delete `session-secret`, and restart it.
|
||||
Settings also shows paths, versions, and Claude CLI status, and opens the terminal
|
||||
for `claude` then `/login` as the service user. A credentials file's existence is only
|
||||
a hint, not proof that a login is valid.
|
||||
|
||||
Forward auth is off by default. To enable it set
|
||||
`SHELLBOOK_FORWARD_AUTH_HEADER=Remote-User` and trusted proxy IPs. The header is
|
||||
@@ -59,7 +88,8 @@ Node 22 security releases; unattended upgrades cover Debian packages only.
|
||||
Build tools support node-pty compilation. Claude uses its native installer.
|
||||
|
||||
Local deployment regressions: `bash deploy/test/template-picker.test.sh` and
|
||||
`bash deploy/test/ct-config.test.sh`, `bash deploy/test/install-script.test.sh`. Existing CTs with a manual TUN mount entry
|
||||
`bash deploy/test/ct-config.test.sh`, `bash deploy/test/install-script.test.sh`,
|
||||
`bash deploy/test/bootstrap.test.sh` (needs root; run it in a Debian container). Existing CTs with a manual TUN mount entry
|
||||
(earlier Tailscale setups) keep it; no `dev0` is added on top.
|
||||
The scripts require bash, use LF endings, and avoid early-consuming pipelines
|
||||
under pipefail. Proxmox, systemd, Tailscale and SSH require deployment validation.
|
||||
|
||||
+96
-11
@@ -1,4 +1,7 @@
|
||||
#!/usr/bin/env bash
|
||||
# Installs ShellBook on Debian 13, or updates an existing installation (rerunnable).
|
||||
# Keeps env, password, workspace, SSH key, Claude login and session secret.
|
||||
# Also installs `shellbook-update`, which reruns this installer fetched over HTTPS.
|
||||
set -euo pipefail
|
||||
[[ $EUID == 0 ]] || { echo 'Run as root inside Debian 13' >&2; exit 1; }
|
||||
# `pct exec` starts with PATH=/sbin:/bin:/usr/sbin:/usr/bin; Node and pnpm live in /usr/local/bin.
|
||||
@@ -44,7 +47,10 @@ if [[ ! -e /opt/shellbook ]]; then
|
||||
install -d -o shellbook -g shellbook /opt/shellbook
|
||||
runuser -u shellbook -- git clone "$repo" /opt/shellbook
|
||||
fi
|
||||
if [[ -n ${SHELLBOOK_REF:-} ]]; then runuser -u shellbook -- git -C /opt/shellbook checkout "$SHELLBOOK_REF"; fi
|
||||
git_app() { runuser -u shellbook -- git -C /opt/shellbook "$@"; }
|
||||
if [[ -n ${SHELLBOOK_REF:-} ]]; then git_app fetch --tags origin; git_app checkout "$SHELLBOOK_REF"; fi
|
||||
if git_app symbolic-ref -q HEAD >/dev/null; then git_app pull --ff-only
|
||||
else echo "Not pulling: /opt/shellbook is pinned to $(git_app rev-parse --short HEAD) (SHELLBOOK_REF)"; fi
|
||||
runuser -u shellbook -- bash -c 'cd /opt/shellbook; pnpm install --frozen-lockfile; pnpm build'
|
||||
workspace=/home/shellbook/workspace
|
||||
install -d -o shellbook -g shellbook "$workspace"
|
||||
@@ -53,6 +59,22 @@ if [[ -z $(find "$workspace" -mindepth 1 -maxdepth 1 -print -quit) ]]; then
|
||||
chown -R shellbook:shellbook "$workspace"
|
||||
runuser -u shellbook -- git -C "$workspace" init
|
||||
fi
|
||||
# Offer each shipped notebook template once: updates bring new templates into existing
|
||||
# workspaces, but never overwrite files or bring back ones the user deleted. The copy runs
|
||||
# as the service user, so links inside the workspace cannot redirect a root write.
|
||||
offer_templates() { # <templates dir> <workspace> <offered list>
|
||||
local file rel
|
||||
touch "$3"
|
||||
[[ -d $1/notebooks ]] || return 0
|
||||
while IFS= read -r -d '' file; do
|
||||
rel=${file#"$1"/}
|
||||
grep -qxF -- "$rel" "$3" && continue
|
||||
runuser -u shellbook -- bash -c 'test -e "$2" || test -L "$2" || install -D -m 644 "$1" "$2"' _ "$file" "$2/$rel"
|
||||
printf '%s\n' "$rel" >> "$3"
|
||||
done < <(find "$1/notebooks" -type f -name '*.md' -print0 | sort -z)
|
||||
}
|
||||
install -d -m 0750 /etc/shellbook
|
||||
offer_templates /opt/shellbook/templates/workspace "$workspace" /etc/shellbook/templates-offered
|
||||
if [[ ! -f /home/shellbook/.ssh/id_ed25519 ]]; then
|
||||
runuser -u shellbook -- ssh-keygen -q -t ed25519 -N '' -f /home/shellbook/.ssh/id_ed25519 -C shellbook
|
||||
fi
|
||||
@@ -60,6 +82,27 @@ if [[ ! -x /home/shellbook/.local/bin/claude ]]; then
|
||||
runuser -u shellbook -- env HOME=/home/shellbook bash -o pipefail -c 'curl -fsSL https://claude.ai/install.sh | bash'
|
||||
fi
|
||||
install -d -m 0750 /etc/shellbook
|
||||
# Where `shellbook-update` fetches the installer; remembered across updates.
|
||||
installer_url=${SHELLBOOK_INSTALLER_URL:-$(cat /etc/shellbook/installer-url 2>/dev/null || echo https://git.finalfactory.de/FinalFactory/ShellBook/raw/branch/main/deploy/install.sh)}
|
||||
[[ $installer_url =~ ^(https|file)://[^[:space:]]+$ ]] || { echo 'Invalid SHELLBOOK_INSTALLER_URL' >&2; exit 1; }
|
||||
printf '%s\n' "$installer_url" > /etc/shellbook/installer-url
|
||||
# Root must never execute code from /opt/shellbook: the service user (and its
|
||||
# terminal panel) can write there. The updater runs the installer from the repository.
|
||||
cat > /usr/local/sbin/shellbook-update <<'EOF'
|
||||
#!/usr/bin/env bash
|
||||
# Updates ShellBook: reruns the installer fetched from the repository.
|
||||
set -euo pipefail
|
||||
[[ $EUID == 0 ]] || { echo 'Run as root' >&2; exit 1; }
|
||||
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
|
||||
url=${SHELLBOOK_INSTALLER_URL:-$(cat /etc/shellbook/installer-url)}
|
||||
installer=$(mktemp)
|
||||
trap 'rm -f -- "$installer"' EXIT
|
||||
curl -fsSL "$url" -o "$installer"
|
||||
[[ $(head -n1 "$installer") == '#!/usr/bin/env bash' ]] || { echo "Not an installer: $url" >&2; exit 1; }
|
||||
cd /
|
||||
bash "$installer"
|
||||
EOF
|
||||
chmod 0755 /usr/local/sbin/shellbook-update
|
||||
if [[ ! -f /etc/shellbook/env ]]; then
|
||||
host=${SHELLBOOK_HOST:-0.0.0.0}
|
||||
port=${SHELLBOOK_PORT:-8080}
|
||||
@@ -77,6 +120,33 @@ PATH=/home/shellbook/.local/bin:/usr/local/bin:/usr/bin:/bin
|
||||
EOF
|
||||
fi
|
||||
chmod 600 /etc/shellbook/env
|
||||
# Updates from the web UI (#15). The service stays unprivileged and may only change a
|
||||
# request file in its data directory; systemd then runs the fixed root-owned updater
|
||||
# above. Its output goes to root-owned /var/log, readable by the service.
|
||||
data_dir=$(sed -n 's/^SHELLBOOK_DATA_DIR=//p' /etc/shellbook/env)
|
||||
[[ $data_dir =~ ^/[A-Za-z0-9._/-]+$ ]] || { echo 'Invalid SHELLBOOK_DATA_DIR' >&2; exit 1; }
|
||||
cat > /etc/systemd/system/shellbook-update.service <<'EOF'
|
||||
[Unit]
|
||||
Description=Update ShellBook (requested from the web UI)
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/usr/local/sbin/shellbook-update
|
||||
StandardOutput=truncate:/var/log/shellbook-update.log
|
||||
StandardError=inherit
|
||||
TimeoutStartSec=30min
|
||||
EOF
|
||||
cat > /etc/systemd/system/shellbook-update.path <<EOF
|
||||
[Unit]
|
||||
Description=Start a ShellBook update when the web UI requests one
|
||||
|
||||
[Path]
|
||||
PathChanged=$data_dir/update-request
|
||||
Unit=shellbook-update.service
|
||||
|
||||
[Install]
|
||||
WantedBy=paths.target
|
||||
EOF
|
||||
cat > /etc/systemd/system/shellbook.service <<'EOF'
|
||||
[Unit]
|
||||
Description=ShellBook runbook server
|
||||
@@ -119,15 +189,30 @@ if [[ -n ${TS_AUTHKEY:-} ]]; then
|
||||
fi
|
||||
systemctl daemon-reload
|
||||
systemctl enable shellbook
|
||||
systemctl enable --now shellbook-update.path
|
||||
systemctl restart shellbook
|
||||
cat <<'EOF'
|
||||
Next steps:
|
||||
1. Set the password (hidden prompt):
|
||||
runuser -u shellbook -- env SHELLBOOK_DATA_DIR=/var/lib/shellbook node /opt/shellbook/apps/server/dist/cli/set-password.js
|
||||
2. Log into Claude as the service user:
|
||||
runuser -l shellbook -c '/home/shellbook/.local/bin/claude'
|
||||
Then use /login.
|
||||
3. Authorize this public SSH key on managed servers:
|
||||
EOF
|
||||
# Wait until the server answers before reporting success.
|
||||
listen_host=$(sed -n 's/^SHELLBOOK_HOST=//p' /etc/shellbook/env)
|
||||
listen_port=$(sed -n 's/^SHELLBOOK_PORT=//p' /etc/shellbook/env)
|
||||
case ${listen_host:-0.0.0.0} in 0.0.0.0|::|'[::]') probe=127.0.0.1 ;; *:*) probe="[$listen_host]" ;; *) probe=$listen_host ;; esac
|
||||
for ((attempt=0; attempt<60; attempt++)); do
|
||||
if curl -fsS "http://$probe:${listen_port:-8080}/api/health" >/dev/null 2>&1; then break; fi
|
||||
sleep 1
|
||||
done
|
||||
curl -fsS "http://$probe:${listen_port:-8080}/api/health" >/dev/null 2>&1 || {
|
||||
echo 'ShellBook did not start; see: journalctl -u shellbook -n 50' >&2; exit 1;
|
||||
}
|
||||
address=$(hostname -I 2>/dev/null | awk '{print $1}')
|
||||
echo
|
||||
echo "ShellBook $(git_app describe --always --dirty) is running: http://${address:-<container-ip>}:${listen_port:-8080}"
|
||||
if [[ -f /var/lib/shellbook/setup-token ]]; then
|
||||
echo "First-time setup token (one-time, deleted after setup): $(cat /var/lib/shellbook/setup-token)"
|
||||
echo 'Enter it in the browser together with your new password.'
|
||||
fi
|
||||
if [[ ! -f /home/shellbook/.claude/.credentials.json ]]; then
|
||||
echo 'Claude is not logged in yet: Settings > "Open terminal to log in", then /login.'
|
||||
fi
|
||||
echo "ShellBook's SSH public key (the Hosts page can install it on your servers):"
|
||||
cat /home/shellbook/.ssh/id_ed25519.pub
|
||||
echo '4. Configure Traefik, trusted proxy IPs and the LAN/Tailscale firewall; see deploy/README.md.'
|
||||
echo 'Update later with: shellbook-update (from the Proxmox host: pct exec <ctid> -- shellbook-update)'
|
||||
echo 'Behind Traefik: see deploy/README.md for the proxy and firewall settings.'
|
||||
|
||||
Executable
+15
@@ -0,0 +1,15 @@
|
||||
#!/usr/bin/env bash
|
||||
# Install or update ShellBook in a Proxmox CT in one step, leaving nothing on the host.
|
||||
# Run on the Proxmox host as root:
|
||||
# bash -c "$(curl -fsSL https://git.finalfactory.de/FinalFactory/ShellBook/raw/branch/main/deploy/proxmox/bootstrap.sh)"
|
||||
# Accepts the overrides of create-ct.sh (CTID, CT_*, SHELLBOOK_*, TS_AUTHKEY).
|
||||
# The repository is unpacked into a temporary directory that is always removed.
|
||||
set -euo pipefail
|
||||
[[ $EUID == 0 ]] && command -v pct >/dev/null || { echo 'Run on the Proxmox host as root' >&2; exit 1; }
|
||||
archive=${SHELLBOOK_ARCHIVE_URL:-https://git.finalfactory.de/FinalFactory/ShellBook/archive/${SHELLBOOK_REF:-main}.tar.gz}
|
||||
work=$(mktemp -d)
|
||||
trap 'rm -rf -- "$work"' EXIT
|
||||
curl -fsSL "$archive" | tar -xz -C "$work" --strip-components=1 --no-same-owner
|
||||
[[ -f $work/deploy/proxmox/create-ct.sh ]] || { echo "No ShellBook deploy scripts in $archive" >&2; exit 1; }
|
||||
# stdin stays away from pct exec: callers may pipe this script into bash.
|
||||
bash "$work/deploy/proxmox/create-ct.sh" </dev/null
|
||||
@@ -67,4 +67,5 @@ for key in SHELLBOOK_REPO SHELLBOOK_REF SHELLBOOK_HOST SHELLBOOK_PORT SHELLBOOK_
|
||||
if [[ -v $key ]]; then printf 'export %s=%q\n' "$key" "${!key}" >> "$settings"; fi
|
||||
done
|
||||
pct push "$ctid" "$settings" /root/shellbook-install.env --perms 0600
|
||||
pct exec "$ctid" -- bash -c 'trap "rm -f /root/shellbook-install.env" EXIT; source /root/shellbook-install.env; bash /root/shellbook-install.sh'
|
||||
# Leave no installer files behind in the CT either; later updates use `shellbook-update`.
|
||||
pct exec "$ctid" -- bash -c 'trap "rm -f /root/shellbook-install.env /root/shellbook-install.sh" EXIT; source /root/shellbook-install.env; bash /root/shellbook-install.sh'
|
||||
|
||||
Executable
+40
@@ -0,0 +1,40 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
# Runs bootstrap.sh against a stub `pct` (existing CT 501) and checks that the
|
||||
# host keeps no files and the CT keeps no installer files. Needs root (Linux/Docker).
|
||||
[[ $EUID == 0 ]] || { echo 'bootstrap test skipped: needs root (run it in a Debian container)'; exit 0; }
|
||||
repo=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
|
||||
test_dir=$(mktemp -d)
|
||||
trap 'rm -rf -- "$test_dir"' EXIT
|
||||
mkdir "$test_dir/bin" "$test_dir/tmp" "$test_dir/ct"
|
||||
# Archive of the working tree, shaped like Gitea's (one top-level folder).
|
||||
tar -C "$repo/.." -czf "$test_dir/archive.tar.gz" --exclude=node_modules --exclude=.git "$(basename "$repo")/deploy"
|
||||
cat > "$test_dir/bin/pct" <<'STUB'
|
||||
#!/usr/bin/env bash
|
||||
log=$STUB_DIR/pct.log; ct=$STUB_DIR/ct
|
||||
echo "$*" >> "$log"
|
||||
case $1 in
|
||||
config) printf 'arch: amd64\nfeatures: nesting=1\nostype: debian\nunprivileged: 1\nlxc.mount.entry: /dev/net/tun dev/net/tun none bind,create=file\n' ;;
|
||||
status) echo 'status: running' ;;
|
||||
start|set|shutdown) ;;
|
||||
push) cp "$3" "$ct/$(basename "$4")" ;;
|
||||
exec)
|
||||
shift 3
|
||||
if [[ $1 == dpkg ]]; then echo amd64
|
||||
elif [[ $1 == bash && $2 == -c ]]; then
|
||||
# Run the real cleanup wrapper with /root mapped into the fake CT.
|
||||
script=${3//\/root\//$ct/}; script=${script//bash $ct\/shellbook-install.sh/echo installer-ran}
|
||||
bash -c "$script"
|
||||
fi ;;
|
||||
esac
|
||||
STUB
|
||||
printf '#!/usr/bin/env bash\necho amd64\n' > "$test_dir/bin/dpkg"
|
||||
chmod +x "$test_dir/bin/pct" "$test_dir/bin/dpkg"
|
||||
out=$(PATH="$test_dir/bin:$PATH" STUB_DIR="$test_dir" TMPDIR="$test_dir/tmp" CTID=501 SHELLBOOK_ARCHIVE_URL="file://$test_dir/archive.tar.gz" \
|
||||
bash "$repo/deploy/proxmox/bootstrap.sh")
|
||||
[[ $out == *installer-ran* ]] || { echo "installer did not run: $out" >&2; exit 1; }
|
||||
[[ -z $(ls -A "$test_dir/tmp") ]] || { echo "host temp files left: $(ls -A "$test_dir/tmp")" >&2; exit 1; }
|
||||
[[ -z $(ls -A "$test_dir/ct") ]] || { echo "CT files left: $(ls -A "$test_dir/ct")" >&2; exit 1; }
|
||||
grep -q '^push 501 .*/install.sh /root/shellbook-install.sh' "$test_dir/pct.log" || { echo 'installer not pushed' >&2; exit 1; }
|
||||
! grep -q -- '--dev0' "$test_dir/pct.log" || { echo 'dev0 added despite TUN mount' >&2; exit 1; }
|
||||
printf '5 bootstrap checks passed\n'
|
||||
@@ -3,12 +3,51 @@ set -euo pipefail
|
||||
# Static guards for regressions seen on a real Proxmox deploy (full run needs Debian 13 as root).
|
||||
dir="$(dirname "${BASH_SOURCE[0]}")/.."
|
||||
path_line='export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
|
||||
for script in install.sh update.sh; do
|
||||
# pct exec omits /usr/local/bin: PATH must be set before the first command that needs node/pnpm.
|
||||
first_path=$(grep -nxF "$path_line" "$dir/$script" | head -n1 | cut -d: -f1)
|
||||
first_use=$(grep -nE '\b(node|pnpm|npm|corepack)\b' "$dir/$script" | grep -v '^[0-9]*:#' | head -n1 | cut -d: -f1)
|
||||
[[ -n $first_path && $first_path -lt $first_use ]] || { echo "$script: PATH not set before node/pnpm use" >&2; exit 1; }
|
||||
done
|
||||
# pct exec omits /usr/local/bin: PATH must be set before the first command that needs node/pnpm.
|
||||
first_path=$(grep -nxF "$path_line" "$dir/install.sh" | head -n1 | cut -d: -f1)
|
||||
first_use=$(grep -nE '\b(node|pnpm|npm|corepack)\b' "$dir/install.sh" | grep -v '^[0-9]*:#' | head -n1 | cut -d: -f1)
|
||||
[[ -n $first_path && $first_path -lt $first_use ]] || { echo 'install.sh: PATH not set before node/pnpm use' >&2; exit 1; }
|
||||
# Node tarball must not hand /usr/local to the archive's uid.
|
||||
grep -qE '^tar --no-same-owner .*node_file' "$dir/install.sh" || { echo 'install.sh: tar keeps archive owners' >&2; exit 1; }
|
||||
printf '3 install script checks passed\n'
|
||||
# The root-run updater must not execute anything from the service-user-writable checkout.
|
||||
updater=$(sed -n "/^cat > \/usr\/local\/sbin\/shellbook-update <<'EOF'$/,/^EOF$/p" "$dir/install.sh" | sed '1d;$d')
|
||||
[[ -n $updater ]] || { echo 'install.sh: shellbook-update not generated' >&2; exit 1; }
|
||||
bash -n <<< "$updater" || { echo 'shellbook-update: syntax error' >&2; exit 1; }
|
||||
[[ $updater != */opt/shellbook* ]] || { echo 'shellbook-update: references /opt/shellbook' >&2; exit 1; }
|
||||
[[ $updater == *"$path_line"* ]] || { echo 'shellbook-update: PATH not set' >&2; exit 1; }
|
||||
# An existing checkout must be updated, not just rebuilt.
|
||||
grep -q 'git_app pull --ff-only' "$dir/install.sh" || { echo 'install.sh: existing checkout is not pulled' >&2; exit 1; }
|
||||
# Nothing may remain in the CT's /root after the Proxmox install.
|
||||
grep -q 'rm -f /root/shellbook-install.env /root/shellbook-install.sh' "$dir/proxmox/create-ct.sh" \
|
||||
|| { echo 'create-ct.sh: installer files left in the CT' >&2; exit 1; }
|
||||
# Templates: new ones reach existing workspaces once; existing and deleted files stay as they are.
|
||||
offer=$(sed -n '/^offer_templates() {/,/^}$/p' "$dir/install.sh")
|
||||
[[ -n $offer ]] || { echo 'install.sh: offer_templates missing' >&2; exit 1; }
|
||||
tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT
|
||||
(
|
||||
runuser() { shift 3; "$@"; } # stub: run as the current user
|
||||
eval "$offer"
|
||||
mkdir -p "$tmp/t/notebooks/infra" "$tmp/w/notebooks"
|
||||
printf 'new\n' > "$tmp/t/notebooks/infra/lxc.md"; printf 'shipped\n' > "$tmp/t/notebooks/a.md"
|
||||
printf 'mine\n' > "$tmp/w/notebooks/a.md"
|
||||
offer_templates "$tmp/t" "$tmp/w" "$tmp/offered"
|
||||
[[ $(cat "$tmp/w/notebooks/a.md") == mine && $(cat "$tmp/w/notebooks/infra/lxc.md") == new ]] || { echo 'offer_templates: wrong copy' >&2; exit 1; }
|
||||
rm "$tmp/w/notebooks/infra/lxc.md"
|
||||
offer_templates "$tmp/t" "$tmp/w" "$tmp/offered"
|
||||
[[ ! -e $tmp/w/notebooks/infra/lxc.md ]] || { echo 'offer_templates: deleted template came back' >&2; exit 1; }
|
||||
[[ $(sort "$tmp/offered" | tr '\n' ' ') == 'notebooks/a.md notebooks/infra/lxc.md ' ]] || { echo 'offer_templates: wrong list' >&2; exit 1; }
|
||||
)
|
||||
# Updates from the web UI: the service only touches a request file; root runs the fixed updater.
|
||||
unit_body() { sed -n "/^cat > \/etc\/systemd\/system\/$1 <<'\{0,1\}EOF'\{0,1\}$/,/^EOF$/p" "$dir/install.sh" | sed '1d;$d'; }
|
||||
update_service=$(unit_body shellbook-update.service)
|
||||
update_path=$(unit_body shellbook-update.path)
|
||||
[[ -n $update_service && -n $update_path ]] || { echo 'install.sh: update units not generated' >&2; exit 1; }
|
||||
grep -qxF 'ExecStart=/usr/local/sbin/shellbook-update' <<< "$update_service" || { echo 'update unit: wrong ExecStart' >&2; exit 1; }
|
||||
grep -qxF 'Type=oneshot' <<< "$update_service" || { echo 'update unit: not oneshot' >&2; exit 1; }
|
||||
[[ $update_service$update_path != */opt/shellbook* ]] || { echo 'update units: reference /opt/shellbook' >&2; exit 1; }
|
||||
# Root writes its output only below root-owned /var/log, never into the service user's data dir.
|
||||
grep -qxF 'StandardOutput=truncate:/var/log/shellbook-update.log' <<< "$update_service" || { echo 'update unit: log not in /var/log' >&2; exit 1; }
|
||||
grep -qxF 'PathChanged=$data_dir/update-request' <<< "$update_path" || { echo 'update path unit: wrong request file' >&2; exit 1; }
|
||||
grep -qxF 'Unit=shellbook-update.service' <<< "$update_path" || { echo 'update path unit: wrong unit' >&2; exit 1; }
|
||||
grep -qxF 'systemctl enable --now shellbook-update.path' "$dir/install.sh" || { echo 'install.sh: update trigger not enabled' >&2; exit 1; }
|
||||
printf '17 install script checks passed\n'
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
[[ $EUID == 0 ]] || { echo 'Run as root' >&2; exit 1; }
|
||||
# `pct exec` omits /usr/local/bin, where Node and pnpm live.
|
||||
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
|
||||
runuser -u shellbook -- bash -c 'cd /opt/shellbook; git pull --ff-only; pnpm install --frozen-lockfile; pnpm build'
|
||||
systemctl restart shellbook
|
||||
systemctl --no-pager status shellbook
|
||||
+169
-15
@@ -5,7 +5,7 @@ A notebook is a Markdown file: prose plus shell blocks. The shell is the primary
|
||||
artifact — always shown literally, with parameter values filled in, copyable into
|
||||
any terminal. ShellBook adds buttons around it: run on a host over SSH, check a
|
||||
condition, download a produced file. Claude Code (the real CLI, subscription
|
||||
login) runs in a built-in terminal and edits the notebooks.
|
||||
login) runs behind chat or in a built-in terminal and edits the notebooks.
|
||||
|
||||
## 1. Goals
|
||||
|
||||
@@ -28,7 +28,7 @@ programs inside run blocks (use the terminal panel for those).
|
||||
- **Workspace**: a git repo with the user's data, separate from the app code:
|
||||
`notebooks/*.md`, `hosts.yaml`, `CLAUDE.md` (format guide for Claude, shipped by ShellBook).
|
||||
- **Host**: an entry in `hosts.yaml` (`name`, `address`, `user`, `port`, optional `tags`).
|
||||
ShellBook connects with its own SSH key.
|
||||
Authentication is chosen per host in the Servers & SSH page (see ?4.1).
|
||||
- **Step**: a fenced block with a ShellBook attribute set. Kinds: `run`, `check`.
|
||||
- **Run record**: one execution of a step (host, rendered script, output, exit code,
|
||||
artifacts, timestamp). Appended to the audit log.
|
||||
@@ -93,7 +93,11 @@ Download the private key above, then save it:
|
||||
- **Substitution in scripts is shell-safe**: the value is inserted shell-quoted when it
|
||||
contains anything outside `[A-Za-z0-9._/@:=+-]`. The displayed script and the executed
|
||||
script are the same string. One function does this (`core/shellQuote`), nowhere else.
|
||||
- A step with a missing required param shows the script with `{{name}}` highlighted and a disabled Run button.
|
||||
- A step needs exactly the values it uses: every param and runtime value it references, and
|
||||
the required secrets its script reads as `$NAME`/`${NAME}`. While one is missing the script
|
||||
shows `{{name}}` highlighted and Run is disabled. Required params the step does not use never
|
||||
block it, so a guided notebook (§3.7) runs its first steps before later values are entered.
|
||||
Set secrets of the step's notebook are always validated, because all are passed as env vars.
|
||||
|
||||
### 3.3 Step attributes
|
||||
|
||||
@@ -118,21 +122,122 @@ Info string: `sh {<kind> key=value key="value with spaces" flag}`. Language `sh`
|
||||
`:::after{step=<id>}` … `:::` — rendered only after that step succeeded in the
|
||||
current session. `:::after{step=<id> failed}` for the failure case. (remark-directive syntax.)
|
||||
|
||||
`:::when{param=a,b}` … `:::` — shown, and its steps runnable, only while the `choice` (or
|
||||
other non-secret) parameter has one of the listed values. The server refuses to run a
|
||||
step inside an inactive section. Values must be options of a `choice` parameter.
|
||||
|
||||
### 3.5 Artifacts
|
||||
|
||||
Each `on=local` run gets a fresh workdir under `data/runs/<run-id>/`. Artifacts are kept
|
||||
for 24 h (configurable), then deleted. Private keys are flagged sensitive: one download
|
||||
only, then removed.
|
||||
|
||||
### 3.6 Chained notebooks
|
||||
|
||||
A notebook can include another one and continue with what it produced, e.g. a service
|
||||
notebook that first creates an LXC container:
|
||||
|
||||
```markdown
|
||||
:::when{target=lxc}
|
||||
::use{notebook="infra/lxc-container.md" as=ct with="hostname={{server_name}}"}
|
||||
:::
|
||||
```
|
||||
|
||||
- `::use{notebook="dir/name.md" as=alias with="p={{x}}, q=1"}` — path relative to
|
||||
`notebooks/`, no `..`. The server composes the notebook (core `composeNotebook`):
|
||||
the included params, step ids, captures and templates are namespaced by the alias
|
||||
(`ct.hostname`, `ct.create`, `{{ct.address}}`) and shown inline as a collapsible
|
||||
section with its own parameter group. Nested includes chain aliases (`svc.ct.x`); at
|
||||
most 4 levels. Missing files, cycles and errors inside the included notebook are
|
||||
errors on the `::use` line. The UI reloads when an included file changes.
|
||||
- `with` sets defaults of the included params, written in the including notebook's
|
||||
namespace. Secrets cannot be bound; they are entered in the form and passed only to
|
||||
steps of their own notebook, under their local name (`$ROOTPW`).
|
||||
- Steps are gated only by the values they use (§3.2); an included notebook's empty form
|
||||
never blocks the parent's steps unless they reference its values.
|
||||
- Non-secret defaults may reference captures and builtins (`default: "{{ct.host}}"`). Until
|
||||
the value exists the field shows "Available after the step that sets ct.host". Only
|
||||
steps that reference such a param wait for it.
|
||||
- `::host{name="{{hostname}}" address="{{address}}" user=root port=22 capture=host}` adds
|
||||
the machine to Hosts (same validation as the Hosts page; never overwrites a different
|
||||
host with that name). `capture` stores the host name as a runtime value so later
|
||||
steps can target it. The first SSH connection still requires host key confirmation.
|
||||
- Builtins are server-provided runtime values, never namespaced:
|
||||
`{{shellbook.public_key}}` is ShellBook's SSH public key. The server sets them on every
|
||||
run; client-sent values are ignored.
|
||||
|
||||
### 3.7 Guided text: parameter fields and groups
|
||||
|
||||
Authors can ask for each value where the text explains it:
|
||||
|
||||
```markdown
|
||||
:::group{title="1. Network" collapsed}
|
||||
Pick the bridge the container joins:
|
||||
|
||||
::param{name=bridge}
|
||||
:::
|
||||
```
|
||||
|
||||
- `::param{name=x}` on its own line shows the input of the declared parameter `x` at that
|
||||
point. It is bound to the same value as the parameter panel, which still lists every
|
||||
parameter. Inside an included notebook the name is namespaced like everything else.
|
||||
- `:::group{title="…" collapsed}` … `:::` is a titled, collapsible container for any
|
||||
blocks, including nested groups. `collapsed` starts it closed; the user's choice is
|
||||
remembered per notebook. The title may use `{{name}}` like prose. Groups are purely
|
||||
presentational: unlike `:::when` they never hide or block steps.
|
||||
- A group's **inputs** are its `::param` fields, the parameters its steps and `::host`
|
||||
blocks reference (those are needed: the step cannot run without them) and, for a
|
||||
`::use` section, the included notebook's parameters. Inactive `:::when` sections and
|
||||
runtime values are ignored. Core `groupInputs` computes the status, shown as the outline
|
||||
color and in words: orange (missing) while a required or needed input is empty or a
|
||||
value is invalid, green (filled) when every input has a value, grey (optional) when
|
||||
only optional inputs are empty or there are none.
|
||||
- Included notebooks (`::use`) are shown as groups with the same status, so a reusable
|
||||
group is a notebook included where it is needed.
|
||||
|
||||
## 4. Execution
|
||||
|
||||
- Scripts run as `bash -euo pipefail -s` with the script on stdin; no TTY.
|
||||
- SSH via `ssh2`, ShellBook's own key, **strict host key checking**. Unknown host key →
|
||||
- SSH via `ssh2`, per-host authentication, **strict host key checking**. Unknown host key →
|
||||
UI shows the fingerprint and asks once (TOFU), then stored in the workspace's `known_hosts`.
|
||||
- Output is streamed to the browser over WebSocket (stdout/stderr interleaved, with exit code).
|
||||
- Every run is appended to `data/audit.jsonl`: time, notebook, step id, host, rendered script, exit code, duration. Secrets never appear.
|
||||
- One step per host at a time (queue); different hosts in parallel.
|
||||
|
||||
### 4.1 Hosts and SSH credentials
|
||||
|
||||
The Servers & SSH page manages host name, address, user, port and tags without YAML
|
||||
editing. Changes preserve YAML comments/order where practical and use an opaque
|
||||
inventory version; stale writes return 409. Host renames migrate stored credentials;
|
||||
notebook host references remain literal and must be updated by the user. The file
|
||||
watcher publishes `file.changed` / `file.deleted` with path `hosts.yaml`.
|
||||
|
||||
Per-host authentication is ShellBook key (default), password (including non-echoed
|
||||
keyboard-interactive password prompts), or private key with optional passphrase.
|
||||
Paste or upload the key from the browser. ssh2 1.17.0 does not expose client user
|
||||
certificate pairing; the UI explicitly disables OpenSSH certificates. All remote
|
||||
execution, checks, uploads and artifact downloads use the same authenticated client.
|
||||
Strict host key checks and explicit TOFU acceptance remain mandatory.
|
||||
|
||||
Passwords, private keys and passphrases are stored only in the data directory,
|
||||
AES-256-GCM encrypted with random 96-bit nonces and host-name AAD. A random 256-bit
|
||||
key file and credential files have POSIX mode 0600; ciphertext updates use atomic
|
||||
rename. Keep dataDir outside the workspace repository. APIs never return stored
|
||||
secrets: only type, key fingerprint (when applicable), and set-at time. Selecting
|
||||
the default or deleting a host deletes its credential. Credential values join the
|
||||
existing streaming/audit redaction list; host actions discard remote output and
|
||||
return only an exit status or a TOFU fingerprint challenge.
|
||||
|
||||
The page shows the ShellBook public key with Copy, Test connection (`true`),
|
||||
Install ShellBook key, and Forget host key. Installation requires the stored
|
||||
password and previews the literal script; the server rejects a mismatched preview
|
||||
before connecting. It appends the public key idempotently to the remote user's
|
||||
`~/.ssh/authorized_keys`, with all quoting through core `shellQuote`. The password
|
||||
remains selected until the user chooses ShellBook key after successful installation.
|
||||
Forgetting a host key requires UI confirmation and removes only that endpoint,
|
||||
preserving other aliases. All management routes use the existing session and origin
|
||||
checks and responses disable caching.
|
||||
|
||||
## 5. UI
|
||||
|
||||
- **Notebook list** (left), **notebook view** (center), **AI/terminal panel** (right, collapsible).
|
||||
@@ -143,25 +248,74 @@ only, then removed.
|
||||
- Edit mode: raw Markdown in CodeMirror with live preview. Files changed on disk
|
||||
(by Claude or git pull) reload live.
|
||||
|
||||
- Notebook management: searchable folder tree; create with name/folder/title and a
|
||||
valid starter, rename/move, duplicate, and explicitly confirmed delete. Paths are
|
||||
relative to `notebooks/`; folders are created as needed and pruned when empty.
|
||||
- Editor toolbar inserts checks, runs, artifact downloads, uploads, captures and
|
||||
after-step notes at the cursor. A parameter form edits YAML frontmatter through
|
||||
a YAML document parser; format help explains syntax. Targets are local or host
|
||||
parameters. Examples must be reviewed before execution.
|
||||
- Mutations use optimistic versions; occupied destinations or stale versions return
|
||||
409. Atomic file publication and recursive watcher events refresh all tabs. An
|
||||
external rename/delete retains the old open draft with a notice and refreshes
|
||||
the tree; users can select the new path. Unsaved navigation requires confirmation.
|
||||
|
||||
## 6. AI: Claude Code
|
||||
|
||||
- The right panel is a real terminal (xterm.js ↔ node-pty) running `claude` in the
|
||||
workspace, inside `tmux` so the session survives closed tabs and app restarts.
|
||||
This is the genuine CLI with the user's own subscription login — no API key, no SDK.
|
||||
- The workspace ships a `CLAUDE.md` describing this notebook format, so Claude writes
|
||||
shell-first notebooks (literal commands, no wrapper code).
|
||||
- Live reload (§5) makes Claude's edits appear immediately.
|
||||
- Later option: `ANTHROPIC_BASE_URL` / token for a custom endpoint, set in the
|
||||
panel's environment.
|
||||
- The right panel offers chat and a real terminal. Both use the real `claude`
|
||||
CLI with the user's own subscription login; no API key or embedded SDK.
|
||||
- Chat runs one headless CLI process per turn (`-p`, stream-json stdin/stdout),
|
||||
in the workspace, with explicit `--resume` of the CLI session ID. A dedicated,
|
||||
authenticated same-origin `/api/chat` WebSocket streams text deltas, compact
|
||||
tool summaries, completion metadata and safe errors. Disconnect/Stop/timeout
|
||||
terminate the process; only one active turn per conversation is allowed.
|
||||
- File tools are restricted to workspace working directories using CLI restricted
|
||||
mode (Claude Code 2.1.248+). Available tools are Read, Glob, Grep, Edit, Write,
|
||||
MultiEdit; Bash is added only by the off-by-default shell-command toggle. Web
|
||||
and MCP tools are unavailable. Never use bypassPermissions.
|
||||
- The data directory persists conversation titles (first message), session IDs
|
||||
and timestamps, not messages or tool contents. The CLI keeps its own session
|
||||
transcripts. Never send secrets in chat. History resumes CLI context; the web
|
||||
view retains messages only for the lifetime of the mounted panel.
|
||||
- The terminal (xterm.js and node-pty) uses tmux, so interactive sessions survive
|
||||
closed tabs and app restarts. Missing CLI/login errors offer this panel with
|
||||
instructions to run `claude`, then `/login`.
|
||||
- The workspace ships a `CLAUDE.md` describing the notebook format. The chat
|
||||
appends ShellBook context and the open notebook path to the system prompt.
|
||||
Live reload (section 5) makes actual notebook edits appear immediately.
|
||||
- Details, resource limits and verified CLI flags: `apps/server/src/chat/README.md`.
|
||||
|
||||
## 7. Security
|
||||
|
||||
- The app can run commands on every host → treat access as root-equivalent.
|
||||
- Built-in login: one password (scrypt hash in config), session cookie signed with a
|
||||
secret persisted on disk → **logins survive restarts**. Optional: trust a
|
||||
forward-auth header from Traefik instead.
|
||||
- Built-in login: one scrypt password hash in `auth.json`; session cookies are HMAC
|
||||
signed with a persisted mode-0600 secret and bound to the current password hash.
|
||||
Logins survive restarts; changing the password invalidates other cookies.
|
||||
- First run creates a random mode-0600 `setup-token` in the data directory. Only its
|
||||
path is logged. Public GET `/api/auth/setup` reports whether setup is needed;
|
||||
POST requires the token (constant-time comparison), matching passwords of at
|
||||
least 12 characters (maximum 4096 bytes), and consumes the token once. Configured
|
||||
instances reject setup with 409. Setup and login share a per-IP rate limit.
|
||||
- Settings changes require the current password, or atomically rotate the signing
|
||||
secret to sign out all sessions. Both issue a fresh cookie to the current browser
|
||||
and close existing WebSockets; future connections must authenticate again.
|
||||
Forward-auth identities remain governed by the upstream proxy.
|
||||
- Every API route is authenticated except exact health, login, and setup paths;
|
||||
the origin check also covers those exceptions and WebSocket upgrades.
|
||||
Optional forward-auth headers are accepted only from configured trusted peers.
|
||||
- Claude status executes only `claude --version` with argv, timeout, and output limit.
|
||||
Login status checks only the existence of `~/.claude/.credentials.json` under the
|
||||
service user home; credential contents are never read or returned.
|
||||
- Listens on `127.0.0.1` or LAN; intended behind Traefik + firewall (LAN/Tailscale only).
|
||||
- Terminal panel = shell as the service user: same trust level as the app itself.
|
||||
- Self-update from Settings never gives the service privileges: POST
|
||||
`/api/settings/update` only writes `<data dir>/update-request`. A root-owned systemd
|
||||
path unit starts the oneshot `shellbook-update.service`, which runs the fixed
|
||||
root-owned `/usr/local/sbin/shellbook-update` (it fetches the installer from the
|
||||
repository and never executes the service-writable checkout) and writes its output
|
||||
to `/var/log/shellbook-update.log`. The server reads state only through
|
||||
`systemctl show` and that log; "check for updates" runs `git fetch` into
|
||||
`FETCH_HEAD` only. A request can only start that fixed updater, nothing else.
|
||||
- No secrets in notebooks, audit log or artifacts metadata.
|
||||
|
||||
## 8. Architecture
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
// Chained notebooks (`::use`): pure composition. The server loads the files; core only
|
||||
// namespaces and merges them, so display and execution keep using one notebook model.
|
||||
import type { Block, Diagnostic, Notebook, ParamDef, ParamValues, Step } from "./types";
|
||||
import { includePath } from "./parser";
|
||||
|
||||
const template = /\{\{\s*([^{}]+?)\s*\}\}/g;
|
||||
/** Maximum `::use` nesting (root -> a -> b -> c -> d). */
|
||||
export const MAX_INCLUDE_DEPTH = 4;
|
||||
/** Runtime names provided by the server, never namespaced: {{shellbook.public_key}}. */
|
||||
export const isBuiltin = (name: string) => name.startsWith("shellbook.");
|
||||
|
||||
/** Workspace paths a notebook includes directly, in document order. Invalid paths never reach I/O. */
|
||||
export function notebookIncludes(notebook: Notebook): string[] {
|
||||
const paths: string[] = [];
|
||||
const walk = (blocks: Block[]) => {
|
||||
for (const block of blocks) {
|
||||
if (block.type === "use" && !block.blocks.length) { if (includePath(block.path)) paths.push(block.path); }
|
||||
else if (block.type === "after" || block.type === "when" || block.type === "use" || block.type === "group") walk(block.blocks);
|
||||
}
|
||||
};
|
||||
walk(notebook.blocks);
|
||||
return [...new Set(paths)];
|
||||
}
|
||||
|
||||
const qualify = (alias: string, name: string) => `${alias}.${name}`;
|
||||
const rewrite = (text: string, alias: string) =>
|
||||
text.replace(template, (match, name: string) => isBuiltin(name) ? match : `{{${qualify(alias, name)}}}`);
|
||||
const scoped = (alias: string, scope?: string) => scope ? qualify(alias, scope) : alias;
|
||||
|
||||
function prefixStep(step: Step, alias: string): Step {
|
||||
const a = step.attrs;
|
||||
return {
|
||||
...step,
|
||||
script: rewrite(step.script, alias),
|
||||
attrs: {
|
||||
...a,
|
||||
id: qualify(alias, a.id),
|
||||
host: a.host === undefined ? undefined : rewrite(a.host, alias),
|
||||
capture: a.capture === undefined ? undefined : qualify(alias, a.capture),
|
||||
artifacts: a.artifacts.map(x => rewrite(x, alias)),
|
||||
uploads: a.uploads.map(u => ({ src: rewrite(u.src, alias), dst: rewrite(u.dst, alias) })),
|
||||
scope: scoped(alias, a.scope),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Namespace a composed notebook's blocks under alias (names, ids, templates, scopes). */
|
||||
function prefixBlocks(blocks: Block[], alias: string): Block[] {
|
||||
return blocks.map((block): Block => {
|
||||
switch (block.type) {
|
||||
case "markdown": return { ...block, text: rewrite(block.text, alias) };
|
||||
case "step": return { type: "step", step: prefixStep(block.step, alias) };
|
||||
case "after": return { ...block, stepId: qualify(alias, block.stepId), blocks: prefixBlocks(block.blocks, alias) };
|
||||
case "when": return { ...block, param: qualify(alias, block.param), blocks: prefixBlocks(block.blocks, alias) };
|
||||
case "use": return { ...block, scope: qualify(alias, block.scope), bindings: {}, blocks: prefixBlocks(block.blocks, alias) };
|
||||
case "group": return { ...block, title: rewrite(block.title, alias), blocks: prefixBlocks(block.blocks, alias) };
|
||||
case "param": return { ...block, name: qualify(alias, block.name) };
|
||||
case "host": return {
|
||||
...block, id: qualify(alias, block.id), scope: scoped(alias, block.scope),
|
||||
name: rewrite(block.name, alias), address: rewrite(block.address, alias),
|
||||
user: rewrite(block.user, alias), port: rewrite(block.port, alias),
|
||||
capture: block.capture === undefined ? undefined : qualify(alias, block.capture),
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function prefixParam(def: ParamDef, alias: string): ParamDef {
|
||||
return {
|
||||
...def,
|
||||
name: qualify(alias, def.name),
|
||||
default: def.default === undefined ? undefined : rewrite(def.default, alias),
|
||||
scope: scoped(alias, def.scope),
|
||||
};
|
||||
}
|
||||
|
||||
/** Every step and host id in composed blocks (for duplicate detection). */
|
||||
function blockIds(blocks: Block[], into: string[] = []): string[] {
|
||||
for (const block of blocks) {
|
||||
if (block.type === "step") into.push(block.step.attrs.id);
|
||||
else if (block.type === "host") into.push(block.id);
|
||||
else if ("blocks" in block) blockIds(block.blocks, into);
|
||||
}
|
||||
return into;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve `::use` blocks: the included notebook's params, steps, captures and ids are
|
||||
* namespaced by its alias ("ct.hostname") and merged into one notebook. `with` bindings
|
||||
* become the included params' defaults in the including notebook's namespace.
|
||||
* Missing files, cycles, nesting deeper than MAX_INCLUDE_DEPTH and errors inside an
|
||||
* included notebook become error diagnostics on the `::use` line.
|
||||
*/
|
||||
export function composeNotebook(path: string, notebook: Notebook, load: (path: string) => Notebook | undefined): Notebook {
|
||||
return compose(path, notebook, load, [path]);
|
||||
}
|
||||
|
||||
function compose(path: string, notebook: Notebook, load: (path: string) => Notebook | undefined, stack: string[]): Notebook {
|
||||
const diagnostics: Diagnostic[] = [...notebook.diagnostics];
|
||||
const params: ParamDef[] = [...notebook.params];
|
||||
const fail = (message: string, line: number) => diagnostics.push({ severity: "error", message, line });
|
||||
const resolve = (blocks: Block[]): Block[] => blocks.map((block): Block => {
|
||||
if (block.type === "after" || block.type === "when" || block.type === "group") return { ...block, blocks: resolve(block.blocks) };
|
||||
if (block.type !== "use") return block;
|
||||
const line = block.range.startLine;
|
||||
// The parser already reported an invalid path; never hand it to the loader.
|
||||
if (!includePath(block.path)) return block;
|
||||
if (stack.includes(block.path)) { fail(`Notebook include cycle: ${[...stack, block.path].join(" -> ")}`, line); return block; }
|
||||
if (stack.length > MAX_INCLUDE_DEPTH) { fail(`Notebook includes are nested deeper than ${MAX_INCLUDE_DEPTH}`, line); return block; }
|
||||
const loaded = load(block.path);
|
||||
if (!loaded) { fail(`Included notebook not found: ${block.path}`, line); return block; }
|
||||
const child = compose(block.path, loaded, load, [...stack, block.path]);
|
||||
for (const d of child.diagnostics) if (d.severity === "error") fail(`${block.path}${d.line ? `:${d.line}` : ""}: ${d.message}`, line);
|
||||
const alias = block.scope;
|
||||
for (const [name, value] of Object.entries(block.bindings)) {
|
||||
const def = child.params.find(p => p.name === name && !p.scope);
|
||||
if (!def) fail(`with binds unknown parameter of ${block.path}: ${name}`, line);
|
||||
else if (def.type === "secret") fail(`with cannot bind secret ${name}; enter it in the form`, line);
|
||||
}
|
||||
for (const def of child.params) {
|
||||
const prefixed = prefixParam(def, alias);
|
||||
// Bindings are templates in the including notebook's namespace: not rewritten.
|
||||
if (!def.scope && def.type !== "secret" && Object.hasOwn(block.bindings, def.name)) prefixed.default = block.bindings[def.name];
|
||||
params.push(prefixed);
|
||||
}
|
||||
return { ...block, title: child.title, bindings: { ...block.bindings }, blocks: prefixBlocks(child.blocks, alias) };
|
||||
});
|
||||
const blocks = resolve(notebook.blocks);
|
||||
const seen = new Set<string>();
|
||||
for (const id of blockIds(blocks)) {
|
||||
if (seen.has(id) && id.includes(".")) fail(`Duplicate step id after including notebooks: ${id}`, 1);
|
||||
seen.add(id);
|
||||
}
|
||||
return { ...notebook, params, blocks, diagnostics };
|
||||
}
|
||||
|
||||
/** Find a step anywhere in the block tree (after, when, use and group containers). */
|
||||
export function findStep(blocks: Block[], id: string): Step | undefined {
|
||||
for (const block of blocks) {
|
||||
if (block.type === "step" && block.step.attrs.id === id) return block.step;
|
||||
if ("blocks" in block) {
|
||||
const found = findStep(block.blocks, id);
|
||||
if (found) return found;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a step or host block is shown and runnable: every enclosing `:::when` must match
|
||||
* the resolved parameter values. `:::after` only gates display, not execution.
|
||||
*/
|
||||
export function blockActive(notebook: Notebook, id: string, values: ParamValues): boolean {
|
||||
const walk = (blocks: Block[], active: boolean): boolean | undefined => {
|
||||
for (const block of blocks) {
|
||||
if (block.type === "step" && block.step.attrs.id === id) return active;
|
||||
if (block.type === "host" && block.id === id) return active;
|
||||
if (block.type === "when") {
|
||||
const found = walk(block.blocks, active && block.values.includes(values[block.param] ?? ""));
|
||||
if (found !== undefined) return found;
|
||||
} else if (block.type === "after" || block.type === "use" || block.type === "group") {
|
||||
const found = walk(block.blocks, active);
|
||||
if (found !== undefined) return found;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
return walk(notebook.blocks, true) ?? false;
|
||||
}
|
||||
|
||||
/** Whether an included notebook's scope ("ct", "svc.ct") is active, i.e. its `::use` lies in matching `:::when` sections. The root scope ("") always is. */
|
||||
export function scopeActive(notebook: Notebook, scope: string, values: ParamValues): boolean {
|
||||
if (!scope) return true;
|
||||
const walk = (blocks: Block[], active: boolean): boolean | undefined => {
|
||||
for (const block of blocks) {
|
||||
if (block.type === "use" && block.scope === scope) return active;
|
||||
if (!("blocks" in block)) continue;
|
||||
const found = walk(block.blocks, active && (block.type !== "when" || block.values.includes(values[block.param] ?? "")));
|
||||
if (found !== undefined) return found;
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
return walk(notebook.blocks, true) ?? false;
|
||||
}
|
||||
|
||||
/** Runtime names that steps or host blocks of the notebook set (`capture=`). */
|
||||
export function captureNames(blocks: Block[], into = new Set<string>()): Set<string> {
|
||||
for (const block of blocks) {
|
||||
if (block.type === "step" && block.step.attrs.capture) into.add(block.step.attrs.capture);
|
||||
else if (block.type === "host" && block.capture) into.add(block.capture);
|
||||
else if ("blocks" in block) captureNames(block.blocks, into);
|
||||
}
|
||||
return into;
|
||||
}
|
||||
+149
-28
@@ -1,8 +1,10 @@
|
||||
// Public API of @shellbook/core. Pure functions, no I/O.
|
||||
import type { Notebook, ParamValues, RenderedStep, Step } from "./types";
|
||||
import type { Block, GroupInputs, Notebook, ParamValues, RenderedHost, RenderedStep, Step } from "./types";
|
||||
import { captureNames, isBuiltin } from "./compose";
|
||||
export type * from "./types";
|
||||
export type * from "./protocol";
|
||||
export { parseNotebook } from "./parser";
|
||||
export { parseNotebook, includePath } from "./parser";
|
||||
export { composeNotebook, notebookIncludes, findStep, blockActive, scopeActive, captureNames, isBuiltin, MAX_INCLUDE_DEPTH } from "./compose";
|
||||
|
||||
const template = /\{\{\s*([^{}]+?)\s*\}\}/g;
|
||||
const own = (object: object, key: string) => Object.hasOwn(object, key);
|
||||
@@ -17,15 +19,20 @@ export function shellQuote(value: string): string {
|
||||
return /^[A-Za-z0-9._/@:=+\-]+$/.test(value) ? value : `'${value.replace(/'/g, "'\\''")}'`;
|
||||
}
|
||||
|
||||
/** Resolve defaults ({{other}} references) and validate all params by type. */
|
||||
/**
|
||||
* Resolve defaults ({{other}} references) and validate all params by type. Defaults may
|
||||
* also reference runtime values (captures such as {{ct.host}}, builtins {{shellbook.*}}).
|
||||
*/
|
||||
export function resolveParams(
|
||||
notebook: Notebook,
|
||||
values: ParamValues,
|
||||
hostNames: readonly string[],
|
||||
runtime: ParamValues = {},
|
||||
): { values: ParamValues; errors: Record<string, string> } {
|
||||
const effective = dictionary();
|
||||
const errors = dictionary();
|
||||
const defs = new Map(notebook.params.map(def => [def.name, def]));
|
||||
const captures = captureNames(notebook.blocks);
|
||||
const active = new Set<string>();
|
||||
const resolve = (name: string): string => {
|
||||
if (own(effective, name)) return effective[name]!;
|
||||
@@ -34,9 +41,14 @@ export function resolveParams(
|
||||
if (active.has(name)) { errors[name] = "Cyclic parameter default"; return ""; }
|
||||
active.add(name);
|
||||
let value = own(values, name) ? values[name] ?? "" : "";
|
||||
let pending = false;
|
||||
if (!value && def.type !== "secret" && def.default !== undefined) {
|
||||
value = def.default.replace(template, (match, ref: string) => {
|
||||
const other = defs.get(ref);
|
||||
if (!other && (captures.has(ref) || isBuiltin(ref))) {
|
||||
if (own(runtime, ref) && runtime[ref]) return runtime[ref]!;
|
||||
errors[name] = `Available after the step that sets ${ref}`; pending = true; return match;
|
||||
}
|
||||
if (!other) { errors[name] = `Unknown default reference: ${ref}`; return match; }
|
||||
if (other.type === "secret") { errors[name] = "Defaults cannot reference secrets"; return match; }
|
||||
const resolved = resolve(ref);
|
||||
@@ -46,6 +58,8 @@ export function resolveParams(
|
||||
});
|
||||
}
|
||||
active.delete(name);
|
||||
// A default still waiting for a captured value is empty, not its literal template.
|
||||
if (pending) value = "";
|
||||
effective[name] = value;
|
||||
if (!value) {
|
||||
if (def.required) errors[name] ??= "Required parameter is missing";
|
||||
@@ -63,6 +77,50 @@ export function resolveParams(
|
||||
return { values: effective, errors };
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared template substitution for steps and host blocks. A block needs exactly the values
|
||||
* it uses (spec §3.6): referenced parameters and runtime values, and for scripts the
|
||||
* required secrets of its scope that the script reads. Required parameters it does not
|
||||
* use never block it, so guided notebooks can run early steps before later values exist.
|
||||
*/
|
||||
function substitution(notebook: Notebook, scope: string | undefined, values: ParamValues, runtime: ParamValues, hostNames: readonly string[]) {
|
||||
const resolved = resolveParams(notebook, values, hostNames, runtime);
|
||||
const captures = captureNames(notebook.blocks);
|
||||
const defs = new Map(notebook.params.map(def => [def.name, def]));
|
||||
const invalid = dictionary();
|
||||
const missing = new Set<string>();
|
||||
const ownSecrets = notebook.params.filter(def => def.type === "secret" && (def.scope ?? "") === (scope ?? ""));
|
||||
// Every set secret of the scope is passed as an env var (secretEnv), so it must be valid.
|
||||
for (const def of ownSecrets)
|
||||
if (resolved.values[def.name] && own(resolved.errors, def.name)) invalid[def.name] = resolved.errors[def.name]!;
|
||||
/** A required secret the script reads as $NAME or ${NAME} (its local name) must be set. */
|
||||
const readsSecrets = (script: string) => {
|
||||
for (const def of ownSecrets) {
|
||||
const local = def.scope ? def.name.slice(def.scope.length + 1) : def.name;
|
||||
if (def.required && !resolved.values[def.name] && new RegExp("\\$\\{?" + local + "(?![A-Za-z0-9_])").test(script))
|
||||
missing.add(def.name);
|
||||
}
|
||||
};
|
||||
const substitute = (text: string, script: boolean): string => text.replace(template, (match, name: string) => {
|
||||
const def = defs.get(name);
|
||||
if (def?.type === "secret") { invalid[name] = "Secrets must be referenced as environment variables"; return match; }
|
||||
if (!def && !own(runtime, name)) {
|
||||
// A capture that has not run yet (or a builtin) is pending, not a typo.
|
||||
if (captures.has(name) || isBuiltin(name)) missing.add(name);
|
||||
else invalid[name] = "Unknown parameter or runtime value";
|
||||
return match;
|
||||
}
|
||||
const value = def ? resolved.values[name] : runtime[name];
|
||||
if (def && own(resolved.errors, name)) invalid[name] = resolved.errors[name]!;
|
||||
if (!value) { missing.add(name); return match; }
|
||||
if (value.includes("\0")) { invalid[name] = "Value cannot contain NUL"; return match; }
|
||||
// Never interpolate values with validation errors into scripts or metadata.
|
||||
if (own(invalid, name)) return match;
|
||||
return script ? shellQuote(value) : value;
|
||||
});
|
||||
return { substitute, readsSecrets, invalid, missing };
|
||||
}
|
||||
|
||||
/**
|
||||
* The single script substitution path: display and execution consume this result.
|
||||
* Attributes use raw substitution and separate validation; secrets are env-only.
|
||||
@@ -74,28 +132,9 @@ export function renderStep(
|
||||
runtime: ParamValues,
|
||||
hostNames: readonly string[],
|
||||
): RenderedStep {
|
||||
const resolved = resolveParams(notebook, values, hostNames);
|
||||
const defs = new Map(notebook.params.map(def => [def.name, def]));
|
||||
const invalid = dictionary();
|
||||
const missing = new Set<string>();
|
||||
for (const def of notebook.params) {
|
||||
if (def.required && !resolved.values[def.name]) missing.add(def.name);
|
||||
if ((def.required || def.type === "secret") && resolved.values[def.name]
|
||||
&& own(resolved.errors, def.name)) invalid[def.name] = resolved.errors[def.name]!;
|
||||
}
|
||||
const substitute = (text: string, script: boolean): string => text.replace(template, (match, name: string) => {
|
||||
const def = defs.get(name);
|
||||
if (def?.type === "secret") { invalid[name] = "Secrets must be referenced as environment variables"; return match; }
|
||||
if (!def && !own(runtime, name)) { invalid[name] = "Unknown parameter or runtime value"; return match; }
|
||||
const value = def ? resolved.values[name] : runtime[name];
|
||||
if (def && own(resolved.errors, name)) invalid[name] = resolved.errors[name]!;
|
||||
if (!value) { missing.add(name); return match; }
|
||||
if (value.includes("\0")) { invalid[name] = "Value cannot contain NUL"; return match; }
|
||||
// Never interpolate values with validation errors into scripts or metadata.
|
||||
if (own(invalid, name)) return match;
|
||||
return script ? shellQuote(value) : value;
|
||||
});
|
||||
const { substitute, readsSecrets, invalid, missing } = substitution(notebook, step.attrs.scope, values, runtime, hostNames);
|
||||
const script = substitute(step.script, true);
|
||||
readsSecrets(step.script);
|
||||
const host = step.attrs.local || step.attrs.host === undefined ? undefined : substitute(step.attrs.host, false);
|
||||
if (!step.attrs.local && (!host || !hostNames.includes(host))) invalid.host ??= "Unknown or missing target host";
|
||||
const plainFile = (name: string) => !!name && !/[\\/\0\r\n]/.test(name) && !name.includes("..");
|
||||
@@ -113,15 +152,97 @@ export function renderStep(
|
||||
return { stepId: step.attrs.id, kind: step.kind, host, local: step.attrs.local, script, artifacts, uploads, missing: [...missing], invalid };
|
||||
}
|
||||
|
||||
/** Resolve a `::host` block with the same rules as hosts.yaml entries. */
|
||||
export function renderHost(
|
||||
notebook: Notebook,
|
||||
block: Extract<Block, { type: "host" }>,
|
||||
values: ParamValues,
|
||||
runtime: ParamValues,
|
||||
hostNames: readonly string[],
|
||||
): RenderedHost {
|
||||
const { substitute, invalid, missing } = substitution(notebook, block.scope, values, runtime, hostNames);
|
||||
const name = substitute(block.name, false), address = substitute(block.address, false);
|
||||
const user = substitute(block.user, false), portText = substitute(block.port, false);
|
||||
const port = Number(portText);
|
||||
if (!/^[A-Za-z0-9._-]+$/.test(name)) invalid.name ??= "Host name may only contain letters, digits, ., _ or -";
|
||||
if (!address || /[\s\0]/.test(address)) invalid.address ??= "Address cannot be empty or contain whitespace";
|
||||
if (!/^[A-Za-z0-9._-]+$/.test(user)) invalid.user ??= "User may only contain letters, digits, ., _ or -";
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) invalid.port ??= "Port must be 1-65535";
|
||||
return { id: block.id, name, address, user, port, missing: [...missing], invalid };
|
||||
}
|
||||
|
||||
/**
|
||||
* Input status of a container block (`:::group`, `::use`; spec §3.7). Its inputs are its
|
||||
* `::param` fields, the parameters its steps and host blocks reference (those are needed:
|
||||
* the step cannot run without them) and, for `::use`, the included notebook's parameters.
|
||||
* Sections of inactive `:::when` blocks are ignored; runtime values are not inputs.
|
||||
*/
|
||||
export function groupInputs(
|
||||
notebook: Notebook,
|
||||
block: Block,
|
||||
values: ParamValues,
|
||||
hostNames: readonly string[],
|
||||
runtime: ParamValues = {},
|
||||
): GroupInputs {
|
||||
const resolved = resolveParams(notebook, values, hostNames, runtime);
|
||||
const defs = new Map(notebook.params.map(def => [def.name, def]));
|
||||
const params: string[] = [];
|
||||
const needed = new Set<string>();
|
||||
const add = (name: string, need: boolean) => {
|
||||
const def = defs.get(name);
|
||||
if (!def) return;
|
||||
if (!params.includes(name)) params.push(name);
|
||||
if (need || def.required) needed.add(name);
|
||||
};
|
||||
const references = (text: string) => { for (const match of text.matchAll(template)) add(match[1]!, true); };
|
||||
const walk = (items: Block[]) => {
|
||||
for (const item of items) {
|
||||
switch (item.type) {
|
||||
case "param": add(item.name, false); break;
|
||||
case "step": {
|
||||
const attrs = item.step.attrs;
|
||||
// In display order: the target first, then the script.
|
||||
if (attrs.host !== undefined) references(attrs.host);
|
||||
references(item.step.script);
|
||||
attrs.artifacts.forEach(references);
|
||||
for (const upload of attrs.uploads) { references(upload.src); references(upload.dst); }
|
||||
break;
|
||||
}
|
||||
case "host": [item.name, item.address, item.user, item.port].forEach(references); break;
|
||||
case "when": if (item.values.includes(resolved.values[item.param] ?? "")) walk(item.blocks); break;
|
||||
case "use":
|
||||
for (const def of notebook.params) if (def.scope === item.scope) add(def.name, false);
|
||||
walk(item.blocks); break;
|
||||
case "after": case "group": walk(item.blocks); break;
|
||||
case "markdown": break;
|
||||
}
|
||||
}
|
||||
};
|
||||
walk([block]);
|
||||
const filled = (name: string) => !!resolved.values[name];
|
||||
const missing = params.filter(name => needed.has(name) && !filled(name));
|
||||
const invalid = params.filter(name => filled(name) && own(resolved.errors, name));
|
||||
const status = missing.length || invalid.length ? "missing"
|
||||
: !params.length ? "none"
|
||||
: params.every(filled) ? "filled" : "optional";
|
||||
return { status, params, missing, invalid };
|
||||
}
|
||||
|
||||
/** Substitute prose without quoting; secrets always appear masked. */
|
||||
export function renderText(text: string, values: ParamValues, notebook: Notebook): string {
|
||||
const secrets = new Set(notebook.params.filter(def => def.type === "secret").map(def => def.name));
|
||||
return text.replace(template, (match, name: string) => secrets.has(name) ? "••••" : own(values, name) ? values[name]! : match);
|
||||
return text.replace(template, (match, name: string) => secrets.has(name) ? "••••" : own(values, name) && values[name] ? values[name]! : match);
|
||||
}
|
||||
|
||||
/** Env vars for a run: every secret param under its exact name. Server-side only. */
|
||||
export function secretEnv(notebook: Notebook, values: ParamValues): Record<string, string> {
|
||||
/**
|
||||
* Env vars for a run: the secrets of the step's scope under their local name
|
||||
* (an included notebook's `ct.TOKEN` is `$TOKEN` in its own steps). Server-side only.
|
||||
*/
|
||||
export function secretEnv(notebook: Notebook, values: ParamValues, scope?: string): Record<string, string> {
|
||||
const env = dictionary();
|
||||
for (const def of notebook.params) if (def.type === "secret" && own(values, def.name)) env[def.name] = values[def.name]!;
|
||||
for (const def of notebook.params) {
|
||||
if (def.type !== "secret" || (def.scope ?? "") !== (scope ?? "") || !own(values, def.name)) continue;
|
||||
env[def.scope ? def.name.slice(def.scope.length + 1) : def.name] = values[def.name]!;
|
||||
}
|
||||
return env;
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user