feat(web): add shell-first runbook UI and mock demo (#2)
Add notebook parameters, literal highlighted scripts, copy helpers, streamed runs, host-key confirmation, artifacts, conditional notes, login and optimistic Markdown editing. Keep the temporary core renderer isolated to mock mode. Use React and Vite for the UI, react-markdown for safe Markdown rendering, highlight.js for shell syntax, and CodeMirror 6 for Markdown editing. Add Testing Library, jsdom and Vitest for component and event-state coverage. Validate pnpm install, root typecheck and test (29 web tests, 1 server test), plus normal and mock web builds. Core contracts remain unchanged; real backend execution awaits the parallel core/server implementations.
This commit is contained in:
@@ -0,0 +1,123 @@
|
||||
import type { ServerEvent, StartRunRequest } from "@shellbook/core";
|
||||
import type { Api } from "../api";
|
||||
import { HttpError } from "../api";
|
||||
import { parseNotebook, renderStep } from "./core";
|
||||
import initial from "./ssh-key.md?raw";
|
||||
let source = initial;
|
||||
let version = 1;
|
||||
let counter = 0;
|
||||
const listeners = new Set<(event: ServerEvent) => void>();
|
||||
const emit = (event: ServerEvent) =>
|
||||
listeners.forEach((listener) => listener(event));
|
||||
const hosts = [
|
||||
{
|
||||
name: "staging",
|
||||
user: "admin",
|
||||
address: "192.0.2.10",
|
||||
port: 22,
|
||||
tags: ["demo"],
|
||||
},
|
||||
{
|
||||
name: "production",
|
||||
user: "ops",
|
||||
address: "192.0.2.20",
|
||||
port: 2222,
|
||||
tags: ["prod"],
|
||||
},
|
||||
];
|
||||
const artifactUrl = URL.createObjectURL(
|
||||
new Blob(["Demo artifact only. No real key material.\n"], {
|
||||
type: "text/plain",
|
||||
}),
|
||||
);
|
||||
export const mockApi: Api = {
|
||||
me: async () => ({ authenticated: true }),
|
||||
login: async () => undefined,
|
||||
list: async () => ({
|
||||
notebooks: [{ path: "ssh-key.md", title: "New server SSH key" }],
|
||||
}),
|
||||
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) };
|
||||
},
|
||||
events: (receive, connected) => {
|
||||
listeners.add(receive);
|
||||
connected(true);
|
||||
return () => {
|
||||
listeners.delete(receive);
|
||||
};
|
||||
},
|
||||
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 rendered = renderStep(
|
||||
notebook,
|
||||
block.step,
|
||||
request.params,
|
||||
request.runtime,
|
||||
hosts.map((h) => h.name),
|
||||
);
|
||||
const runId = `demo-${++counter}`;
|
||||
setTimeout(() => {
|
||||
emit({
|
||||
type: "run.started",
|
||||
runId,
|
||||
notebookPath: request.notebookPath,
|
||||
stepId: request.stepId,
|
||||
script: rendered.script,
|
||||
host: rendered.host,
|
||||
});
|
||||
if (rendered.host === "production" && !request.acceptHostKey) {
|
||||
emit({
|
||||
type: "run.hostKeyUnknown",
|
||||
runId,
|
||||
host: "production",
|
||||
fingerprint: "SHA256:DEMO-VERIFY-OUT-OF-BAND",
|
||||
changed: true,
|
||||
});
|
||||
return;
|
||||
}
|
||||
emit({
|
||||
type: "run.output",
|
||||
runId,
|
||||
stream: "stdout",
|
||||
data: "Demo stream — no shell commands execute.\n",
|
||||
});
|
||||
setTimeout(() => {
|
||||
const failed = request.stepId === "password-login-disabled";
|
||||
emit({
|
||||
type: "run.output",
|
||||
runId,
|
||||
stream: failed ? "stderr" : "stdout",
|
||||
data: failed
|
||||
? "Demo: password authentication is enabled.\n"
|
||||
: "Demo: completed successfully.\n",
|
||||
});
|
||||
emit({
|
||||
type: "run.finished",
|
||||
runId,
|
||||
exitCode: failed ? 1 : 0,
|
||||
durationMs: 850,
|
||||
artifacts: rendered.artifacts,
|
||||
captured: block.step.attrs.capture
|
||||
? { name: block.step.attrs.capture, value: "demo-value" }
|
||||
: undefined,
|
||||
});
|
||||
}, 850);
|
||||
}, 50);
|
||||
return { runId };
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,204 @@
|
||||
/** TEMPORARY M0 fallback. Demo-only Vite alias; never used in production.
|
||||
* Remove this file and the alias when core lands. Parser supports the fixture
|
||||
* body syntax only; frontmatter definitions are fixed to spec §3.1.
|
||||
*/
|
||||
import type {
|
||||
Block,
|
||||
Notebook,
|
||||
ParamValues,
|
||||
RenderedStep,
|
||||
Step,
|
||||
StepAttrs,
|
||||
} from "../../../../packages/core/src/types";
|
||||
export function shellQuote(value: string): string {
|
||||
return value && /^[A-Za-z0-9._/@:=+-]+$/.test(value)
|
||||
? value
|
||||
: `'${value.replace(/'/g, "'\\''")}'`;
|
||||
}
|
||||
export function parseNotebook(source: string): Notebook {
|
||||
const lines = source
|
||||
.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, "")
|
||||
.split(/\r?\n/);
|
||||
function parse(
|
||||
start: number,
|
||||
nested = false,
|
||||
): { blocks: Block[]; end: number } {
|
||||
const blocks: Block[] = [];
|
||||
let prose = "";
|
||||
const range = { startLine: 1, endLine: 1 };
|
||||
const flush = () => {
|
||||
if (prose) blocks.push({ type: "markdown", text: prose, range });
|
||||
prose = "";
|
||||
};
|
||||
for (let i = start; i < lines.length; i++) {
|
||||
const line = lines[i]!;
|
||||
if (nested && line === ":::") {
|
||||
flush();
|
||||
return { blocks, end: i };
|
||||
}
|
||||
const after = line.match(/^:::after\{step=(\S+?)( failed)?\}$/);
|
||||
if (after) {
|
||||
flush();
|
||||
const inner = parse(i + 1, true);
|
||||
blocks.push({
|
||||
type: "after",
|
||||
stepId: after[1]!,
|
||||
onFailure: !!after[2],
|
||||
blocks: inner.blocks,
|
||||
range,
|
||||
});
|
||||
i = inner.end;
|
||||
continue;
|
||||
}
|
||||
const fence = line.match(/^```(?:sh|bash) \{(run|check) (.*)\}$/);
|
||||
if (fence) {
|
||||
flush();
|
||||
const raw = fence[2]!;
|
||||
const attrs = Object.fromEntries(
|
||||
[...raw.matchAll(/([\w]+)=(?:"([^"]*)"|([^\s]+))/g)].map((m) => [
|
||||
m[1],
|
||||
m[2] ?? m[3],
|
||||
]),
|
||||
);
|
||||
const title = attrs.title ?? "Step";
|
||||
const stepAttrs: StepAttrs = {
|
||||
id: attrs.id ?? title.toLowerCase().replace(/\s+/g, "-"),
|
||||
title,
|
||||
host: attrs.host,
|
||||
local: attrs.on === "local",
|
||||
sudo: /(?:^|\s)sudo(?:\s|$)/.test(raw),
|
||||
confirm: /(?:^|\s)confirm(?:\s|$)/.test(raw),
|
||||
artifacts: attrs.artifacts?.split(",") ?? [],
|
||||
uploads: attrs.upload
|
||||
? attrs.upload.split(",").map((pair: string) => {
|
||||
const [src, dst] = pair.split(":");
|
||||
return { src: src!, dst: dst! };
|
||||
})
|
||||
: [],
|
||||
timeoutSec: 30,
|
||||
capture: attrs.capture,
|
||||
};
|
||||
const script: string[] = [];
|
||||
while (++i < lines.length && lines[i] !== "```") script.push(lines[i]!);
|
||||
blocks.push({
|
||||
type: "step",
|
||||
step: {
|
||||
kind: fence[1] as Step["kind"],
|
||||
lang: "sh",
|
||||
attrs: stepAttrs,
|
||||
script: script.join("\n"),
|
||||
range,
|
||||
},
|
||||
});
|
||||
} else prose += line + "\n";
|
||||
}
|
||||
flush();
|
||||
return { blocks, end: lines.length };
|
||||
}
|
||||
return {
|
||||
title: "New server SSH key",
|
||||
params: [
|
||||
{ name: "host", type: "host", required: true, label: "Target server" },
|
||||
{
|
||||
name: "user",
|
||||
type: "name",
|
||||
required: true,
|
||||
default: "admin",
|
||||
label: "Login user",
|
||||
},
|
||||
{
|
||||
name: "keyname",
|
||||
type: "name",
|
||||
required: false,
|
||||
default: "id_ed25519_{{host}}",
|
||||
},
|
||||
],
|
||||
blocks: parse(0).blocks,
|
||||
diagnostics: [
|
||||
{
|
||||
severity: "warning",
|
||||
message:
|
||||
"Mock demo: frontmatter schema is fixed; prose and step edits are supported. No commands execute.",
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
export function renderText(
|
||||
text: string,
|
||||
values: ParamValues,
|
||||
notebook: Notebook,
|
||||
): string {
|
||||
return text.replace(/\{\{(\w+)\}\}/g, (token, name: string) =>
|
||||
notebook.params.find((p) => p.name === name)?.type === "secret"
|
||||
? "••••"
|
||||
: values[name] || token,
|
||||
);
|
||||
}
|
||||
export function resolveParams(
|
||||
notebook: Notebook,
|
||||
input: ParamValues,
|
||||
hosts: readonly string[],
|
||||
) {
|
||||
const values = { ...input };
|
||||
const errors: Record<string, string> = {};
|
||||
for (let i = 0; i < notebook.params.length; i++)
|
||||
for (const p of notebook.params)
|
||||
if (values[p.name] === undefined && p.default !== undefined) {
|
||||
const expanded = renderText(p.default, values, notebook);
|
||||
if (!expanded.includes("{{")) values[p.name] = expanded;
|
||||
}
|
||||
for (const p of notebook.params) {
|
||||
const value = values[p.name] ?? "";
|
||||
if (!value && p.required) errors[p.name] = "Required";
|
||||
else if (
|
||||
value &&
|
||||
((p.type === "host" && !hosts.includes(value)) ||
|
||||
(p.type === "name" && !/^[A-Za-z0-9._-]+$/.test(value)) ||
|
||||
(p.type === "choice" && !p.options?.includes(value)))
|
||||
)
|
||||
errors[p.name] = "Invalid value";
|
||||
}
|
||||
return { values, errors };
|
||||
}
|
||||
export function renderStep(
|
||||
notebook: Notebook,
|
||||
step: Step,
|
||||
values: ParamValues,
|
||||
runtime: ParamValues,
|
||||
hosts: readonly string[],
|
||||
): RenderedStep {
|
||||
const resolved = resolveParams(notebook, values, hosts);
|
||||
const all = { ...runtime, ...resolved.values };
|
||||
const missing = notebook.params
|
||||
.filter((p) => p.required && !all[p.name])
|
||||
.map((p) => p.name);
|
||||
const invalid = { ...resolved.errors };
|
||||
const script = step.script.replace(
|
||||
/\{\{(\w+)\}\}/g,
|
||||
(token, name: string) => {
|
||||
if (notebook.params.find((p) => p.name === name)?.type === "secret") {
|
||||
invalid[name] = "Use an environment variable for secrets";
|
||||
return token;
|
||||
}
|
||||
if (!all[name]) {
|
||||
if (!missing.includes(name)) missing.push(name);
|
||||
return token;
|
||||
}
|
||||
return shellQuote(all[name]!);
|
||||
},
|
||||
);
|
||||
return {
|
||||
stepId: step.attrs.id,
|
||||
kind: step.kind,
|
||||
host: renderText(step.attrs.host ?? "", all, notebook),
|
||||
local: step.attrs.local,
|
||||
script,
|
||||
artifacts: step.attrs.artifacts.map((a) => renderText(a, all, notebook)),
|
||||
uploads: step.attrs.uploads.map((u) => ({
|
||||
src: renderText(u.src, all, notebook),
|
||||
dst: renderText(u.dst, all, notebook),
|
||||
})),
|
||||
missing,
|
||||
invalid,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
---
|
||||
title: New server SSH key
|
||||
params:
|
||||
host: { type: host, required: true, label: Target server }
|
||||
user: { type: name, required: true, default: admin, label: Login user }
|
||||
keyname: { type: name, default: "id_ed25519_{{host}}" }
|
||||
---
|
||||
|
||||
# New server SSH key
|
||||
|
||||
Creates a key pair for **{{user}}** on **{{host}}** and authorizes it.
|
||||
|
||||
```sh {check host="{{host}}" title="User exists"}
|
||||
id {{user}}
|
||||
```
|
||||
|
||||
```sh {check host="{{host}}" title="Password login disabled"}
|
||||
sshd -T | grep -qx 'passwordauthentication no'
|
||||
```
|
||||
|
||||
```sh {run on=local id=keygen title="Generate key pair" artifacts="{{keyname}},{{keyname}}.pub"}
|
||||
ssh-keygen -q -t ed25519 -N '' -C {{user}}@{{host}} -f {{keyname}}
|
||||
```
|
||||
|
||||
```sh {run host="{{host}}" id=authorize title="Authorize key" confirm upload="{{keyname}}.pub:/tmp/new_key.pub"}
|
||||
install -d -m 700 -o {{user}} -g {{user}} ~{{user}}/.ssh
|
||||
cat /tmp/new_key.pub >> ~{{user}}/.ssh/authorized_keys
|
||||
rm /tmp/new_key.pub
|
||||
```
|
||||
|
||||
:::after{step=keygen}
|
||||
Download the private key above, then save it:
|
||||
|
||||
- **Linux:** `~/.ssh/{{keyname}}`, then `chmod 600 ~/.ssh/{{keyname}}`
|
||||
- **Windows:** `C:\Users\<you>\.ssh\{{keyname}}`
|
||||
:::
|
||||
Reference in New Issue
Block a user