Merge branch 't3/manage-host-ssh-credentials'

# Conflicts:
#	.agents/mind/architecture.md
#	apps/server/src/app.ts
#	apps/web/src/App.tsx
#	packages/core/src/protocol.ts
This commit is contained in:
Florian Schmidt
2026-11-16 10:24:42 +01:00
22 changed files with 1775 additions and 82 deletions
+16 -57
View File
@@ -29,6 +29,8 @@ import type {
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";
@@ -131,6 +133,10 @@ export function App({ api }: { api: Api }) {
})
.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.type === "file.deleted") {
void api
@@ -377,7 +383,7 @@ export function App({ api }: { api: Api }) {
<main>
<HeaderNavigation page={page} onChange={setPage} />
{page === "Settings" && <SettingsPage openTerminal={() => { setTerminalOpened(true); setTerminal(true); }} />}
{page === "Hosts" && <p>Host management will appear here.</p>}
{page === "Hosts" && <HostsPage onChange={() => { void api.hosts().then(result => setHosts(result.hosts)).catch(e => setError(String(e))); }} />}
<div hidden={page !== "Notebooks"}>
<div className="toolbar">
<button aria-expanded={chat} onClick={() => { setChat(!chat); setTerminal(false); }}>Chat</button>
@@ -537,62 +543,15 @@ export function App({ api }: { api: Api }) {
</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>
)}
{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>
);
}
+1 -1
View File
@@ -1,4 +1,4 @@
// Feature navigation: add entries here and mount their view in App. Hosts is a placeholder for #7.
// 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({
+44
View File
@@ -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>
);
}
+464
View File
@@ -0,0 +1,464 @@
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";
const base = "/host-management";
const url = (name: string) => `${base}/${encodeURIComponent(name)}`;
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>();
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) {
setError(`${String(e)}. Reload hosts after a conflict before retrying.`);
} 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})`}`,
);
}
}
return (
<section className="hosts-page" aria-label="Server management">
<h1>Servers and SSH credentials</h1>
{error && <p role="alert">{error}</p>}
{status && <p role="status">{status}</p>}
<button
disabled={busy}
onClick={() =>
void perform(async () => {
await load();
setEditing(undefined);
setDraft({ ...empty });
})
}
>
Reload hosts
</button>
{inventory && (
<>
<h2>ShellBook public key</h2>
<pre>{inventory.publicKey}</pre>
<button
onClick={() =>
void perform(async () => {
await navigator.clipboard.writeText(inventory.publicKey);
setStatus("Public key copied");
})
}
>
Copy public key
</button>
<p>{inventory.certificateSupport.reason}</p>
<div className="host-list">
{inventory.hosts.map((host) => (
<article key={host.name}>
<h2>{host.name}</h2>
<p>
{host.user}@{host.address}:{host.port}
</p>
<p>{host.tags.join(", ")}</p>
<p>
Authentication: {host.credential.type}{" "}
{host.credential.fingerprint}{" "}
{host.credential.setAt && `set ${host.credential.setAt}`}
</p>
<div className="actions">
<button
disabled={busy}
onClick={() => {
setEditing(host.name);
setEditVersion(inventory.version);
setDraft({
name: host.name,
address: host.address,
user: host.user,
port: host.port,
tags: host.tags,
});
}}
>
Edit {host.name}
</button>
<button
disabled={busy}
onClick={() => {
setCredentialHost(host.name);
setType("shellbook");
setPassword("");
setPrivateKey("");
setPassphrase("");
}}
>
SSH credentials for {host.name}
</button>
<button
disabled={busy}
onClick={() =>
void perform(() => action(host.name, { action: "test" }))
}
>
Test connection to {host.name}
</button>
<button
disabled={busy || host.credential.type !== "password"}
onClick={() =>
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
disabled={busy}
onClick={() => {
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 for {host.name}
</button>
<button
disabled={busy}
onClick={() => {
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>
</div>
</article>
))}
</div>
<h2>{editing ? `Edit ${editing}` : "Add server"}</h2>
<form
onSubmit={(e) => {
e.preventDefault();
void perform(async () => {
await json(
editing ? url(editing) : base,
editing ? "PUT" : "POST",
{
host: draft,
baseVersion: editing ? editVersion : inventory.version,
},
);
setEditing(undefined);
setDraft({ ...empty });
await load();
onChange?.();
});
}}
>
<label>
Name
<input
required
pattern="[A-Za-z0-9._-]+"
value={draft.name}
onChange={(e) => setDraft({ ...draft, name: e.target.value })}
/>
</label>
<label>
Address
<input
required
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>
Tags (comma separated)
<input
value={draft.tags.join(",")}
onChange={(e) =>
setDraft({
...draft,
tags: e.target.value
.split(",")
.map((t) => t.trim())
.filter(Boolean),
})
}
/>
</label>
<button disabled={busy}>Save server</button>
<button
type="button"
onClick={() => {
setEditing(undefined);
setDraft({ ...empty });
}}
>
New server
</button>
</form>
</>
)}
{credentialHost && (
<section
role="dialog"
aria-modal="true"
aria-label={`SSH credentials for ${credentialHost}`}
>
<h2>SSH credentials for {credentialHost}</h2>
<p>
Saved secrets cannot be read back. Blank fields do not represent the
existing credential.
</p>
<form
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
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>
</>
)}
<button disabled={busy}>Save authentication</button>
<button
type="button"
onClick={() => {
setCredentialHost(undefined);
setPassword("");
setPrivateKey("");
setPassphrase("");
}}
>
Cancel
</button>
</form>
</section>
)}
{install && (
<section
role="dialog"
aria-modal="true"
aria-label="Install ShellBook key"
>
<h2>Install ShellBook key on {install.host}</h2>
<p>
This exact script runs using the stored password. After success,
select ShellBook key in SSH credentials to remove the saved
password.
</p>
<pre>{install.script}</pre>
<button
disabled={busy}
onClick={() =>
void perform(() =>
action(install.host, {
action: "install-key",
script: install.script,
}),
)
}
>
Run displayed script
</button>
<button onClick={() => setInstall(undefined)}>
Cancel installation
</button>
</section>
)}
{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>
);
}
+1 -1
View File
@@ -13,7 +13,7 @@ export class HttpError extends Error {
super(`Request failed (${status})`);
}
}
async function json<T>(
export async function json<T>(
path: string,
method = "GET",
body?: unknown,
+49
View File
@@ -0,0 +1,49 @@
.hosts-page {
padding: 1rem;
max-width: 70rem;
min-width: 0;
}
.hosts-page pre {
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.hosts-page form {
display: flex;
flex-wrap: wrap;
gap: 0.8rem;
align-items: end;
}
.hosts-page label {
display: flex;
flex-direction: column;
gap: 0.3rem;
flex: 1 1 12rem;
min-width: 0;
}
.hosts-page input,
.hosts-page textarea,
.hosts-page select {
width: 100%;
box-sizing: border-box;
}
.hosts-page article,
.hosts-page [role="dialog"] {
border: 1px solid #777;
padding: 1rem;
margin-block: 1rem;
overflow-wrap: anywhere;
}
.hosts-page .actions {
flex-wrap: wrap;
}
.hosts-page button {
white-space: normal;
}
@media (max-width: 600px) {
.app:has(.hosts-page) {
display: block;
}
.app:has(.hosts-page) .sidebar {
width: auto;
}
}
+119
View File
@@ -0,0 +1,119 @@
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.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.getByText("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.getByText("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.getByText("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" }),
),
);
});