Files
stackpilot/frontend/src/pages/Networks.tsx
T
menzeljandClaude Opus 5.5 d6cebb3371
CI / check (push) Successful in 4m9s
CI / build-and-push (push) Failing after 16m10s
Fix what a review of the whole app found, end to end (0.67.1)
A pass over every feature against a real Docker daemon, then clicking
through the UI as admin and read-only user, on a desktop and a phone.

Security. /ws/deploy ran compose up for the read-only role; it is
admin-only now. A container's inspect view, a stack's compose file
(POSTGRES_PASSWORD: hunter2) and the viewer's .env tab no longer show
credentials to that role. Git branch and URL values that git would read
as options (-x, ext::) are refused. SFTP host keys are checked: pinned
on first use or entered by hand (key line or SHA256 fingerprint), a
different key is refused before the password is sent. A backup name
from the API can no longer reach outside the destination folder. The
file browser refuses to move or rename a browse root, as delete did.

Docker lifecycle. Closing the deploy console released the stack lock
while compose was still running and logged rc=None as success; deploys
and updates are now background runs that hold the lock to the end,
report the real exit code and can be re-attached to. Every closed log
view left a `compose logs -f` behind. A dozen open tabs exhausted the
default thread pool and hung the API; event and exec streams have their
own threads. Auto-update and the update endpoint ignored failed pulls.
A deleted git stack was recreated and started by the next webhook or
poll; deleting a stack now drops its git source, auto-update policy and
schedule entries. Deleting no longer walks into mounted shares, is
refused while a backup runs, and removes the containers even when the
compose file is broken. Stack folders compose has to normalise
(Nextcloud -> nextcloud) work everywhere and group correctly on the
volumes, networks and images pages.

Detection. Host port conflicts read the container's own network
namespace; /proc/1/net is read instead. Images referenced as docker.io/…
were never update-checked; local builds no longer report "needs
credentials". NVIDIA GPUs are read from the driver's procfs. The backup
dialog's "path mismatch" warning came from mountinfo's filesystem-relative
root and fired for any stacks folder on its own disk, ZFS dataset or
btrfs subvolume; the host path now comes from Docker's mounts.

Backups and destinations. The download ignored the folder/volume
selection (axios sent binds[]). Restoring under a new name kept the old
one. A report header past nginx's buffer turned a good backup into a
502. SFTP/S3 errors were bare 500s and "Test" did not try to write.
A destination used by a schedule could be deleted. Backup file names
are in the schedule's or the browser's time zone instead of UTC.

Editor and converter. `docker run` conversion produced invalid compose
for --network host, named volumes and -dit; --gpus and --mount were
dropped; a multi-line command pasted into the one-line field became
`image: ' '` (now a textarea, and flattened continuations are read).
Validation failed for env_file stacks. The editor overwrote unsaved
edits on every container event, lost them on a stray click (now asks),
threw when closing the diff, and its helper panel listed the starter
service "app" for every existing stack. Monaco is bundled instead of
loaded from jsdelivr, so the editor works offline (and monaco-editor
0.57 drops the dompurify advisory; axios and react-router updated).

UI. All times were two hours off: offset-less UTC from SQLite was read
as local time, and "next run" always said "just now". A token refresh
mid-session duplicated deploys, reset terminals and doubled logs. A
backend restart (update, self-update) signed everyone out on reload; the
page now waits for it. The editor was unusable on a phone, tables and
tabs overflowed, dialog text was black on the dark theme, and the file
browser opened on an error with the default roots. Read-only users get
"Admin only" pages instead of 403s; in-use networks offer no delete;
"Scan all" covers StackPilot's own stacks only and runs in the
background instead of timing out at 600s.

Deployment. nginx passes the port in Host (the OIDC redirect URI lost
:5009) and keeps an outer proxy's X-Forwarded-Proto. The frontend waits
for a healthy backend (healthcheck probes every 2s while starting). The
frontend image builds with npm ci. Secrets are 0644 in a 0700 folder so
non-root containers can read them; existing files are fixed at startup.
The test suite no longer starts real containers on a host with Docker.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Fx7gcuy8d6nPd95g43rGHu
2026-10-15 13:51:26 +02:00

486 lines
17 KiB
TypeScript

import { Fragment, useMemo, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
Network as NetworkIcon,
Plus,
Trash2,
Eraser,
ChevronRight,
ChevronDown,
Link2,
Unplug,
} from "lucide-react";
import { toast } from "sonner";
import { Badge, Button, Card, Input, Spinner } from "@/components/ui";
import { ConfirmDialog } from "@/components/ui/ConfirmDialog";
import { networksApi, type NetworkInfo } from "@/api/networks";
import { PruneProgress } from "@/components/ui/PruneProgress";
import { usePruneJob } from "@/hooks/usePruneJob";
import { stacksApi } from "@/api/stacks";
import { groupByStack, stripStackPrefix, type StackGroup } from "@/lib/stackGroups";
import { StackGroupHeader } from "@/components/ui/StackGroupHeader";
import { apiErrorMessage } from "@/api/client";
import { useAuthStore } from "@/store/auth";
const selectClass =
"w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm dark:border-slate-600 dark:bg-slate-800";
export function Networks() {
const isAdmin = useAuthStore((s) => s.user?.role === "admin");
return <NetworksSection isAdmin={isAdmin} />;
}
function NetworksSection({ isAdmin }: { isAdmin: boolean }) {
const qc = useQueryClient();
const { data, isLoading } = useQuery({
queryKey: ["networks"],
queryFn: () => networksApi.list(),
refetchInterval: 60000,
});
const [creating, setCreating] = useState(false);
const [toDelete, setToDelete] = useState<NetworkInfo | null>(null);
const [expanded, setExpanded] = useState<string | null>(null);
const [pruneOpen, setPruneOpen] = useState(false);
const invalidate = () => qc.invalidateQueries({ queryKey: ["networks"] });
const colSpan = isAdmin ? 6 : 5;
const stacks = useQuery({
queryKey: ["stacks"],
queryFn: stacksApi.list,
staleTime: 30000,
});
const stackById = useMemo(
() => new Map((stacks.data ?? []).map((s) => [s.id, s])),
[stacks.data]
);
const groups = useMemo(
() =>
groupByStack(data ?? [], {
stacksOf: (n) => (n.stack ? [n.stack] : []),
sortKey: (n) => n.name,
stackById,
// bridge / host / none belong to nobody but are not leftovers either,
// so they get their own group at the very bottom.
isBuiltIn: (n) => n.is_default,
}),
[data, stackById]
);
const prune = usePruneJob({
noun: "network",
queryKey: "network-prune-status",
fetchStatus: networksApi.pruneStatus,
start: networksApi.startPrune,
enabled: isAdmin,
onFinished: invalidate,
});
const remove = useMutation({
mutationFn: (id: string) => networksApi.remove(id),
onSuccess: () => {
toast.success("Network deleted");
setToDelete(null);
invalidate();
},
onError: (e) => toast.error(apiErrorMessage(e)),
});
return (
<section>
{isAdmin && (
<div className="mb-3 flex flex-wrap items-center justify-end gap-2">
<Button variant="outline" onClick={() => setPruneOpen(true)} loading={!!prune.running}>
<Eraser className="h-4 w-4" /> Prune unused
</Button>
<Button onClick={() => setCreating(true)}>
<Plus className="h-4 w-4" /> Create network
</Button>
</div>
)}
{prune.running && (
<PruneProgress status={prune.running} title="Pruning unused networks…" />
)}
{isLoading ? (
<Spinner />
) : (
<Card className="overflow-x-auto p-0">
<table className="w-full text-left text-sm">
<thead className="border-b border-slate-200 text-xs uppercase text-slate-500 dark:border-slate-700">
<tr>
<th className="px-4 py-2">Name</th>
<th className="px-4 py-2">Driver</th>
<th className="px-4 py-2">Scope</th>
<th className="px-4 py-2">Subnet</th>
<th className="px-4 py-2">In use</th>
{isAdmin && <th className="px-4 py-2"></th>}
</tr>
</thead>
<tbody className="divide-y divide-slate-100 dark:divide-slate-700">
{groups.map((group) => (
<Fragment key={group.key}>
<StackGroupHeader
group={group}
colSpan={colSpan}
meta={groupMeta(group)}
/>
{group.items.map((n) => (
<NetworkRows
key={n.id}
network={n}
label={stripStackPrefix(n.name, group.stackId)}
colSpan={colSpan}
isAdmin={isAdmin}
expanded={expanded === n.id}
onToggle={() => setExpanded((e) => (e === n.id ? null : n.id))}
onDelete={() => setToDelete(n)}
/>
))}
</Fragment>
))}
{data?.length === 0 && (
<tr>
<td colSpan={colSpan} className="px-4 py-8 text-center text-sm text-slate-500">
No networks.
</td>
</tr>
)}
</tbody>
</table>
</Card>
)}
{creating && (
<CreateNetworkDialog
onDone={() => { setCreating(false); invalidate(); }}
onCancel={() => setCreating(false)}
/>
)}
{pruneOpen && (
<ConfirmDialog
title="Prune networks"
message="Remove every network no container is attached to, running or stopped. The built-in bridge, host and none networks are kept; a stack recreates its own on the next deploy."
confirmLabel="Prune networks"
danger
busy={prune.start.isPending}
onConfirm={() =>
prune.start.mutate(false, { onSuccess: () => setPruneOpen(false) })
}
onCancel={() => setPruneOpen(false)}
/>
)}
{toDelete && (
<ConfirmDialog
title={`Delete network “${toDelete.name}”?`}
message={
toDelete.in_use
? "This network is in use; Docker will refuse unless containers are disconnected first."
: "This cannot be undone."
}
confirmLabel="Delete network"
danger
busy={remove.isPending}
onConfirm={() => remove.mutate(toDelete.id)}
onCancel={() => setToDelete(null)}
/>
)}
</section>
);
}
/** One network: its row, plus the detail row when it is expanded. */
function NetworkRows({
network: n,
label,
colSpan,
isAdmin,
expanded,
onToggle,
onDelete,
}: {
network: NetworkInfo;
/** The name with the stack's prefix removed, when it had one. */
label: string;
colSpan: number;
isAdmin: boolean;
expanded: boolean;
onToggle: () => void;
onDelete: () => void;
}) {
return (
<>
<tr
onClick={onToggle}
className="cursor-pointer hover:bg-slate-50 dark:hover:bg-slate-800/50"
>
{/* Indented under its group heading. */}
<td className="py-2 pl-10 pr-4">
<div className="flex items-center gap-2">
{expanded ? (
<ChevronDown className="h-4 w-4 text-slate-400" />
) : (
<ChevronRight className="h-4 w-4 text-slate-400" />
)}
<NetworkIcon className="h-4 w-4 text-slate-400" />
{/* The stack is the heading now, so the row shows the part of the
name that differs — compose calls a stack's own network
"<project>_default". */}
<span className="font-medium" title={n.name}>
{label}
</span>
{n.internal && <span className="text-xs text-slate-400">internal</span>}
</div>
</td>
<td className="px-4 py-2 text-slate-500">{n.driver}</td>
<td className="px-4 py-2 text-slate-500">{n.scope}</td>
<td className="px-4 py-2 font-mono text-xs text-slate-500">{n.subnet ?? "—"}</td>
<td className="px-4 py-2">
{n.in_use ? (
<span
title={n.containers.join(", ")}
className="text-slate-600 dark:text-slate-300"
>
{n.containers.length} container{n.containers.length > 1 ? "s" : ""}
</span>
) : (
<span className="text-slate-400">—</span>
)}
</td>
{isAdmin && (
<td className="px-4 py-2 text-right">
{!n.is_default && (
// Disabled while in use: Docker refuses to remove it anyway, and
// the red bin offered a delete that could only fail.
<button
title={n.in_use ? "In use — disconnect its containers first" : "Delete"}
disabled={n.in_use}
onClick={(e) => {
e.stopPropagation();
onDelete();
}}
className="rounded-lg p-1.5 hover:bg-slate-100 disabled:cursor-not-allowed disabled:opacity-30 disabled:hover:bg-transparent dark:hover:bg-slate-700"
>
<Trash2 className={n.in_use ? "h-4 w-4 text-slate-400" : "h-4 w-4 text-red-500"} />
</button>
)}
</td>
)}
</tr>
{expanded && (
<tr>
<td colSpan={colSpan} className="bg-slate-50 px-4 py-3 dark:bg-slate-800/40">
<NetworkDetail network={n} isAdmin={isAdmin} />
</td>
</tr>
)}
</>
);
}
function NetworkDetail({
network,
isAdmin,
}: {
network: NetworkInfo;
isAdmin: boolean;
}) {
const qc = useQueryClient();
const [pick, setPick] = useState("");
const { data, isLoading } = useQuery({
queryKey: ["network-containers", network.id],
queryFn: () => networksApi.containers(network.id),
refetchInterval: 60000,
});
const refresh = () => {
qc.invalidateQueries({ queryKey: ["network-containers", network.id] });
qc.invalidateQueries({ queryKey: ["networks"] });
};
const connect = useMutation({
mutationFn: (container: string) => networksApi.connect(network.id, container),
onSuccess: () => { toast.success("Container connected"); setPick(""); refresh(); },
onError: (e) => toast.error(apiErrorMessage(e)),
});
const disconnect = useMutation({
mutationFn: (container: string) => networksApi.disconnect(network.id, container, false),
onSuccess: () => { toast.success("Container disconnected"); refresh(); },
onError: (e) => toast.error(apiErrorMessage(e)),
});
const connected = (data ?? []).filter((c) => c.connected);
const available = (data ?? []).filter((c) => !c.connected);
return (
<div className="space-y-3 text-sm">
<div className="grid grid-cols-2 gap-x-6 gap-y-1 sm:grid-cols-4">
<Meta label="Driver" value={network.driver} />
<Meta label="Scope" value={network.scope} />
<Meta label="Subnet" value={network.subnet ?? "—"} mono />
<Meta label="Gateway" value={network.gateway ?? "—"} mono />
<Meta label="Attachable" value={network.attachable ? "yes" : "no"} />
<Meta label="Internal" value={network.internal ? "yes" : "no"} />
<Meta label="ID" value={network.id} mono />
</div>
<div>
<p className="mb-1 text-xs font-semibold uppercase tracking-wide text-slate-500">
Connected containers
</p>
{isLoading ? (
<Spinner />
) : connected.length === 0 ? (
<p className="text-slate-400">No containers connected.</p>
) : (
<ul className="space-y-1">
{connected.map((c) => (
<li key={c.id} className="flex items-center gap-2">
<span className="font-medium">{c.name}</span>
{c.stack && <Badge>{c.stack}</Badge>}
<span className="text-xs text-slate-400">{c.state}</span>
{isAdmin && !network.is_default && (
<button
title="Disconnect"
onClick={() => disconnect.mutate(c.name)}
disabled={disconnect.isPending}
className="ml-1 rounded p-1 hover:bg-slate-200 dark:hover:bg-slate-700"
>
<Unplug className="h-3.5 w-3.5 text-red-500" />
</button>
)}
</li>
))}
</ul>
)}
</div>
{isAdmin && (
<div className="flex items-center gap-2">
<select
className={selectClass + " max-w-xs"}
value={pick}
onChange={(e) => setPick(e.target.value)}
>
<option value="">Connect a container…</option>
{available.map((c) => (
<option key={c.id} value={c.name}>
{c.name}
{c.stack ? ` (${c.stack})` : ""}
</option>
))}
</select>
<Button
variant="outline"
disabled={!pick || connect.isPending}
loading={connect.isPending}
onClick={() => connect.mutate(pick)}
>
<Link2 className="h-4 w-4" /> Connect
</Button>
</div>
)}
</div>
);
}
function Meta({ label, value, mono }: { label: string; value: string; mono?: boolean }) {
return (
<div>
<span className="text-xs text-slate-400">{label}</span>
<p className={mono ? "font-mono text-xs" : ""}>{value}</p>
</div>
);
}
function CreateNetworkDialog({
onDone,
onCancel,
}: {
onDone: () => void;
onCancel: () => void;
}) {
const [form, setForm] = useState({
name: "",
driver: "bridge",
subnet: "",
gateway: "",
internal: false,
attachable: true,
});
const set = (k: string, v: unknown) => setForm((f) => ({ ...f, [k]: v }));
const create = useMutation({
mutationFn: () =>
networksApi.create({
name: form.name,
driver: form.driver,
subnet: form.subnet.trim() || null,
gateway: form.gateway.trim() || null,
internal: form.internal,
attachable: form.attachable,
}),
onSuccess: () => { toast.success("Network created"); onDone(); },
onError: (e) => toast.error(apiErrorMessage(e)),
});
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={onCancel}>
<div
className="w-full max-w-md rounded-xl border border-slate-200 bg-card p-5 shadow-xl dark:border-slate-700 dark:bg-card-dark"
onClick={(e) => e.stopPropagation()}
>
<h2 className="mb-3 sp-heading text-lg">Create network</h2>
<div className="space-y-3">
<label className="block space-y-1">
<span className="text-xs font-medium text-slate-500">Name</span>
<Input value={form.name} onChange={(e) => set("name", e.target.value)} placeholder="my-net" />
</label>
<label className="block space-y-1">
<span className="text-xs font-medium text-slate-500">Driver</span>
<select className={selectClass} value={form.driver} onChange={(e) => set("driver", e.target.value)}>
<option value="bridge">bridge</option>
<option value="macvlan">macvlan</option>
<option value="ipvlan">ipvlan</option>
<option value="overlay">overlay</option>
</select>
</label>
<div className="grid grid-cols-2 gap-3">
<label className="space-y-1">
<span className="text-xs font-medium text-slate-500">Subnet (optional)</span>
<Input value={form.subnet} onChange={(e) => set("subnet", e.target.value)} placeholder="172.20.0.0/16" />
</label>
<label className="space-y-1">
<span className="text-xs font-medium text-slate-500">Gateway (optional)</span>
<Input value={form.gateway} onChange={(e) => set("gateway", e.target.value)} placeholder="172.20.0.1" />
</label>
</div>
<div className="flex gap-4">
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" checked={form.internal} onChange={(e) => set("internal", e.target.checked)} className="h-4 w-4" />
Internal (no external access)
</label>
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" checked={form.attachable} onChange={(e) => set("attachable", e.target.checked)} className="h-4 w-4" />
Attachable
</label>
</div>
</div>
<div className="mt-4 flex justify-end gap-2">
<Button variant="outline" onClick={onCancel}>Cancel</Button>
<Button onClick={() => create.mutate()} loading={create.isPending} disabled={!form.name.trim()}>
Create
</Button>
</div>
</div>
</div>
);
}
/** What a network group can say for itself. */
function groupMeta(group: StackGroup<NetworkInfo>): string {
const parts = [`${group.items.length} network${group.items.length > 1 ? "s" : ""}`];
const idle = group.items.filter((n) => !n.in_use).length;
if (idle > 0) parts.push(`${idle} unused`);
return parts.join(" · ");
}