feat(web): handle one-shot sensitive artifact downloads (#4)
Track sensitive download state per run in the session reducer. Fetch each artifact once into a blob so expired or consumed downloads show HTTP 410 without a separate preflight request. Verify the SSH-key notebook, capture substitution, failure sections and public-key upload provenance through App. Document demo and real terminal workflows.
This commit is contained in:
+68
-19
@@ -1,8 +1,10 @@
|
||||
# ShellBook web
|
||||
# ShellBook web
|
||||
|
||||
From the repository root, install with `npx -y [email protected] install`.
|
||||
Install from the repository root with `npx -y [email protected] install` (Node 22).
|
||||
The viewer, demo and tests all use the real `@shellbook/core` parser and renderer.
|
||||
Scripts are rendered only by core; the server uses the same substitution path.
|
||||
|
||||
PowerShell demo (no server or core implementation required):
|
||||
## Demo without a server
|
||||
|
||||
```powershell
|
||||
$env:VITE_MOCK = '1'
|
||||
@@ -10,26 +12,73 @@ npx -y [email protected] --filter @shellbook/web dev
|
||||
```
|
||||
|
||||
Open the Vite URL (normally http://localhost:5173). Select staging, run the checks
|
||||
(one deliberately fails), generate demo artifacts, and authorize the key to try
|
||||
confirmation. Production demonstrates the **changed host key** warning. No commands
|
||||
execute and downloaded artifacts contain dummy text. Mock frontmatter parameters
|
||||
are fixed to the spec example; body edits preview and save in memory only.
|
||||
(one deliberately fails), generate the SSH key pair, download the dummy private
|
||||
key, then authorize the public key with confirmation. The private key is marked
|
||||
**sensitive · one download** and its link is disabled after download. The authorize
|
||||
request carries the earlier artifacts' run IDs in `artifactSources`.
|
||||
Production demonstrates the changed host key warning. No commands execute;
|
||||
artifacts contain dummy text. The fixture is parsed from `src/mock/ssh-key.md`.
|
||||
Markdown edits (including frontmatter) preview through core and save in memory.
|
||||
The terminal echoes input without opening a WebSocket or running a shell.
|
||||
Never deploy a build made with `VITE_MOCK=1`.
|
||||
|
||||
Normal backend mode:
|
||||
## Real server
|
||||
|
||||
```powershell
|
||||
Remove-Item Env:VITE_MOCK -ErrorAction SilentlyContinue
|
||||
npx -y pnpm@9.15.0 --filter @shellbook/web dev
|
||||
npx -y pnpm@9.15.0 dev
|
||||
```
|
||||
|
||||
Vite proxies `/api`, including WebSocket upgrades, to 127.0.0.1:8080. Normal builds
|
||||
use core directly. `src/mock/core.ts` is a temporary fixture renderer selected
|
||||
only by the VITE_MOCK alias; remove it and that alias when core lands. Never deploy
|
||||
a build made with VITE_MOCK=1. The terminal slot is intentionally empty until M4.
|
||||
Configure the server's workspace and hosts first (see `../server/README.md`).
|
||||
Vite proxies `/api`, including WebSocket upgrades, to 127.0.0.1:8080.
|
||||
Open **Terminal** and run `claude` using your own CLI login. The server needs tmux
|
||||
and the real Claude Code CLI installed; see `../server/src/terminal/README.md`.
|
||||
The panel lazily loads xterm and its fit addon on first opening. It attaches to
|
||||
`/api/terminal?session=main` using ws/wss according to the page protocol. Input
|
||||
and resize frames follow the core contract; server output is raw terminal text.
|
||||
Resize messages are debounced by 100 ms. The panel stays mounted when collapsed,
|
||||
retaining the connection and scrollback. A closed connection offers **Reconnect**;
|
||||
there is no automatic retry loop. Reconnecting attaches to the existing tmux
|
||||
session. Theme follows the OS dark/light preference, including live changes.
|
||||
Changes made by Claude reload the notebook through the existing file event stream;
|
||||
unsaved editor drafts are retained with a conflict notice.
|
||||
|
||||
`npx -y [email protected] --filter @shellbook/web test` runs jsdom component and reducer
|
||||
tests. `... --filter @shellbook/web build` builds production assets. Clipboard APIs
|
||||
require HTTPS or localhost. SSH copy uses a quoted heredoc (a multiline paste),
|
||||
with strict bash flags matching server execution; secret env values are never copied.
|
||||
Steps using secret environment variables require the operator to provide them when
|
||||
pasting manually. WebSocket disconnects disable execution and require a page reload.
|
||||
## Run results and downloads
|
||||
|
||||
Successful `capture` results enter notebook-scoped runtime values for subsequent
|
||||
scripts and prose. Success/failure `:::after` sections follow the latest run for
|
||||
that step in this browser session. Artifacts from successful runs supply provenance
|
||||
for `upload=` requests.
|
||||
|
||||
Downloads use one fetch GET followed by a blob download so HTTP 410 can be shown as
|
||||
**no longer available**. There is no HEAD/preflight request that could accidentally
|
||||
consume a one-shot file. Sensitive links disable immediately while fetching and
|
||||
remain consumed in session state after success. If a sensitive request fails,
|
||||
the link remains disabled because the server may already have consumed it; an
|
||||
error explains this. Ordinary failed downloads can be retried. Download state is
|
||||
kept across notebook navigation/reloads within the mounted app, not page refreshes;
|
||||
the server enforces one-shot downloads and expiry across tabs and refreshes.
|
||||
|
||||
Clipboard APIs require HTTPS or localhost. SSH copy uses a quoted heredoc with
|
||||
strict bash flags matching execution; secret env values are never copied. Steps
|
||||
using secret environment variables require the operator to provide them when
|
||||
pasting manually. Event WebSocket disconnects disable execution and require a page
|
||||
reload (terminal reconnection is independent).
|
||||
|
||||
## Verification
|
||||
|
||||
From the root:
|
||||
|
||||
```powershell
|
||||
npx -y pnpm@9.15.0 typecheck
|
||||
npx -y pnpm@9.15.0 test
|
||||
npx -y pnpm@9.15.0 build
|
||||
```
|
||||
|
||||
Web-only tests: `npx -y [email protected] --filter @shellbook/web test`.
|
||||
Vitest/Testing Library tests run in jsdom, with xterm modules mocked only in terminal
|
||||
tests. A fake WebSocket checks raw output, input/resize framing, collapse lifetime,
|
||||
and reconnect. App tests drive the SSH-key fixture through keygen, sensitive artifact
|
||||
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.
|
||||
|
||||
@@ -249,6 +249,9 @@ export function App({ api }: { api: Api }) {
|
||||
host={hosts.find((h) => h.name === rendered.host)}
|
||||
run={runFor(block.step.attrs.id)}
|
||||
artifact={api.artifact}
|
||||
onArtifactState={(runId, name, state) =>
|
||||
dispatch({ type: "artifact.download", runId, name, state })
|
||||
}
|
||||
connected={
|
||||
connected &&
|
||||
!dirty &&
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { useRef } from "react";
|
||||
import type { DownloadState } from "./events";
|
||||
export function ArtifactDownload({
|
||||
name,
|
||||
url,
|
||||
sensitive,
|
||||
state,
|
||||
onState,
|
||||
}: {
|
||||
name: string;
|
||||
url: string;
|
||||
sensitive: boolean;
|
||||
state?: DownloadState;
|
||||
onState(state: DownloadState): void;
|
||||
}) {
|
||||
const busy = useRef(false);
|
||||
const disabled =
|
||||
state === "downloading" ||
|
||||
state === "unavailable" ||
|
||||
(sensitive && !!state);
|
||||
async function download() {
|
||||
if (busy.current || disabled) return;
|
||||
busy.current = true;
|
||||
onState("downloading");
|
||||
try {
|
||||
// A single GET both retrieves the bytes and detects expired/consumed files.
|
||||
const response = await fetch(url, {
|
||||
credentials: "same-origin",
|
||||
cache: "no-store",
|
||||
});
|
||||
if (response.status === 410) {
|
||||
onState("unavailable");
|
||||
return;
|
||||
}
|
||||
if (!response.ok) throw new Error(`Download failed (${response.status})`);
|
||||
const blob = await response.blob();
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
const link = document.createElement("a");
|
||||
link.href = objectUrl;
|
||||
link.download = name;
|
||||
document.body.append(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
// Give the browser time to start saving before releasing the blob.
|
||||
setTimeout(() => URL.revokeObjectURL(objectUrl), 1000);
|
||||
onState("downloaded");
|
||||
} catch {
|
||||
onState("error");
|
||||
} finally {
|
||||
busy.current = false;
|
||||
}
|
||||
}
|
||||
return (
|
||||
<span className="artifact">
|
||||
<a
|
||||
href={disabled ? undefined : url}
|
||||
role="link"
|
||||
aria-disabled={disabled}
|
||||
tabIndex={disabled ? -1 : 0}
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
void download();
|
||||
}}
|
||||
download={name}
|
||||
>
|
||||
↓ {name}
|
||||
</a>
|
||||
{sensitive && <span className="badge">sensitive · one download</span>}
|
||||
{state === "downloaded" && sensitive && (
|
||||
<small> Downloaded / consumed</small>
|
||||
)}
|
||||
{state === "downloading" && <small> Downloading…</small>}
|
||||
{state === "unavailable" && <small> no longer available</small>}
|
||||
{state === "error" && (
|
||||
<small role="alert">
|
||||
{sensitive
|
||||
? "Download failed; one-shot download may have been consumed."
|
||||
: "Download failed. Try again."}
|
||||
</small>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
+13
-12
@@ -1,8 +1,9 @@
|
||||
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 { RunState } from "./events";
|
||||
import type { DownloadState, RunState } from "./events";
|
||||
import { sshCommand } from "./ssh";
|
||||
hljs.registerLanguage("bash", bash);
|
||||
|
||||
@@ -11,9 +12,7 @@ function Script({ script }: { script: string }) {
|
||||
return (
|
||||
<pre className="script">
|
||||
<code>
|
||||
{script
|
||||
.split(/(\{\{[^}]+\}\})/g)
|
||||
.map((part, i) =>
|
||||
{script.split(/(\{\{[^}]+\}\})/g).map((part, i) =>
|
||||
part.startsWith("{{") ? (
|
||||
<mark key={i}>{part}</mark>
|
||||
) : (
|
||||
@@ -37,6 +36,7 @@ export function StepCard({
|
||||
onRun,
|
||||
artifact,
|
||||
connected = true,
|
||||
onArtifactState,
|
||||
}: {
|
||||
step: Step;
|
||||
rendered: RenderedStep;
|
||||
@@ -45,6 +45,7 @@ export function StepCard({
|
||||
onRun(): void;
|
||||
artifact(id: string, name: string): string;
|
||||
connected?: boolean;
|
||||
onArtifactState?(runId: string, name: string, state: DownloadState): void;
|
||||
}) {
|
||||
const [notice, setNotice] = useState("");
|
||||
const invalid =
|
||||
@@ -129,14 +130,14 @@ export function StepCard({
|
||||
</pre>
|
||||
{run.error && <p className="error">{run.error}</p>}
|
||||
{run.artifacts.map((name) => (
|
||||
<a
|
||||
className="artifact"
|
||||
key={name}
|
||||
href={artifact(run.runId, name)}
|
||||
download
|
||||
>
|
||||
↓ {name}
|
||||
</a>
|
||||
<ArtifactDownload
|
||||
key={`${run.runId}:${name}`}
|
||||
name={name}
|
||||
url={artifact(run.runId, name)}
|
||||
sensitive={run.sensitiveArtifacts?.includes(name) ?? false}
|
||||
state={run.artifactDownloads?.[name]}
|
||||
onState={(state) => onArtifactState?.(run.runId, name, state)}
|
||||
/>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
|
||||
+29
-1
@@ -1,5 +1,11 @@
|
||||
import type { ServerEvent, StartRunRequest } from "@shellbook/core";
|
||||
|
||||
export type DownloadState =
|
||||
| "downloading"
|
||||
| "downloaded"
|
||||
| "unavailable"
|
||||
| "error";
|
||||
|
||||
export interface RunState {
|
||||
runId: string;
|
||||
notebookPath: string;
|
||||
@@ -9,6 +15,8 @@ export interface RunState {
|
||||
exitCode?: number;
|
||||
durationMs?: number;
|
||||
artifacts: string[];
|
||||
sensitiveArtifacts?: string[];
|
||||
artifactDownloads?: Record<string, DownloadState>;
|
||||
error?: string;
|
||||
hostKey?: Extract<ServerEvent, { type: "run.hostKeyUnknown" }>;
|
||||
}
|
||||
@@ -26,6 +34,12 @@ export const emptySession: Session = {
|
||||
};
|
||||
export const stepKey = (path: string, id: string) => JSON.stringify([path, id]);
|
||||
export type Action =
|
||||
| {
|
||||
type: "artifact.download";
|
||||
runId: string;
|
||||
name: string;
|
||||
state: DownloadState;
|
||||
}
|
||||
| ServerEvent
|
||||
| { type: "requested"; runId: string; request: StartRunRequest };
|
||||
export function eventReducer(state: Session, event: Action): Session {
|
||||
@@ -58,6 +72,15 @@ export function eventReducer(state: Session, event: Action): Session {
|
||||
let updated: RunState = run;
|
||||
let next = state;
|
||||
switch (event.type) {
|
||||
case "artifact.download":
|
||||
updated = {
|
||||
...run,
|
||||
artifactDownloads: {
|
||||
...run.artifactDownloads,
|
||||
[event.name]: event.state,
|
||||
},
|
||||
};
|
||||
break;
|
||||
case "run.output":
|
||||
updated = {
|
||||
...run,
|
||||
@@ -74,7 +97,11 @@ export function eventReducer(state: Session, event: Action): Session {
|
||||
// An attempt aborted for host key confirmation also finishes (exit -1);
|
||||
// keep the prompt open until the user accepts or rejects.
|
||||
if (run.status === "hostKey") {
|
||||
updated = { ...run, exitCode: event.exitCode, durationMs: event.durationMs };
|
||||
updated = {
|
||||
...run,
|
||||
exitCode: event.exitCode,
|
||||
durationMs: event.durationMs,
|
||||
};
|
||||
break;
|
||||
}
|
||||
updated = {
|
||||
@@ -83,6 +110,7 @@ export function eventReducer(state: Session, event: Action): Session {
|
||||
exitCode: event.exitCode,
|
||||
durationMs: event.durationMs,
|
||||
artifacts: event.artifacts,
|
||||
sensitiveArtifacts: event.sensitiveArtifacts ?? [],
|
||||
};
|
||||
if (event.exitCode === 0) {
|
||||
next = {
|
||||
|
||||
@@ -112,6 +112,10 @@ export const mockApi: Api = {
|
||||
exitCode: failed ? 1 : 0,
|
||||
durationMs: 850,
|
||||
artifacts: rendered.artifacts,
|
||||
sensitiveArtifacts:
|
||||
request.stepId === "keygen"
|
||||
? rendered.artifacts.filter((name) => !name.endsWith(".pub"))
|
||||
: [],
|
||||
captured: block.step.attrs.capture
|
||||
? { name: block.step.attrs.capture, value: "demo-value" }
|
||||
: undefined,
|
||||
|
||||
+157
-11
@@ -35,14 +35,10 @@ function harness() {
|
||||
const api: Api = {
|
||||
me: vi.fn().mockResolvedValue({}),
|
||||
login: vi.fn().mockResolvedValue(undefined),
|
||||
list: vi
|
||||
.fn()
|
||||
.mockResolvedValue({
|
||||
list: vi.fn().mockResolvedValue({
|
||||
notebooks: [{ path: "ssh-key.md", title: "New server SSH key" }],
|
||||
}),
|
||||
hosts: vi
|
||||
.fn()
|
||||
.mockResolvedValue({
|
||||
hosts: vi.fn().mockResolvedValue({
|
||||
hosts: [
|
||||
{
|
||||
name: "staging",
|
||||
@@ -53,9 +49,7 @@ function harness() {
|
||||
},
|
||||
],
|
||||
}),
|
||||
notebook: vi
|
||||
.fn()
|
||||
.mockResolvedValue({
|
||||
notebook: vi.fn().mockResolvedValue({
|
||||
path: "ssh-key.md",
|
||||
source,
|
||||
notebook: parseNotebook(source),
|
||||
@@ -128,10 +122,15 @@ it("reveals after sections only on success and passes artifact provenance", asyn
|
||||
runId: "1",
|
||||
exitCode: 0,
|
||||
durationMs: 30,
|
||||
artifacts: ["key.pub"],
|
||||
artifacts: ["id_ed25519_staging", "id_ed25519_staging.pub"],
|
||||
sensitiveArtifacts: ["id_ed25519_staging"],
|
||||
captured: { name: "captured", value: "value" },
|
||||
});
|
||||
expect(screen.getByText(/Download the private key/)).toBeInTheDocument();
|
||||
expect(screen.getByText("sensitive \u00b7 one download")).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole("link", { name: "\u2193 id_ed25519_staging.pub" }),
|
||||
).toHaveAttribute("href", "/download");
|
||||
fireEvent.click(
|
||||
within(screen.getByRole("article", { name: "Authorize key" })).getByRole(
|
||||
"button",
|
||||
@@ -142,7 +141,7 @@ it("reveals after sections only on success and passes artifact provenance", asyn
|
||||
await waitFor(() => expect(api.run).toHaveBeenCalledTimes(2));
|
||||
expect(vi.mocked(api.run).mock.calls[1]?.[0]).toMatchObject({
|
||||
runtime: { captured: "value" },
|
||||
artifactSources: { "key.pub": "1" },
|
||||
artifactSources: { id_ed25519_staging: "1", "id_ed25519_staging.pub": "1" },
|
||||
});
|
||||
emit({
|
||||
type: "run.hostKeyUnknown",
|
||||
@@ -214,3 +213,150 @@ it("retains edits made while a file reload is in flight", async () => {
|
||||
source + "\nIn-flight draft\n",
|
||||
);
|
||||
});
|
||||
|
||||
it("renders captured runtime in later scripts and prose and selects failed after sections", async () => {
|
||||
const { api, emit } = harness();
|
||||
const captureSource =
|
||||
source +
|
||||
`
|
||||
|
||||
\`\`\`sh {run on=local id=capture capture=directory}
|
||||
printf '/tmp/a b'
|
||||
\`\`\`
|
||||
|
||||
\`\`\`sh {run on=local id=use title="Use capture"}
|
||||
printf '%s' {{directory}}
|
||||
\`\`\`
|
||||
|
||||
Captured directory: {{directory}}
|
||||
|
||||
:::after{step=keygen failed}
|
||||
Key generation failed. Retry safely.
|
||||
:::
|
||||
`;
|
||||
vi.mocked(api.notebook).mockResolvedValue({
|
||||
path: "ssh-key.md",
|
||||
source: captureSource,
|
||||
notebook: parseNotebook(captureSource),
|
||||
version: "1",
|
||||
});
|
||||
await ready(api);
|
||||
const later = screen.getByRole("article", { name: "Use capture" });
|
||||
expect(within(later).getByRole("button", { name: "Run" })).toBeDisabled();
|
||||
emit({
|
||||
type: "run.started",
|
||||
runId: "capture-run",
|
||||
notebookPath: "ssh-key.md",
|
||||
stepId: "capture",
|
||||
script: "printf '/tmp/a b'",
|
||||
});
|
||||
emit({
|
||||
type: "run.finished",
|
||||
runId: "capture-run",
|
||||
exitCode: 0,
|
||||
durationMs: 1,
|
||||
artifacts: [],
|
||||
captured: { name: "directory", value: "/tmp/a b" },
|
||||
});
|
||||
expect(later.querySelector("pre.script")).toHaveTextContent(
|
||||
"printf '%s' '/tmp/a b'",
|
||||
);
|
||||
expect(screen.getByText("Captured directory: /tmp/a b")).toBeInTheDocument();
|
||||
fireEvent.click(within(later).getByRole("button", { name: "Run" }));
|
||||
await waitFor(() =>
|
||||
expect(api.run).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ runtime: { directory: "/tmp/a b" } }),
|
||||
),
|
||||
);
|
||||
emit({
|
||||
type: "run.started",
|
||||
runId: "failed",
|
||||
notebookPath: "ssh-key.md",
|
||||
stepId: "keygen",
|
||||
script: "ssh-keygen",
|
||||
});
|
||||
emit({
|
||||
type: "run.finished",
|
||||
runId: "failed",
|
||||
exitCode: 1,
|
||||
durationMs: 1,
|
||||
artifacts: [],
|
||||
});
|
||||
expect(
|
||||
screen.getByText("Key generation failed. Retry safely."),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByText(/Download the private key/),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it.each([200, 410])(
|
||||
"handles a sensitive artifact GET with status %s and retains session state",
|
||||
async (status) => {
|
||||
const { api, emit } = harness();
|
||||
const fetchMock = vi
|
||||
.fn()
|
||||
.mockResolvedValue({
|
||||
status,
|
||||
ok: status === 200,
|
||||
blob: async () => new Blob(["key bytes"]),
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const create = vi.fn(() => "blob:download");
|
||||
const revoke = vi.fn();
|
||||
Object.defineProperty(URL, "createObjectURL", {
|
||||
configurable: true,
|
||||
value: create,
|
||||
});
|
||||
Object.defineProperty(URL, "revokeObjectURL", {
|
||||
configurable: true,
|
||||
value: revoke,
|
||||
});
|
||||
const click = vi
|
||||
.spyOn(HTMLAnchorElement.prototype, "click")
|
||||
.mockImplementation(() => {});
|
||||
try {
|
||||
await ready(api);
|
||||
emit({
|
||||
type: "run.started",
|
||||
runId: "key-run",
|
||||
notebookPath: "ssh-key.md",
|
||||
stepId: "keygen",
|
||||
script: "ssh-keygen",
|
||||
});
|
||||
emit({
|
||||
type: "run.finished",
|
||||
runId: "key-run",
|
||||
exitCode: 0,
|
||||
durationMs: 1,
|
||||
artifacts: ["private"],
|
||||
sensitiveArtifacts: ["private"],
|
||||
});
|
||||
const link = screen.getByRole("link", { name: "↓ private" });
|
||||
fireEvent.click(link);
|
||||
fireEvent.click(link);
|
||||
await screen.findByText(
|
||||
status === 410 ? "no longer available" : "Downloaded / consumed",
|
||||
);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
expect(fetchMock).toHaveBeenCalledWith("/download", {
|
||||
credentials: "same-origin",
|
||||
cache: "no-store",
|
||||
});
|
||||
expect(link).toHaveAttribute("aria-disabled", "true");
|
||||
expect(link).not.toHaveAttribute("href");
|
||||
expect(click).toHaveBeenCalledTimes(status === 200 ? 1 : 0);
|
||||
if (status === 200) expect(create).toHaveBeenCalledWith(expect.any(Blob));
|
||||
// A notebook reload keeps the reducer's consumed/expired state.
|
||||
emit({ type: "file.changed", path: "ssh-key.md" });
|
||||
await waitFor(() => expect(api.notebook).toHaveBeenCalledTimes(2));
|
||||
expect(screen.getByRole("link", { name: "↓ private" })).toHaveAttribute(
|
||||
"aria-disabled",
|
||||
"true",
|
||||
);
|
||||
} finally {
|
||||
click.mockRestore();
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user