One component, PageIntro, for the text under a page's title: shown as it is when it fits in two lines, otherwise folded with a Show more, remembered per page in this browser, opened by tabbing to a link in it, unfolded in print. Used on 41 pages. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
351 lines
17 KiB
TypeScript
351 lines
17 KiB
TypeScript
import { useCallback, useEffect, useMemo, useState } from "react";
|
|
import { Link } from "react-router-dom";
|
|
import ProxyHostForm from "../components/ProxyHostForm";
|
|
import { api, type CurrentUser, type IntegrationProblem, type NpmHost, type NpmOverview } from "../api/client";
|
|
import SortableTh from "../components/SortableTh";
|
|
import Pagination from "../components/Pagination";
|
|
import TableToolbar from "../components/TableToolbar";
|
|
import TimeAgo from "../components/TimeAgo";
|
|
import EmptyState, { EmptyRow } from "../components/EmptyState";
|
|
import { BlockSkeleton } from "../components/Skeleton";
|
|
import { ErrorNotice } from "../components/Notice";
|
|
import { useSortable } from "../hooks/useSortable";
|
|
import { useTableSearch } from "../hooks/useTableSearch";
|
|
import { usePagination } from "../hooks/usePagination";
|
|
import { downloadCsv } from "../utils/csv";
|
|
import { confirmDialog, promptDialog } from "../utils/dialogs";
|
|
import { formatDate } from "../utils/date";
|
|
import { readableError } from "../utils/errors";
|
|
import { toast } from "../utils/toast";
|
|
import PageIntro from "../components/PageIntro";
|
|
|
|
type Row = NpmHost & { integrationId: number; canManage: boolean; integrationName: string; domain: string; target: string; certDays: number | null; certName: string; statusRank: number; serverName: string };
|
|
|
|
const DAY_MS = 86_400_000;
|
|
const daysLeft = (iso: string | null): number | null => (iso && Number.isFinite(Date.parse(iso)) ? Math.floor((Date.parse(iso) - Date.now()) / DAY_MS) : null);
|
|
|
|
function StatusBadge({ h }: { h: Row }) {
|
|
if (!h.enabled) return <span className="badge bg-secondary-lt text-secondary">Switched off</span>;
|
|
if (!h.online)
|
|
return (
|
|
<span className="badge bg-red-lt text-red" title={h.error ?? "Nginx Proxy Manager could not set this host up"}>
|
|
Not working
|
|
</span>
|
|
);
|
|
return <span className="badge bg-green-lt text-green">Working</span>;
|
|
}
|
|
|
|
function CertBadge({ h }: { h: Row }) {
|
|
if (!h.certificate) return <span className="text-secondary">{h.sslForced ? "—" : "No certificate"}</span>;
|
|
const d = h.certDays;
|
|
const color = d === null ? "secondary" : d < 0 ? "red" : d <= 3 ? "red" : d <= 14 ? "yellow" : "green";
|
|
const words = d === null ? "no end date" : d < 0 ? `ran out ${-d} ${d === -1 ? "day" : "days"} ago` : d === 0 ? "ends today" : `${d} ${d === 1 ? "day" : "days"} left`;
|
|
return (
|
|
<span title={h.certificate.expiresAt ? `${h.certificate.name} — ends ${formatDate(new Date(h.certificate.expiresAt))}` : h.certificate.name}>
|
|
<span className={`badge bg-${color}-lt text-${color}`}>{words}</span>
|
|
<div className="text-secondary small">{h.certificate.name}</div>
|
|
</span>
|
|
);
|
|
}
|
|
|
|
/**
|
|
* What Nginx Proxy Manager proxies: each name people use, where it forwards to (and which server that is), its certificate and whether NPM could set it up. Read
|
|
* from NPM when the page is opened (and at most once a minute); nothing here changes anything in NPM.
|
|
*/
|
|
export default function ProxyHosts({ user }: { user: CurrentUser }) {
|
|
const [data, setData] = useState<NpmOverview | null>(null);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [reading, setReading] = useState(false);
|
|
|
|
const load = useCallback(
|
|
(refresh = false) =>
|
|
api.npm
|
|
.overview(refresh)
|
|
.then((res) => {
|
|
setData(res);
|
|
setError(null);
|
|
})
|
|
.catch((err) => setError(readableError(err))),
|
|
[],
|
|
);
|
|
|
|
useEffect(() => {
|
|
void load();
|
|
const timer = setInterval(() => void load(), 60_000);
|
|
return () => clearInterval(timer);
|
|
}, [load]);
|
|
|
|
async function readNow() {
|
|
setReading(true);
|
|
await load(true);
|
|
setReading(false);
|
|
toast.success("Read from Nginx Proxy Manager.");
|
|
}
|
|
|
|
const rows: Row[] = useMemo(
|
|
() =>
|
|
(data?.integrations ?? []).flatMap((i) =>
|
|
i.hosts.map((h) => ({
|
|
...h,
|
|
integrationId: i.id,
|
|
canManage: i.canManage,
|
|
integrationName: i.name,
|
|
domain: h.domains.join(", "),
|
|
target: `${h.forwardScheme}://${h.forwardHost}${h.forwardPort !== null ? `:${h.forwardPort}` : ""}`,
|
|
certDays: daysLeft(h.certificate?.expiresAt ?? null),
|
|
certName: h.certificate?.name ?? "",
|
|
statusRank: !h.enabled ? 2 : h.online ? 1 : 0,
|
|
serverName: h.server?.name ?? "",
|
|
})),
|
|
),
|
|
[data],
|
|
);
|
|
const isAdmin = user.role === "admin";
|
|
const managing = (data?.integrations ?? []).filter((i) => i.canManage && !i.error);
|
|
const canManageAny = isAdmin && (data?.integrations ?? []).some((i) => i.canManage);
|
|
// The form that is open: a new host (on one of the NPMs that can be managed) or a change of one.
|
|
const [form, setForm] = useState<{ mode: "new"; integrationId: number } | { mode: "edit"; row: Row } | null>(null);
|
|
|
|
async function afterChange(message: string) {
|
|
setForm(null);
|
|
toast.success(message);
|
|
await load(true);
|
|
}
|
|
|
|
async function switchHost(h: Row) {
|
|
if (h.enabled && !(await confirmDialog({ title: "Switch off proxy host", message: `Switch off ${h.domains[0]}? Nginx Proxy Manager stops serving ${h.domains.length > 1 ? "its names" : "it"}. Nothing is lost, and switching it on again brings it back.`, confirmLabel: "Switch off", danger: true }))) return;
|
|
try {
|
|
await api.npm.setHostEnabled(h.integrationId, h.id, !h.enabled);
|
|
toast.success(`${h.domains[0]} is ${h.enabled ? "off" : "on"}.`);
|
|
await load(true);
|
|
} catch (err) {
|
|
toast.error(readableError(err));
|
|
}
|
|
}
|
|
|
|
async function deleteHost(h: Row) {
|
|
const typed = await promptDialog({
|
|
title: "Delete proxy host",
|
|
message: `This deletes the proxy host ${h.domains.join(", ")} (it forwards to ${h.target}) in ${h.integrationName}: Nginx Proxy Manager stops serving ${h.domains.length > 1 ? "those names" : "that name"}. Type its first name to confirm.`,
|
|
label: "First name",
|
|
confirmLabel: "Delete",
|
|
required: true,
|
|
});
|
|
if (typed === null) return;
|
|
if (typed.trim().toLowerCase() !== h.domains[0]) {
|
|
toast.error("That is not the first name of the host, so nothing was deleted.");
|
|
return;
|
|
}
|
|
try {
|
|
await api.npm.deleteHost(h.integrationId, h.id, h.domains[0]);
|
|
toast.success(`Deleted ${h.domains[0]}.`);
|
|
await load(true);
|
|
} catch (err) {
|
|
toast.error(readableError(err));
|
|
}
|
|
}
|
|
|
|
const tableSearch = useTableSearch(rows);
|
|
const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered, "statusRank", "asc", { url: true });
|
|
const { pageItems, page, setPage, pageCount, totalCount } = usePagination(sorted);
|
|
|
|
const problems: (IntegrationProblem & { integration: string })[] = (data?.integrations ?? []).flatMap((i) => i.problems.map((p) => ({ ...p, integration: i.name })));
|
|
const soon = rows.filter((h) => h.enabled && h.certDays !== null && h.certDays <= 14).length;
|
|
const noNpm = data !== null && data.integrations.length === 0;
|
|
|
|
function exportCsv() {
|
|
downloadCsv(
|
|
"proxy-hosts.csv",
|
|
["Names", "Forwards to", "Server", "Status", "Certificate", "Certificate ends", "Force HTTPS", "Nginx Proxy Manager"],
|
|
(sorted ?? []).map((h) => [h.domain, h.target, h.serverName, !h.enabled ? "switched off" : h.online ? "working" : "not working", h.certName, h.certificate?.expiresAt ?? "", h.sslForced ? "yes" : "no", h.integrationName]),
|
|
);
|
|
}
|
|
|
|
return (
|
|
<>
|
|
<div className="d-flex flex-wrap align-items-center gap-2 mb-1">
|
|
<h2 className="page-title mb-0">Proxy hosts</h2>
|
|
{(user.role === "admin" || user.role === "operator") && data && data.integrations.length > 0 && (
|
|
<div className="ms-auto btn-list">
|
|
{isAdmin && managing.length > 0 && (
|
|
<button className="btn btn-primary" onClick={() => setForm({ mode: "new", integrationId: managing[0].id })}>
|
|
New proxy host
|
|
</button>
|
|
)}
|
|
<button className="btn btn-outline-secondary" onClick={() => void readNow()} disabled={reading}>
|
|
{reading ? "Reading…" : "Read now"}
|
|
</button>
|
|
</div>
|
|
)}
|
|
</div>
|
|
<PageIntro>
|
|
What Nginx Proxy Manager serves: the name, where it forwards to, the certificate and whether NPM could set it up. {canManageAny ? "An administrator can also make, change, switch off and delete hosts here. " : "It only reads — nothing here changes anything in NPM. "}A certificate in its last
|
|
two weeks, or a host NPM can’t set up, is an alert.
|
|
</PageIntro>
|
|
{isAdmin && data && data.integrations.length > 0 && !canManageAny && (
|
|
<div className="text-secondary small mb-3">
|
|
To make and change proxy hosts from here, give the Nginx Proxy Manager integration a user with <em>Manage</em> on Proxy Hosts: <Link to="/integrations">Integrations</Link> → edit → <em>Email of a user that may manage</em>.
|
|
</div>
|
|
)}
|
|
{form && form.mode === "new" && (
|
|
<>
|
|
{managing.length > 1 && (
|
|
<div className="mb-2">
|
|
<label className="form-label" htmlFor="ph-integration">
|
|
In
|
|
</label>
|
|
<select id="ph-integration" className="form-select w-auto" value={form.integrationId} onChange={(e) => setForm({ mode: "new", integrationId: Number(e.target.value) })}>
|
|
{managing.map((i) => (
|
|
<option key={i.id} value={i.id}>
|
|
{i.name}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</div>
|
|
)}
|
|
<ProxyHostForm key={form.integrationId} integrationId={form.integrationId} integrationName={managing.find((i) => i.id === form.integrationId)?.name ?? ""} certificates={managing.find((i) => i.id === form.integrationId)?.certificates ?? []} onDone={(name) => void afterChange(`Made the proxy host ${name}.`)} onCancel={() => setForm(null)} />
|
|
</>
|
|
)}
|
|
{form && form.mode === "edit" && (
|
|
<ProxyHostForm
|
|
key={`${form.row.integrationId}-${form.row.id}`}
|
|
integrationId={form.row.integrationId}
|
|
integrationName={form.row.integrationName}
|
|
certificates={(data?.integrations ?? []).find((i) => i.id === form.row.integrationId)?.certificates ?? []}
|
|
host={form.row}
|
|
onDone={(name) => void afterChange(`Saved ${name}.`)}
|
|
onCancel={() => setForm(null)}
|
|
/>
|
|
)}
|
|
<ErrorNotice error={error} />
|
|
{data === null && !error && <BlockSkeleton lines={4} />}
|
|
|
|
{noNpm && (
|
|
<div className="card">
|
|
<EmptyState
|
|
title="No Nginx Proxy Manager connected"
|
|
hint="Add an Nginx Proxy Manager integration — a user that may only view proxy hosts and certificates is enough — and what it serves appears here."
|
|
action={user.role === "admin" ? { label: "Add Nginx Proxy Manager", to: "/integrations" } : undefined}
|
|
/>
|
|
</div>
|
|
)}
|
|
|
|
{data && data.integrations.length > 0 && (
|
|
<div className="mb-3 small">
|
|
{data.integrations.map((i) => (
|
|
<div key={i.id} className={i.error ? "text-red" : "text-secondary"}>
|
|
<strong>{i.name}</strong>
|
|
{i.error ? <> — couldn’t be read: {i.error}</> : <> — read <TimeAgo value={i.readAt} />{i.version ? ` · version ${i.version}` : ""} · {i.hosts.length} {i.hosts.length === 1 ? "host" : "hosts"}</>}
|
|
</div>
|
|
))}
|
|
</div>
|
|
)}
|
|
|
|
{data && data.integrations.some((i) => !i.error) && (
|
|
<>
|
|
<div className="row row-cards mb-3">
|
|
{[
|
|
{ label: "Proxy hosts", value: rows.length, color: "" },
|
|
{ label: "Not working", value: rows.filter((h) => h.enabled && !h.online).length, color: rows.some((h) => h.enabled && !h.online) ? "text-red" : "text-green" },
|
|
{ label: "Certificates ending within 14 days", value: soon, color: soon > 0 ? "text-yellow" : "text-green" },
|
|
{ label: "Switched off", value: rows.filter((h) => !h.enabled).length, color: "" },
|
|
].map((c) => (
|
|
<div className="col-6 col-lg-3" key={c.label}>
|
|
<div className="card card-sm">
|
|
<div className="card-body">
|
|
<div className={`h2 mb-0 ${c.color}`}>{c.value}</div>
|
|
<div className="text-secondary">{c.label}</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
))}
|
|
</div>
|
|
|
|
{problems.length > 0 && (
|
|
<div className="card mb-3">
|
|
<div className="card-header">
|
|
<h3 className="card-title">Needs attention</h3>
|
|
</div>
|
|
<div className="list-group list-group-flush">
|
|
{problems.map((p) => (
|
|
<div className="list-group-item d-flex align-items-center gap-2" key={p.key}>
|
|
<span className={`badge ${p.severity === "critical" ? "bg-red-lt text-red" : "bg-yellow-lt text-yellow"}`}>{p.severity === "critical" ? "Critical" : "Warning"}</span>
|
|
<span>{p.message}</span>
|
|
</div>
|
|
))}
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
<div className="card">
|
|
<TableToolbar search={tableSearch.query} onSearch={tableSearch.setQuery} placeholder="Search names, targets, servers…" shown={sorted?.length} total={rows.length} onExport={exportCsv} exportDisabled={!sorted || sorted.length === 0} />
|
|
<div className="table-responsive">
|
|
<table className="table table-vcenter card-table table-stack">
|
|
<thead>
|
|
<tr>
|
|
<SortableTh<Row> label="Status" sortKeyName="statusRank" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
|
<SortableTh<Row> label="Name" sortKeyName="domain" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
|
<SortableTh<Row> label="Forwards to" sortKeyName="target" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
|
<SortableTh<Row> label="Certificate" sortKeyName="certDays" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
|
{canManageAny && <th />}
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{(pageItems ?? []).length === 0 && <EmptyRow colSpan={canManageAny ? 5 : 4} title="No proxy hosts" filtered={tableSearch.active ? () => tableSearch.setQuery("") : undefined} />}
|
|
{(pageItems ?? []).map((h) => (
|
|
<tr key={`${h.integrationName}-${h.id}`}>
|
|
<td>
|
|
<StatusBadge h={h} />
|
|
{h.error && h.enabled && <div className="text-secondary small">{h.error.slice(0, 120)}</div>}
|
|
</td>
|
|
<td className="stack-wide">
|
|
{h.domains.map((d, i) => (
|
|
<div key={i}>
|
|
<a href={`${h.sslForced || h.certificate ? "https" : "http"}://${d}`} target="_blank" rel="noopener noreferrer">
|
|
<strong>{d}</strong>
|
|
</a>
|
|
</div>
|
|
))}
|
|
{data && data.integrations.length > 1 && <div className="text-secondary small">{h.integrationName}</div>}
|
|
</td>
|
|
<td className="stack-label" data-label="Forwards to">
|
|
<span className="font-monospace">{h.target}</span>
|
|
{h.server && (
|
|
<div className="small">
|
|
<Link to={`/servers/${h.server.id}`}>{h.server.name}</Link>
|
|
</div>
|
|
)}
|
|
</td>
|
|
<td className="stack-label" data-label="Certificate">
|
|
<CertBadge h={h} />
|
|
</td>
|
|
{canManageAny && (
|
|
<td className="text-end text-nowrap">
|
|
{h.canManage && (
|
|
<>
|
|
<button className="btn btn-sm btn-outline-secondary me-1" onClick={() => setForm({ mode: "edit", row: h })}>
|
|
Edit
|
|
</button>
|
|
<button className="btn btn-sm btn-outline-secondary me-1" onClick={() => void switchHost(h)}>
|
|
{h.enabled ? "Switch off" : "Switch on"}
|
|
</button>
|
|
<button className="btn btn-sm btn-outline-danger" onClick={() => void deleteHost(h)}>
|
|
Delete
|
|
</button>
|
|
</>
|
|
)}
|
|
</td>
|
|
)}
|
|
</tr>
|
|
))}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
<Pagination page={page} pageCount={pageCount} totalCount={totalCount} onPageChange={setPage} />
|
|
</div>
|
|
</>
|
|
)}
|
|
</>
|
|
);
|
|
}
|