Manage Nginx Proxy Manager proxy hosts from the Proxy hosts page

With an optional second user on the NPM integration (Manage on Proxy Hosts,
no two-factor sign-in) an administrator can make, change, switch off and
delete proxy hosts: names, where it forwards to, an existing certificate and
what is switched on. Only what differs is sent, a host's access list,
locations and custom configuration are never touched, and combinations NPM
would quietly undo (Force HTTPS, HTTP/2 or HSTS without a certificate) are
refused with the reason. Delete asks for the host's first name, checked
against the host as NPM has it. The user that reads is still view-only and
never writes. Audited; the managing user can be taken away again.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-11-03 19:24:00 +01:00
1 parent 672c7f2f66
commit 4dd7901f1c
13 files changed
+1286 -14

No files matched your search

+29 -1
View File
@@ -2258,6 +2258,14 @@ export interface NpmHost {
forwardPort: number | null;
enabled: boolean;
sslForced: boolean;
http2: boolean;
hsts: boolean;
hstsSubdomains: boolean;
blockExploits: boolean;
caching: boolean;
websocket: boolean;
/** The certificate it uses, by id; null for none. */
certificateId: number | null;
certificate: { id: number; name: string; expiresAt: string | null } | null;
online: boolean;
error: string | null;
@@ -2280,8 +2288,24 @@ export interface IntegrationProblem {
message: string;
}
/** What a proxy host is made of, as it is made and changed from here. */
export interface NpmHostSettings {
domains: string[];
scheme: "http" | "https";
host: string;
port: number;
certificateId: number | null;
sslForced: boolean;
http2: boolean;
hsts: boolean;
hstsSubdomains: boolean;
blockExploits: boolean;
caching: boolean;
websocket: boolean;
}
export interface NpmOverview {
integrations: { id: number; name: string; readAt: string; error: string | null; version: string | null; hosts: NpmHost[]; certificates: NpmCertificate[]; problems: IntegrationProblem[] }[];
integrations: { id: number; name: string; /** Whether it has a user to manage proxy hosts with. */ canManage: boolean; readAt: string; error: string | null; version: string | null; hosts: NpmHost[]; certificates: NpmCertificate[]; problems: IntegrationProblem[] }[];
}
export interface HaSyncStatus {
@@ -3690,6 +3714,10 @@ export const api = {
},
npm: {
overview: (refresh = false) => request<NpmOverview>(`/api/npm${refresh ? "?refresh=1" : ""}`),
createHost: (integrationId: number, body: NpmHostSettings) => request<{ host: NpmHost }>(`/api/npm/${integrationId}/hosts`, { method: "POST", body: JSON.stringify(body) }),
updateHost: (integrationId: number, hostId: number, body: Partial<NpmHostSettings>) => request<{ changed: string[]; host: NpmHost }>(`/api/npm/${integrationId}/hosts/${hostId}`, { method: "PATCH", body: JSON.stringify(body) }),
setHostEnabled: (integrationId: number, hostId: number, enabled: boolean) => request<{ enabled: boolean; changed: boolean }>(`/api/npm/${integrationId}/hosts/${hostId}/enabled`, { method: "POST", body: JSON.stringify({ enabled }) }),
deleteHost: (integrationId: number, hostId: number, domain: string) => request<void>(`/api/npm/${integrationId}/hosts/${hostId}`, { method: "DELETE", body: JSON.stringify({ domain }) }),
},
homeAssistant: {
overview: () => request<HaOverview>("/api/home-assistant"),
+161
View File
@@ -0,0 +1,161 @@
import { useState, type FormEvent } from "react";
import { api, type NpmCertificate, type NpmHost, type NpmHostSettings } from "../api/client";
import { ErrorNotice } from "./Notice";
import { readableError } from "../utils/errors";
const DAY_MS = 86_400_000;
const certLabel = (c: NpmCertificate) => {
const d = c.expiresAt && Number.isFinite(Date.parse(c.expiresAt)) ? Math.floor((Date.parse(c.expiresAt) - Date.now()) / DAY_MS) : null;
return `${c.name}${d === null ? "" : d < 0 ? " — ran out" : ` — ${d} ${d === 1 ? "day" : "days"} left`}`;
};
/**
* Making a proxy host, or changing one, in Nginx Proxy Manager: its names, where it forwards to, an existing certificate and what is switched on. What needs a certificate (Force HTTPS, HTTP/2,
* HSTS) is switched off and cannot be ticked without one, because NPM would quietly undo it. A host's access list, locations and custom configuration are not here, and are left as they are.
*/
export default function ProxyHostForm({ integrationId, integrationName, certificates, host, onDone, onCancel }: { integrationId: number; integrationName: string; certificates: NpmCertificate[]; host?: NpmHost; onDone: (name: string) => void; onCancel: () => void }) {
const [names, setNames] = useState(host ? host.domains.join("\n") : "");
const [scheme, setScheme] = useState<"http" | "https">(host?.forwardScheme === "https" ? "https" : "http");
const [target, setTarget] = useState(host?.forwardHost ?? "");
const [port, setPort] = useState(String(host?.forwardPort ?? 80));
const [certificateId, setCertificateId] = useState<number | null>(host?.certificateId ?? null);
const [sslForced, setSslForced] = useState(host?.sslForced ?? false);
const [http2, setHttp2] = useState(host?.http2 ?? false);
const [hsts, setHsts] = useState(host?.hsts ?? false);
const [hstsSubdomains, setHstsSubdomains] = useState(host?.hstsSubdomains ?? false);
const [blockExploits, setBlockExploits] = useState(host?.blockExploits ?? true);
const [caching, setCaching] = useState(host?.caching ?? false);
const [websocket, setWebsocket] = useState(host?.websocket ?? false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const hasCert = certificateId !== null;
// What needs what: without a certificate nothing of the three can be on; HSTS needs HTTPS forced; its subdomains need HSTS.
const ssl = hasCert && sslForced;
const hstsOn = ssl && hsts;
function pickCertificate(value: string) {
const id = value === "" ? null : Number(value);
setCertificateId(id);
if (id === null) {
setSslForced(false);
setHttp2(false);
setHsts(false);
setHstsSubdomains(false);
}
}
async function submit(e: FormEvent) {
e.preventDefault();
if (busy) return;
const body: NpmHostSettings = {
domains: names.split(/[\n,]+/).map((s) => s.trim()).filter(Boolean),
scheme,
host: target.trim(),
port: Number(port),
certificateId,
sslForced: hasCert && sslForced,
http2: hasCert && http2,
hsts: ssl && hsts,
hstsSubdomains: hstsOn && hstsSubdomains,
blockExploits,
caching,
websocket,
};
setBusy(true);
setError(null);
try {
if (host) await api.npm.updateHost(integrationId, host.id, body);
else await api.npm.createHost(integrationId, body);
onDone(body.domains[0] ?? "the host");
} catch (err) {
setError(readableError(err));
setBusy(false);
}
}
const check = (id: string, label: string, checked: boolean, set: (v: boolean) => void, enabled = true) => (
<label className="form-check" key={id}>
<input type="checkbox" className="form-check-input" id={id} checked={checked} disabled={!enabled} onChange={(e) => set(e.target.checked)} />
<span className="form-check-label">{label}</span>
</label>
);
return (
<form onSubmit={submit} className="card mb-3">
<div className="card-header">
<h3 className="card-title">{host ? `Change ${host.domains[0]}` : "New proxy host"}</h3>
<div className="card-actions text-secondary small">{integrationName}</div>
</div>
<div className="card-body">
<ErrorNotice error={error} />
<div className="mb-3">
<label className="form-label" htmlFor="ph-names">
Names
</label>
<textarea id="ph-names" className="form-control" rows={2} required autoFocus placeholder={"app.example.com\nwww.app.example.com"} value={names} onChange={(e) => setNames(e.target.value)} />
<div className="text-secondary small">The names people type, one to a line. Written in lower case; a name another host has is refused by NPM.</div>
</div>
<div className="row g-2 mb-3">
<div className="col-md-2">
<label className="form-label" htmlFor="ph-scheme">
Forwards by
</label>
<select id="ph-scheme" className="form-select" value={scheme} onChange={(e) => setScheme(e.target.value as "http" | "https")}>
<option value="http">http</option>
<option value="https">https</option>
</select>
</div>
<div className="col-md-7">
<label className="form-label" htmlFor="ph-host">
To host or address
</label>
<input id="ph-host" className="form-control" required maxLength={255} autoComplete="off" placeholder="10.0.0.5" value={target} onChange={(e) => setTarget(e.target.value)} />
</div>
<div className="col-md-3">
<label className="form-label" htmlFor="ph-port">
Port
</label>
<input id="ph-port" className="form-control" type="number" min={1} max={65535} required value={port} onChange={(e) => setPort(e.target.value)} />
</div>
</div>
<div className="mb-3">
<label className="form-label" htmlFor="ph-cert">
Certificate
</label>
<select id="ph-cert" className="form-select" value={certificateId === null ? "" : String(certificateId)} onChange={(e) => pickCertificate(e.target.value)}>
<option value="">None (plain HTTP)</option>
{certificates.map((c) => (
<option key={c.id} value={c.id}>
{certLabel(c)}
</option>
))}
</select>
<div className="text-secondary small">One NPM already has. Getting a new certificate is done in NPM.</div>
</div>
<div className="row mb-1">
<div className="col-md-6">
{check("ph-ssl", "Force HTTPS", sslForced && hasCert, setSslForced, hasCert)}
{check("ph-http2", "HTTP/2", http2 && hasCert, setHttp2, hasCert)}
{check("ph-hsts", "HSTS", hsts && ssl, (v) => { setHsts(v); if (!v) setHstsSubdomains(false); }, ssl)}
{check("ph-hsts-sub", "HSTS for subdomains", hstsSubdomains && hstsOn, setHstsSubdomains, hstsOn)}
{!hasCert && <div className="text-secondary small mb-2">These need a certificate.</div>}
</div>
<div className="col-md-6">
{check("ph-block", "Block common exploits", blockExploits, setBlockExploits)}
{check("ph-cache", "Cache assets", caching, setCaching)}
{check("ph-ws", "Websockets support", websocket, setWebsocket)}
</div>
</div>
</div>
<div className="card-footer d-flex gap-2">
<button type="submit" className="btn btn-primary" disabled={busy || names.trim() === "" || target.trim() === ""}>
{busy ? "Saving…" : host ? "Save" : "Make proxy host"}
</button>
<button type="button" className="btn btn-link text-secondary" onClick={onCancel} disabled={busy}>
Cancel
</button>
</div>
</form>
);
}
+110 -3
View File
@@ -1,5 +1,6 @@
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";
@@ -12,11 +13,12 @@ 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";
type Row = NpmHost & { integrationName: string; domain: string; target: string; certDays: number | null; certName: string; statusRank: number; serverName: string };
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);
@@ -84,6 +86,8 @@ export default function ProxyHosts({ user }: { user: CurrentUser }) {
(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}` : ""}`,
@@ -95,6 +99,51 @@ export default function ProxyHosts({ user }: { user: CurrentUser }) {
),
[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);
@@ -117,6 +166,11 @@ export default function ProxyHosts({ user }: { user: CurrentUser }) {
<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>
@@ -124,9 +178,44 @@ export default function ProxyHosts({ user }: { user: CurrentUser }) {
)}
</div>
<div className="text-secondary mb-3">
What Nginx Proxy Manager serves: the name, where it forwards to, the certificate and whether NPM could set it up. It only reads — nothing here changes anything in NPM. A certificate in its last
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&rsquo;t set up, is an alert.
</div>
{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} />}
@@ -197,10 +286,11 @@ export default function ProxyHosts({ user }: { user: CurrentUser }) {
<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={4} title="No proxy hosts" filtered={tableSearch.active ? () => tableSearch.setQuery("") : undefined} />}
{(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>
@@ -228,6 +318,23 @@ export default function ProxyHosts({ user }: { user: CurrentUser }) {
<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>