From 4dd7901f1cd831f1d66c675f628315ae077cbe1e Mon Sep 17 00:00:00 2001 From: Bobban Rydh Date: Tue, 3 Nov 2026 19:24:00 +0100 Subject: [PATCH] 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 --- INTEGRATIONS.md | 11 +- README.md | 2 +- ROLES.md | 2 +- server/src/integrations/fieldSchemas.ts | 2 + server/src/integrations/httpJson.ts | 2 +- server/src/integrations/npm/adapter.ts | 20 +- server/src/integrations/npm/hostPlan.ts | 105 +++++ server/src/integrations/npm/manage.ts | 107 +++++ server/src/routes/npm.ts | 214 +++++++++- server/test/npmProxyHosts.test.ts | 531 ++++++++++++++++++++++++ web/src/api/client.ts | 30 +- web/src/components/ProxyHostForm.tsx | 161 +++++++ web/src/pages/ProxyHosts.tsx | 113 ++++- 13 files changed, 1286 insertions(+), 14 deletions(-) create mode 100644 server/src/integrations/npm/hostPlan.ts create mode 100644 server/src/integrations/npm/manage.ts create mode 100644 server/test/npmProxyHosts.test.ts create mode 100644 web/src/components/ProxyHostForm.tsx diff --git a/INTEGRATIONS.md b/INTEGRATIONS.md index 8c9ba1e..e108fe1 100644 --- a/INTEGRATIONS.md +++ b/INTEGRATIONS.md @@ -315,9 +315,9 @@ osTicket's API cannot close a ticket, so this is the one place in the app that * ### Nginx Proxy Manager -- **Config fields:** NPM's admin URL (the address of its web page, usually port 81), an email and a password, and a checkbox to allow a self-signed certificate. +- **Config fields:** NPM's admin URL (the address of its web page, usually port 81), an email and a password, optionally a second **email and password for managing** proxy hosts (below), and a checkbox to allow a self-signed certificate. - **Required access:** NPM has no API keys: its API is the one its own web page uses, so the app signs in with an email and password (each read signs in again; nothing is kept). Make a **dedicated user** under - *Users* and, under its *Permissions*, give it **View only** on *Proxy Hosts* and *SSL Certificates* — that is all that is read. **Nothing is ever written** to NPM. + *Users* and, under its *Permissions*, give it **View only** on *Proxy Hosts* and *SSL Certificates* — that is all that is read, and this user **never writes**: reading NPM sends nothing but `GET` requests. - **What it does:** when **Network → Proxy hosts** is opened (and for the alerts and the suggested checks, at most once a minute) NPM is asked for its proxy hosts and certificates. Nothing is stored in the database: what is shown is what NPM said a minute ago. - Each host shows its names, where it forwards to — and the server that is, when the address (or name) is one of a server's own, exactly — its certificate and whether it is working. @@ -325,7 +325,12 @@ osTicket's API cannot close a ticket, so this is the one place in the app that * is a **monitoring** alert. A host that is switched off is left alone. Both link to the Proxy hosts page and can be silenced with maintenance on the integration. - The hosts it serves are offered as **Endpoints → Suggested** checks (a web check on the name people use; https when there is a certificate), linked to the server it forwards to. - If NPM cannot be read, the Alerts page says it could not check, and the integration is raised as failing like any other. -- **Not verified against a live NPM** — built from the API its own web page uses (`/api/tokens`, `/api/nginx/proxy-hosts?expand=certificate`, `/api/nginx/certificates`) and tried against a pretend one. Every +- **Managing proxy hosts (optional, administrators only):** with a second user in *Email of a user that may manage* and *Password of that user* — a user with **Manage** on *Proxy Hosts*, **without two-factor sign-in** (NPM's API can't complete that from here); give it only if you want this — **Network → Proxy hosts** gets **New proxy host** and, on each row, **Edit**, **Switch off / on** and **Delete**: + - **Make / change** (`POST /api/nginx/proxy-hosts`, `PUT …/{id}`): the **names**, where it **forwards to** (http or https, a host or address, a port), an **existing certificate**, and what is switched on — Force HTTPS, HTTP/2, HSTS (and for subdomains), block common exploits, cache assets, websockets. Names are written lower case and must be names NPM takes; a name another host has is NPM's own refusal, shown as it was said. Getting a *new* certificate is done in NPM. + - **Only what differs is sent** when a host is changed, and a host's **access list, locations and custom nginx configuration are never sent**, so they stay as they are. NPM quietly turns Force HTTPS and HTTP/2 off for a host with no certificate (and HSTS when HTTPS is not forced), so those combinations are refused here with the reason, and the form does not let them be ticked. + - **Switch off / on** (`POST …/{id}/disable` and `…/enable`): off, NPM stops serving the names; nothing is lost. **Delete** (`DELETE …/{id}`): NPM stops serving them and keeps the record out of sight; **the host's first name has to be typed**, and the server checks it against the host as NPM has it now, so a page that is minutes old or a wrong id cannot delete another host. + - Every call **signs in again** as the managing user (nothing is kept); the user that reads is never used to write. What this app has read of NPM is read again after a change. *Stop managing* is under Integrations → edit (removing the two fields, or `DELETE /api/npm/{id}/manage`, which keeps the reading user). Written in the audit log: who made, changed, switched or deleted which host (its names and what it forwards to, and which settings changed — never a password). +- **Not verified against a live NPM** — built from the API its own web page uses (`/api/tokens`, `/api/nginx/proxy-hosts?expand=certificate`, `/api/nginx/certificates`, and for managing `/api/nginx/proxy-hosts` with `POST`, `PUT`, `DELETE` and `…/enable`, `…/disable`) and tried against a pretend one. Every field is read defensively. If a read fails or comes back empty, the **Diagnostic Log** has what NPM answered. ### Home Assistant diff --git a/README.md b/README.md index f0a2828..87a84f4 100644 --- a/README.md +++ b/README.md @@ -980,7 +980,7 @@ points as a tree by what each is connected through, with the servers plugged int **Nginx Proxy Manager.** Add it under Integrations (a user that may only *view* proxy hosts and certificates is enough; see INTEGRATIONS.md) and **Network → Proxy hosts** lists each name it serves, where it forwards to (and which server that is, when the address is one the app knows), its certificate and whether NPM could set the host up. A certificate in use that ends within 14 days (critical in the last three), or has ended, and a host NPM itself says is not working, are alerts; a host that is switched off is left alone. The hosts it serves are also offered as endpoint checks (Endpoints → Suggested) on the name people really use, linked to the -server it forwards to. It only reads. +server it forwards to. It only reads — unless you give the integration a second user that may *manage* proxy hosts: then an administrator can make, change, switch off and delete hosts from that page (only what differs is sent, a host's access list and custom configuration are never touched, deleting asks for the host's first name, and every change is in the audit log). **Home Assistant.** Add it under Integrations with a long-lived access token (made at the bottom of your profile page in Home Assistant). **Apps → Home Assistant** is where you *choose* the few entities worth an alert — a UPS battery, a freezer's temperature, a pump — not all of them. Each is read every five minutes; a number keeps a history (35 days, with a chart), and you can set a limit under and/or over which it is an alert. diff --git a/ROLES.md b/ROLES.md index c85b447..b2e1ba2 100644 --- a/ROLES.md +++ b/ROLES.md @@ -150,7 +150,7 @@ even further, to admin only: - **Customise** (the dashboard): everyone signed in can hide and move the dashboard's cards for themselves; it is kept on their own user record and changes nothing for anyone else. - **To do and Notes** (Operations → To do, the *To do* card on the dashboard, the *To do* and *Notes* cards on a server's page, a device's *Notes* drawer): everyone signed in reads them; adding, editing, ticking off and removing a job, and writing a note, and adding, captioning and removing a photo on one, need operator. - **Racks** (Inventory → Racks) and the **network diagram**: everyone signed in. A rack is made from the hardware's *where* and *rack unit*, which operators edit on the inventory page. -- **Proxy hosts** (Network → Proxy hosts): everyone signed in sees what Nginx Proxy Manager serves; **Read now** needs operator; adding the integration (its login) is an administrator's job. +- **Proxy hosts** (Network → Proxy hosts): everyone signed in sees what Nginx Proxy Manager serves; **Read now** needs operator; adding the integration (its login) is an administrator's job, and so is **making, changing, switching off and deleting a proxy host** — only where the integration was given a user that may manage. - **Home Assistant** (Apps → Home Assistant): everyone signed in sees what is watched, its state and history; choosing what to watch, its limits, stopping and **Read now** need operator (the list of all entities is read live, so only operators see it); adding the integration (its token) is an administrator's job. - **Service levels** (Monitoring → Service levels): everyone signed in sees the targets and what is left of the budget; setting, changing and removing one is administrator-only, and each is in the audit log. diff --git a/server/src/integrations/fieldSchemas.ts b/server/src/integrations/fieldSchemas.ts index e25f0df..574dea7 100644 --- a/server/src/integrations/fieldSchemas.ts +++ b/server/src/integrations/fieldSchemas.ts @@ -92,6 +92,8 @@ export const INTEGRATION_FIELDS: Partial; body?: unknown; insecure?: boolean; timeoutMs?: number } = {}): Promise { +export function requestJson(url: string, opts: { method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE"; headers?: Record; body?: unknown; insecure?: boolean; timeoutMs?: number } = {}): Promise { return new Promise((resolve, reject) => { let parsed: URL; try { diff --git a/server/src/integrations/npm/adapter.ts b/server/src/integrations/npm/adapter.ts index 312787c..61b7acb 100644 --- a/server/src/integrations/npm/adapter.ts +++ b/server/src/integrations/npm/adapter.ts @@ -5,6 +5,7 @@ * NPM has no API keys: its API is the one its own web page uses, and signs in with the administrator's email and password (`POST /api/tokens` answers with a bearer * token, which the rest take). So this logs in for each read — and only ever reads: the proxy hosts (what is proxied to what, with its certificate) and the * certificates. Use a dedicated user with the "view only" permission on proxy hosts and certificates (Users → Permissions) rather than the administrator's own. + * Managing the hosts is ./manage.ts, with a user of its own. * * Endpoints and field names are from NPM's own API as the web page uses it (`/api/nginx/proxy-hosts?expand=certificate`, `/api/nginx/certificates`), and have * not been checked against a live NPM here; every field is read defensively, so one a version renames is left blank rather than breaking the read. @@ -36,6 +37,15 @@ export interface NpmProxyHost { forwardPort: number | null; enabled: boolean; sslForced: boolean; + /** What else is switched on for the host. */ + http2: boolean; + hsts: boolean; + hstsSubdomains: boolean; + blockExploits: boolean; + caching: boolean; + websocket: boolean; + /** The certificate it uses, by id (even when NPM did not say which it is); null for none. */ + certificateId: number | null; certificate: { id: number; name: string; expiresAt: string | null } | null; /** NPM says its nginx did not accept this host's configuration. */ online: boolean; @@ -59,6 +69,7 @@ const num = (v: unknown): number | null => { const n = typeof v === "number" ? v : typeof v === "string" && v.trim() !== "" ? Number(v) : NaN; return Number.isFinite(n) ? n : null; }; +const on = (v: unknown): boolean => v === true || v === 1; const domainsOf = (v: unknown): string[] => (Array.isArray(v) ? v.filter((d): d is string => typeof d === "string" && d !== "") : []); /** NPM writes times as "2026-12-31 23:59:59" (UTC) or as ISO; either becomes ISO. */ @@ -90,7 +101,14 @@ export function hostFrom(raw: unknown): NpmProxyHost | null { forwardHost: str(h.forward_host) ?? "", forwardPort: num(h.forward_port), enabled: h.enabled !== false && h.enabled !== 0, - sslForced: h.ssl_forced === true || h.ssl_forced === 1, + sslForced: on(h.ssl_forced), + http2: on(h.http2_support), + hsts: on(h.hsts_enabled), + hstsSubdomains: on(h.hsts_subdomains), + blockExploits: on(h.block_exploits), + caching: on(h.caching_enabled), + websocket: on(h.allow_websocket_upgrade), + certificateId: (num(h.certificate_id) ?? 0) > 0 ? num(h.certificate_id) : cert ? cert.id : null, certificate: cert ? { id: cert.id, name: cert.name, expiresAt: cert.expiresAt } : null, // NPM says "online" unless its own check of the generated configuration failed. online: meta.nginx_online !== false && !err, diff --git a/server/src/integrations/npm/hostPlan.ts b/server/src/integrations/npm/hostPlan.ts new file mode 100644 index 0000000..a77b72b --- /dev/null +++ b/server/src/integrations/npm/hostPlan.ts @@ -0,0 +1,105 @@ +/** + * What a proxy host is made of, as this app edits it, and how a change of it is checked and planned for Nginx Proxy Manager. Pure: nothing here talks to NPM. + * + * The settings are the ones a normal edit of a host in NPM changes — the names, where it forwards to, its certificate and what is switched on for it. A host's access list, its locations, its + * custom nginx configuration and its own bookkeeping are not here, and a change never sends them, so they stay as they are (NPM updates only what it is sent). + * + * NPM quietly turns Force HTTPS and HTTP/2 off for a host with no certificate, HSTS off when HTTPS is not forced, and HSTS for subdomains off when HSTS is off. Rather than let a choice vanish + * unseen, such a combination is refused here, with the reason. + */ +import type { NpmProxyHost } from "./adapter.js"; + +export interface HostSettings { + domains: string[]; + scheme: "http" | "https"; + host: string; + port: number; + /** An existing certificate; null for none. */ + certificateId: number | null; + sslForced: boolean; + http2: boolean; + hsts: boolean; + hstsSubdomains: boolean; + blockExploits: boolean; + caching: boolean; + websocket: boolean; +} + +/** NPM's own rule for a name: nothing that is not part of one. */ +const DOMAIN_PATTERN = /^[^&| @!#%^();:/\\}{=+?<>,~`'"]+$/; + +/** A name as it is to be kept — lower case, no space round it — or null when it is not one NPM takes. */ +export function normaliseDomain(input: string): string | null { + const s = input.trim().toLowerCase(); + return s !== "" && s.length <= 253 && DOMAIN_PATTERN.test(s) ? s : null; +} + +/** Whether a combination of settings is one NPM will keep as it is: an error says what to change, null says it is fine. */ +export function checkHost(s: HostSettings): string | null { + if (s.domains.length === 0) return "A proxy host needs at least one name."; + if (s.domains.length > 100) return "A proxy host can have at most 100 names."; + if (new Set(s.domains).size !== s.domains.length) return "A name is in the list twice."; + const bad = s.domains.find((d) => normaliseDomain(d) !== d); + if (bad !== undefined) return `"${bad}" is not a name NPM takes: it has a space or one of & | @ ! # % ^ ( ) ; : / \\ } { = + ? < > , ~ \` ' ".`; + if (!/^[^\s]{1,255}$/.test(s.host)) return "Where to forward to is a host name or an address, without spaces."; + if (!Number.isInteger(s.port) || s.port < 1 || s.port > 65535) return "The port is a number from 1 to 65535."; + if (s.certificateId === null && (s.sslForced || s.http2 || s.hsts)) return "Force HTTPS, HTTP/2 and HSTS need a certificate."; + if (s.hsts && !s.sslForced) return "HSTS needs Force HTTPS."; + if (s.hstsSubdomains && !s.hsts) return "HSTS for subdomains needs HSTS."; + return null; +} + +/** The settings a host has now. */ +export function settingsOf(h: NpmProxyHost): HostSettings { + return { + domains: h.domains, + scheme: h.forwardScheme === "https" ? "https" : "http", + host: h.forwardHost, + port: h.forwardPort ?? 80, + certificateId: h.certificateId, + sslForced: h.sslForced, + http2: h.http2, + hsts: h.hsts, + hstsSubdomains: h.hstsSubdomains, + blockExploits: h.blockExploits, + caching: h.caching, + websocket: h.websocket, + }; +} + +/** The names NPM's API gives each setting. */ +const FIELDS: { key: keyof HostSettings; api: string }[] = [ + { key: "domains", api: "domain_names" }, + { key: "scheme", api: "forward_scheme" }, + { key: "host", api: "forward_host" }, + { key: "port", api: "forward_port" }, + { key: "certificateId", api: "certificate_id" }, + { key: "sslForced", api: "ssl_forced" }, + { key: "http2", api: "http2_support" }, + { key: "hsts", api: "hsts_enabled" }, + { key: "hstsSubdomains", api: "hsts_subdomains" }, + { key: "blockExploits", api: "block_exploits" }, + { key: "caching", api: "caching_enabled" }, + { key: "websocket", api: "allow_websocket_upgrade" }, +]; + +const valueForApi = (key: keyof HostSettings, v: HostSettings[keyof HostSettings]) => (key === "certificateId" ? (v === null ? 0 : v) : v); + +/** The body that makes a host with these settings. A host is made on, and without a certificate has the certificate id 0. */ +export function createBody(s: HostSettings): Record { + return Object.fromEntries(FIELDS.map((f) => [f.api, valueForApi(f.key, s[f.key])])); +} + +export type HostPlan = { send: Record; changed: (keyof HostSettings)[] } | { error: string }; + +const same = (a: unknown, b: unknown) => (Array.isArray(a) && Array.isArray(b) ? a.length === b.length && a.every((x, i) => x === b[i]) : a === b); + +/** What to send to make a host that has `current` have what was asked: only the settings that differ, after the whole is checked. No change is not an error: `changed` is empty. */ +export function planHostEdit(current: HostSettings, wanted: Partial): HostPlan { + const final: HostSettings = { ...current, ...wanted, domains: wanted.domains ?? current.domains }; + const problem = checkHost(final); + if (problem !== null) return { error: problem }; + const changed = FIELDS.filter((f) => !same(final[f.key], current[f.key])).map((f) => f.key); + const send = Object.fromEntries(FIELDS.filter((f) => changed.includes(f.key)).map((f) => [f.api, valueForApi(f.key, final[f.key])])); + return { send, changed }; +} diff --git a/server/src/integrations/npm/manage.ts b/server/src/integrations/npm/manage.ts new file mode 100644 index 0000000..e0d2fa6 --- /dev/null +++ b/server/src/integrations/npm/manage.ts @@ -0,0 +1,107 @@ +/** + * Managing the proxy hosts of Nginx Proxy Manager: making one, changing one, switching one off and on, deleting one. It is kept apart from the adapter that reads (./adapter.ts, which only ever + * reads, with the integration's own view-only user) and signs in as a user of its own — `manageEmail` and `managePassword`, optional, a user with **Manage** on Proxy Hosts — so an NPM that is + * only watched is never written to. + * + * NPM has no API keys: each call signs in again (`POST /api/tokens`) and nothing is kept. The calls are the ones its own page makes: `POST /api/nginx/proxy-hosts`, `PUT …/{id}` (only what is + * sent is changed), `POST …/{id}/enable` and `…/disable`, `DELETE …/{id}`. A user with two-factor sign-in cannot be used. Not checked against a live NPM; its answers are read defensively. + */ +import { requestJson } from "../httpJson.js"; +import { withDiagLogging } from "../../services/diagLog.js"; +import { hostFrom, type NpmProxyHost } from "./adapter.js"; +import { createBody, type HostSettings } from "./hostPlan.js"; + +export interface NpmManageConfig { + url: string; + manageEmail: string; + managePassword: string; + insecure?: boolean; +} + +/** How a call failed: `invalid` — NPM looked at it and said no (a name already used); `denied` — the user is not accepted or may not manage; `missing` — no such host; `failed` — no answer, or nonsense. */ +export class NpmManageError extends Error { + constructor(message: string, readonly kind: "invalid" | "denied" | "missing" | "failed") { + super(message); + } +} + +export interface NpmManageAdapter { + getHost(id: number): Promise; + createHost(settings: HostSettings): Promise; + /** Changes only what is in `body` (NPM's own names for the settings). */ + updateHost(id: number, body: Record): Promise; + setEnabled(id: number, enabled: boolean): Promise; + deleteHost(id: number): Promise; +} + +const obj = (v: unknown): Record => (v !== null && typeof v === "object" && !Array.isArray(v) ? (v as Record) : {}); +const str = (v: unknown): string | null => (typeof v === "string" && v.trim() !== "" ? v.trim() : null); + +const wholeNumber = (id: number): number => { + if (!Number.isInteger(id) || id <= 0) throw new NpmManageError("That is not a proxy host id", "invalid"); + return id; +}; + +export function createNpmManageAdapter(config: NpmManageConfig): NpmManageAdapter { + const base = String(config.url ?? "").replace(/\/+$/, ""); + const insecure = config.insecure === true; + + async function login(): Promise { + let res; + try { + res = await requestJson(`${base}/api/tokens`, { method: "POST", body: { identity: config.manageEmail, secret: config.managePassword }, insecure }); + } catch (err) { + throw new NpmManageError(`Nginx Proxy Manager could not be reached: ${err instanceof Error ? err.message : String(err)}`, "failed"); + } + if (obj(res.json).requires_2fa === true) throw new NpmManageError("That user has two-factor sign-in, which can't be used from here — use a user without it", "denied"); + if (res.status === 400 || res.status === 401 || res.status === 403) throw new NpmManageError("Nginx Proxy Manager did not accept the email and password for managing", "denied"); + const token = str(obj(res.json).token); + if (res.status < 200 || res.status >= 300 || !token) throw new NpmManageError(`Nginx Proxy Manager sign-in failed: HTTP ${res.status}`, "failed"); + return token; + } + + /** One call, signed in; what is returned is the JSON it answered with (null for none). */ + async function call(method: "GET" | "POST" | "PUT" | "DELETE", path: string, body?: unknown): Promise { + const token = await login(); + let res; + try { + res = await requestJson(`${base}${path}`, { method, headers: { Authorization: `Bearer ${token}` }, body, insecure }); + } catch (err) { + throw new NpmManageError(`Nginx Proxy Manager could not be reached: ${err instanceof Error ? err.message : String(err)}`, "failed"); + } + const said = str(obj(obj(res.json).error).message); + if (res.status === 401 || res.status === 403) throw new NpmManageError("Nginx Proxy Manager did not allow that — the user needs Manage on Proxy Hosts", "denied"); + if (res.status === 404) throw new NpmManageError(said ?? "Nginx Proxy Manager has no such proxy host", "missing"); + if (res.status === 400) throw new NpmManageError(said ?? "Nginx Proxy Manager did not accept that", "invalid"); + if (res.status < 200 || res.status >= 300) throw new NpmManageError(said ?? `Nginx Proxy Manager error: HTTP ${res.status}`, "failed"); + return res.json; + } + + const host = (raw: unknown): NpmProxyHost => { + const h = hostFrom(raw); + if (!h) throw new NpmManageError("Nginx Proxy Manager answered, but not with a proxy host", "failed"); + return h; + }; + + async function getHost(id: number): Promise { + return host(await call("GET", `/api/nginx/proxy-hosts/${wholeNumber(id)}?expand=certificate`)); + } + + async function createHost(settings: HostSettings): Promise { + return host(await call("POST", "/api/nginx/proxy-hosts", createBody(settings))); + } + + async function updateHost(id: number, body: Record): Promise { + return host(await call("PUT", `/api/nginx/proxy-hosts/${wholeNumber(id)}`, body)); + } + + async function setEnabled(id: number, enabled: boolean): Promise { + await call("POST", `/api/nginx/proxy-hosts/${wholeNumber(id)}/${enabled ? "enable" : "disable"}`); + } + + async function deleteHost(id: number): Promise { + await call("DELETE", `/api/nginx/proxy-hosts/${wholeNumber(id)}`); + } + + return withDiagLogging("npm", { getHost, createHost, updateHost, setEnabled, deleteHost }); +} diff --git a/server/src/routes/npm.ts b/server/src/routes/npm.ts index dd8662a..fe6277a 100644 --- a/server/src/routes/npm.ts +++ b/server/src/routes/npm.ts @@ -1,7 +1,15 @@ -import { Router } from "express"; +import { Router, type Response } from "express"; +import { eq } from "drizzle-orm"; +import { z } from "zod"; import { db } from "../db/client.js"; -import { servers } from "../db/schema.js"; -import { requireAuth } from "../auth/middleware.js"; +import { integrationCredentials, integrations, servers } from "../db/schema.js"; +import { requireAuth, requireRole } from "../auth/middleware.js"; +import { decryptSecret, encryptSecret } from "../crypto.js"; +import { loadIntegrationConfig } from "../integrations/loadIntegration.js"; +import { checkHost, normaliseDomain, planHostEdit, settingsOf, type HostSettings } from "../integrations/npm/hostPlan.js"; +import { createNpmManageAdapter, NpmManageError, type NpmManageAdapter } from "../integrations/npm/manage.js"; +import { invalidateAlertsCache } from "../services/alerts.js"; +import { recordAudit } from "../services/audit.js"; import { npmIntegrationIds, npmProblems, readNpm } from "../services/npmReader.js"; import { matchServerForTarget } from "../services/uptimeKumaMatch.js"; import { asyncHandler } from "../utils/asyncHandler.js"; @@ -29,9 +37,12 @@ npmRouter.get("/", asyncHandler(async (req, res) => { const out = []; for (const i of await npmIntegrationIds()) { const read = await readNpm(i.id, force); + // Whether it has a user to manage with — only that, never what it is. + const canManage = await loadIntegrationConfig(i.id).then((l) => !!l && hasManageLogin(l.config)).catch(() => false); out.push({ id: i.id, name: i.name, + canManage, readAt: read.at, error: read.error, version: read.snapshot?.version ?? null, @@ -45,3 +56,200 @@ npmRouter.get("/", asyncHandler(async (req, res) => { } res.json({ integrations: out }); })); + +// ─── Managing proxy hosts ───────────────────────────────────────────────────── +// +// Only for an administrator, and only for an NPM that was given a user to manage with (manageEmail, managePassword): the user that reads is view-only and is never used to write. + +const hasManageLogin = (config: Record) => typeof config.manageEmail === "string" && config.manageEmail.trim() !== "" && typeof config.managePassword === "string" && config.managePassword !== ""; + +/** The adapter that manages one NPM, or the answer to send when there is not one to use. */ +async function manageAdapterFor(rawId: string, res: Response): Promise<{ adapter: NpmManageAdapter; id: number; name: string } | null> { + const id = /^\d+$/.test(rawId) ? Number(rawId) : Number.NaN; + if (!Number.isInteger(id)) { + res.status(400).json({ error: "invalid_id" }); + return null; + } + const loaded = await loadIntegrationConfig(id); + if (!loaded) { + res.status(404).json({ error: "not_found" }); + return null; + } + if (loaded.integration.type !== "npm") { + res.status(400).json({ error: "wrong_type" }); + return null; + } + if (!loaded.integration.enabled) { + res.status(400).json({ error: "integration_disabled", message: "This Nginx Proxy Manager is switched off." }); + return null; + } + if (!hasManageLogin(loaded.config)) { + res.status(400).json({ error: "no_manage_login", message: "This Nginx Proxy Manager has no user to manage with. Add one under Integrations → edit." }); + return null; + } + return { adapter: createNpmManageAdapter({ url: String(loaded.config.url ?? ""), manageEmail: String(loaded.config.manageEmail), managePassword: String(loaded.config.managePassword), insecure: loaded.config.insecure === true }), id, name: loaded.integration.name }; +} + +function manageFailure(res: Response, err: unknown) { + if (err instanceof NpmManageError) return res.status(err.kind === "invalid" ? 400 : err.kind === "missing" ? 404 : 502).json({ error: `npm_${err.kind}`, message: err.message }); + return res.status(502).json({ error: "npm_failed", message: err instanceof Error ? err.message : String(err) }); +} + +const hostIdOf = (raw: string) => (/^\d{1,9}$/.test(raw) && Number(raw) > 0 ? Number(raw) : Number.NaN); + +/** After a change, what is read of NPM is read again, so the page and the alerts show it. */ +async function refreshAfterChange(integrationId: number) { + await readNpm(integrationId, true).catch(() => undefined); + invalidateAlertsCache(); +} + +const settingsSchema = z.object({ + domains: z.array(z.string().max(300)).min(1, "A proxy host needs at least one name.").max(100), + scheme: z.enum(["http", "https"]), + host: z.string().trim().min(1, "Say where to forward to.").max(255), + port: z.number().int().min(1).max(65535), + certificateId: z.number().int().positive().nullable(), + sslForced: z.boolean(), + http2: z.boolean(), + hsts: z.boolean(), + hstsSubdomains: z.boolean(), + blockExploits: z.boolean(), + caching: z.boolean(), + websocket: z.boolean(), +}); + +/** The names written the way NPM keeps them, or a message naming the one that is not a name. */ +function normaliseDomains(domains: string[]): { domains: string[] } | { error: string } { + const out: string[] = []; + for (const d of domains) { + const n = normaliseDomain(d); + if (n === null) return { error: `"${d}" is not a name NPM takes: no spaces, and none of & | @ ! # % ^ ( ) ; : / \\ } { = + ? < > , ~ \` ' ".` }; + if (!out.includes(n)) out.push(n); + } + return { domains: out }; +} + +/** Makes a proxy host. Its names, where it forwards to, an existing certificate and what is switched on; NPM says no to a name that another host has. */ +npmRouter.post("/:id/hosts", requireRole("admin"), asyncHandler(async (req, res) => { + const parsed = settingsSchema.safeParse(req.body); + if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: parsed.error.issues[0]?.message ?? "That is not a proxy host.", details: parsed.error.flatten() }); + const names = normaliseDomains(parsed.data.domains); + if ("error" in names) return res.status(400).json({ error: "invalid_host", message: names.error }); + const settings = { ...parsed.data, domains: names.domains }; + const problem = checkHost(settings); + if (problem !== null) return res.status(400).json({ error: "invalid_host", message: problem }); + const target = await manageAdapterFor(req.params.id, res); + if (!target) return; + try { + const host = await target.adapter.createHost(settings); + await recordAudit({ actor: req.currentUser!, category: "integration", action: "create_proxy_host", targetType: "proxy_host", targetId: host.id, detail: { integrationId: target.id, integration: target.name, domains: host.domains, forwardsTo: `${settings.scheme}://${settings.host}:${settings.port}` } }); + await refreshAfterChange(target.id); + res.status(201).json({ host }); + } catch (err) { + manageFailure(res, err); + } +})); + +/** Changes a proxy host: only what differs from the host as NPM has it now is sent, and only after the whole is checked. Its access list, locations and custom configuration are not touched. */ +npmRouter.patch("/:id/hosts/:hostId", requireRole("admin"), asyncHandler(async (req, res) => { + const parsed = settingsSchema.partial().strict().safeParse(req.body); + if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: parsed.error.issues[0]?.message ?? "That is not a change of a proxy host.", details: parsed.error.flatten() }); + const hostId = hostIdOf(req.params.hostId); + if (!Number.isInteger(hostId)) return res.status(400).json({ error: "invalid_host_id" }); + const wanted = { ...parsed.data } as Partial; + if (parsed.data.domains) { + const names = normaliseDomains(parsed.data.domains); + if ("error" in names) return res.status(400).json({ error: "invalid_host", message: names.error }); + wanted.domains = names.domains; + } + const target = await manageAdapterFor(req.params.id, res); + if (!target) return; + try { + const current = await target.adapter.getHost(hostId); + const plan = planHostEdit(settingsOf(current), wanted); + if ("error" in plan) return res.status(400).json({ error: "invalid_host", message: plan.error }); + if (plan.changed.length === 0) return res.json({ changed: [], host: current }); + const host = await target.adapter.updateHost(hostId, plan.send); + await recordAudit({ actor: req.currentUser!, category: "integration", action: "update_proxy_host", targetType: "proxy_host", targetId: hostId, detail: { integrationId: target.id, integration: target.name, domains: current.domains, changed: plan.changed } }); + await refreshAfterChange(target.id); + res.json({ changed: plan.changed, host }); + } catch (err) { + manageFailure(res, err); + } +})); + +const enabledSchema = z.object({ enabled: z.boolean() }); + +/** Switches a proxy host off or on again: off, NPM stops serving its names; nothing is lost. */ +npmRouter.post("/:id/hosts/:hostId/enabled", requireRole("admin"), asyncHandler(async (req, res) => { + const parsed = enabledSchema.safeParse(req.body); + if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: "Say whether the host is to be on or off." }); + const hostId = hostIdOf(req.params.hostId); + if (!Number.isInteger(hostId)) return res.status(400).json({ error: "invalid_host_id" }); + const target = await manageAdapterFor(req.params.id, res); + if (!target) return; + try { + const current = await target.adapter.getHost(hostId); + if (current.enabled === parsed.data.enabled) return res.json({ enabled: current.enabled, changed: false }); + await target.adapter.setEnabled(hostId, parsed.data.enabled); + await recordAudit({ actor: req.currentUser!, category: "integration", action: parsed.data.enabled ? "enable_proxy_host" : "disable_proxy_host", targetType: "proxy_host", targetId: hostId, detail: { integrationId: target.id, integration: target.name, domains: current.domains } }); + await refreshAfterChange(target.id); + res.json({ enabled: parsed.data.enabled, changed: true }); + } catch (err) { + manageFailure(res, err); + } +})); + +const deleteSchema = z.object({ domain: z.string().min(1).max(300) }); + +/** + * Deletes a proxy host: NPM stops serving its names. The host's first name has to be sent along and has to be the one it has now, so a page that is minutes old, or a wrong id, cannot delete + * another host. (NPM keeps a deleted host's record out of sight; the names can be used again.) + */ +npmRouter.delete("/:id/hosts/:hostId", requireRole("admin"), asyncHandler(async (req, res) => { + const parsed = deleteSchema.safeParse(req.body); + if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: "The first name of the host has to be sent along to delete it." }); + const hostId = hostIdOf(req.params.hostId); + if (!Number.isInteger(hostId)) return res.status(400).json({ error: "invalid_host_id" }); + const target = await manageAdapterFor(req.params.id, res); + if (!target) return; + try { + const current = await target.adapter.getHost(hostId); + if (parsed.data.domain.trim().toLowerCase() !== current.domains[0]) return res.status(400).json({ error: "name_mismatch", message: "That is not the first name of that host." }); + await target.adapter.deleteHost(hostId); + await recordAudit({ actor: req.currentUser!, category: "integration", action: "delete_proxy_host", targetType: "proxy_host", targetId: hostId, detail: { integrationId: target.id, integration: target.name, domains: current.domains, forwardsTo: `${current.forwardScheme}://${current.forwardHost}:${current.forwardPort ?? ""}` } }); + await refreshAfterChange(target.id); + res.status(204).end(); + } catch (err) { + manageFailure(res, err); + } +})); + +/** Takes the user for managing away again, leaving the one that reads. */ +npmRouter.delete("/:id/manage", requireRole("admin"), asyncHandler(async (req, res) => { + const id = /^\d+$/.test(req.params.id) ? Number(req.params.id) : Number.NaN; + if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" }); + const [row] = await db.select().from(integrations).where(eq(integrations.id, id)).limit(1); + if (!row) return res.status(404).json({ error: "not_found" }); + if (row.type !== "npm") return res.status(400).json({ error: "wrong_type" }); + let removed = false; + if (row.credentialId) { + const [cred] = await db.select().from(integrationCredentials).where(eq(integrationCredentials.id, row.credentialId)).limit(1); + if (cred) { + const secrets = JSON.parse(decryptSecret(cred.encryptedSecret)) as Record; + if ("managePassword" in secrets) { + delete secrets.managePassword; + await db.update(integrationCredentials).set({ encryptedSecret: encryptSecret(JSON.stringify(secrets)) }).where(eq(integrationCredentials.id, cred.id)); + removed = true; + } + } + } + const config = row.config ? (JSON.parse(row.config) as Record) : {}; + if ("manageEmail" in config) { + delete config.manageEmail; + await db.update(integrations).set({ config: JSON.stringify(config) }).where(eq(integrations.id, id)); + removed = true; + } + if (removed) await recordAudit({ actor: req.currentUser!, category: "integration", action: "remove_npm_manage_login", targetType: "integration", targetId: id, detail: { name: row.name } }); + res.status(204).end(); +})); diff --git a/server/test/npmProxyHosts.test.ts b/server/test/npmProxyHosts.test.ts new file mode 100644 index 0000000..48e53be --- /dev/null +++ b/server/test/npmProxyHosts.test.ts @@ -0,0 +1,531 @@ +/** + * Managing the proxy hosts of Nginx Proxy Manager: what a host's settings may be and what a change comes to, what is sent (only what differs), that the user that reads is never used to write, who + * may, what is refused before NPM is asked, what NPM says when it refuses, and what is written in the audit log. + * + * Run with: npm test --workspace server + */ +import { test, describe, before, after } from "node:test"; +import assert from "node:assert/strict"; +import { createServer as createHttpServer, type Server } from "node:http"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { AddressInfo } from "node:net"; + +const dir = mkdtempSync(join(tmpdir(), "hm-npm-manage-")); +process.env.DATABASE_PATH = join(dir, "test.sqlite"); +process.env.SESSION_DIR = join(dir, "sessions"); +process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32); + +const express = (await import("express")).default; +const { db } = await import("../src/db/client.js"); +const { users, integrations, integrationCredentials, auditLog } = await import("../src/db/schema.js"); +const { runMigrations } = await import("../src/db/migrate.js"); +const { encryptSecret } = await import("../src/crypto.js"); +const { INTEGRATION_FIELDS } = await import("../src/integrations/fieldSchemas.js"); +const { hostFrom } = await import("../src/integrations/npm/adapter.js"); +const plan = await import("../src/integrations/npm/hostPlan.js"); +const { createNpmManageAdapter } = await import("../src/integrations/npm/manage.js"); +const { loadIntegrationConfig } = await import("../src/integrations/loadIntegration.js"); +const { clearNpmCacheForTests } = await import("../src/services/npmReader.js"); +const { npmRouter } = await import("../src/routes/npm.js"); + +await runMigrations(); + +const settings = (over: Partial = {}): import("../src/integrations/npm/hostPlan.js").HostSettings => ({ + domains: ["app.example.com"], + scheme: "http", + host: "10.0.0.5", + port: 8080, + certificateId: null, + sslForced: false, + http2: false, + hsts: false, + hstsSubdomains: false, + blockExploits: true, + caching: false, + websocket: false, + ...over, +}); + +describe("what a proxy host may be", () => { + test("a name is written lower case, without a space round it; NPM's own idea of what is not a name is refused", () => { + assert.equal(plan.normaliseDomain(" App.Example.COM "), "app.example.com"); + assert.equal(plan.normaliseDomain("*.example.com"), "*.example.com"); + for (const bad of ["", " ", "a b.com", "a/b.com", "a@b.com", "a:80", "a,b.com", "a;b", "a?b", "a&b", "a|b", "a'b", 'a"b', "a`b", "x".repeat(254)]) assert.equal(plan.normaliseDomain(bad), null, JSON.stringify(bad)); + }); + + test("the whole is checked: names, where it forwards, and the combinations NPM would quietly undo", () => { + assert.equal(plan.checkHost(settings()), null); + assert.match(plan.checkHost(settings({ domains: [] })) ?? "", /at least one name/); + assert.match(plan.checkHost(settings({ domains: ["a.com", "a.com"] })) ?? "", /twice/); + assert.match(plan.checkHost(settings({ domains: ["A.com"] })) ?? "", /not a name NPM takes/); + assert.match(plan.checkHost(settings({ host: "a b" })) ?? "", /without spaces/); + assert.match(plan.checkHost(settings({ port: 0 })) ?? "", /1 to 65535/); + assert.match(plan.checkHost(settings({ port: 70000 })) ?? "", /1 to 65535/); + assert.match(plan.checkHost(settings({ sslForced: true })) ?? "", /need a certificate/); + assert.match(plan.checkHost(settings({ http2: true })) ?? "", /need a certificate/); + assert.match(plan.checkHost(settings({ certificateId: 3, hsts: true })) ?? "", /HSTS needs Force HTTPS/); + assert.match(plan.checkHost(settings({ certificateId: 3, sslForced: true, hstsSubdomains: true })) ?? "", /subdomains needs HSTS/); + assert.equal(plan.checkHost(settings({ certificateId: 3, sslForced: true, http2: true, hsts: true, hstsSubdomains: true })), null); + }); + + test("a host is made with NPM's own names for everything, and a certificate of none is 0", () => { + assert.deepEqual(plan.createBody(settings({ certificateId: 3, sslForced: true, websocket: true })), { + domain_names: ["app.example.com"], + forward_scheme: "http", + forward_host: "10.0.0.5", + forward_port: 8080, + certificate_id: 3, + ssl_forced: true, + http2_support: false, + hsts_enabled: false, + hsts_subdomains: false, + block_exploits: true, + caching_enabled: false, + allow_websocket_upgrade: true, + }); + assert.equal(plan.createBody(settings()).certificate_id, 0); + }); + + test("a change is only what differs, after the whole is checked; nothing different is nothing to send", () => { + const cur = settings({ certificateId: 3, sslForced: true }); + const p = plan.planHostEdit(cur, { port: 9090, websocket: true, sslForced: true }); + assert.deepEqual(p, { send: { forward_port: 9090, allow_websocket_upgrade: true }, changed: ["port", "websocket"] }); + assert.deepEqual(plan.planHostEdit(cur, { port: 8080, domains: ["app.example.com"] }), { send: {}, changed: [] }); + const names = plan.planHostEdit(cur, { domains: ["a.example.com", "b.example.com"] }); + assert.deepEqual(names, { send: { domain_names: ["a.example.com", "b.example.com"] }, changed: ["domains"] }); + }); + + test("taking the certificate away is only fine if what needs one goes with it; it is sent as 0", () => { + const cur = settings({ certificateId: 3, sslForced: true, http2: true }); + assert.match((plan.planHostEdit(cur, { certificateId: null }) as { error: string }).error, /need a certificate/); + const p = plan.planHostEdit(cur, { certificateId: null, sslForced: false, http2: false }); + assert.deepEqual(p, { send: { certificate_id: 0, ssl_forced: false, http2_support: false }, changed: ["certificateId", "sslForced", "http2"] }); + }); + + test("an edit that would leave something inconsistent is refused with the reason", () => { + assert.match((plan.planHostEdit(settings(), { sslForced: true }) as { error: string }).error, /need a certificate/); + assert.match((plan.planHostEdit(settings({ certificateId: 3, sslForced: true, hsts: true }), { sslForced: false }) as { error: string }).error, /HSTS needs Force HTTPS/); + }); +}); + +describe("what NPM says of a host", () => { + test("the settings are read, and the certificate id is the host's even when NPM did not say which certificate it is", () => { + const h = hostFrom({ id: 4, domain_names: ["a.com"], forward_scheme: "https", forward_host: "h", forward_port: "443", enabled: 1, ssl_forced: 1, http2_support: true, hsts_enabled: 0, hsts_subdomains: false, block_exploits: true, caching_enabled: 1, allow_websocket_upgrade: false, certificate_id: 7, certificate: null, meta: {} })!; + assert.deepEqual([h.forwardPort, h.sslForced, h.http2, h.hsts, h.blockExploits, h.caching, h.websocket, h.certificateId, h.certificate], [443, true, true, false, true, true, false, 7, null]); + assert.equal(hostFrom({ id: 5, domain_names: ["b.com"], certificate_id: 0 })!.certificateId, null); + }); + + test("the user for managing is an optional pair of fields of the integration, the password a secret", () => { + const fields = INTEGRATION_FIELDS.npm!; + assert.deepEqual([fields.find((f) => f.key === "manageEmail")?.optional, fields.find((f) => f.key === "managePassword")?.secret, fields.find((f) => f.key === "managePassword")?.optional], [true, true, true]); + }); +}); + +/** An NPM that keeps its hosts, tells the user that may only view from the one that may manage, and does what NPM does quietly with SSL settings. */ +interface FakeHost { + id: number; + domain_names: string[]; + forward_scheme: string; + forward_host: string; + forward_port: number; + enabled: boolean; + ssl_forced: boolean; + http2_support: boolean; + hsts_enabled: boolean; + hsts_subdomains: boolean; + block_exploits: boolean; + caching_enabled: boolean; + allow_websocket_upgrade: boolean; + certificate_id: number; + advanced_config: string; +} +const fresh = (): FakeHost[] => [ + { id: 1, domain_names: ["app.example.com"], forward_scheme: "http", forward_host: "10.0.0.5", forward_port: 8080, enabled: true, ssl_forced: true, http2_support: true, hsts_enabled: false, hsts_subdomains: false, block_exploits: true, caching_enabled: false, allow_websocket_upgrade: false, certificate_id: 1, advanced_config: "proxy_set_header X-Test 1;" }, + { id: 2, domain_names: ["old.example.com", "legacy.example.com"], forward_scheme: "http", forward_host: "10.0.0.6", forward_port: 80, enabled: false, ssl_forced: false, http2_support: false, hsts_enabled: false, hsts_subdomains: false, block_exploits: false, caching_enabled: false, allow_websocket_upgrade: false, certificate_id: 0, advanced_config: "" }, +]; +let hosts = fresh(); +let nextId = 10; +interface Seen { + method: string; + path: string; + as: string; + body: string; +} +const seen: Seen[] = []; + +let fake: Server; +let fakeUrl = ""; + +before(async () => { + fake = createHttpServer((req, res) => { + let body = ""; + req.on("data", (c) => (body += c)); + req.on("end", () => { + const u = new URL(req.url ?? "", "http://x"); + const bearer = String(req.headers.authorization ?? "").replace(/^Bearer /, ""); + const as = bearer === "view-token" ? "view" : bearer === "manage-token" ? "manage" : bearer === "" ? "nobody" : "unknown"; + seen.push({ method: req.method ?? "", path: u.pathname + u.search, as, body }); + const send = (status: number, json: unknown) => { + res.writeHead(status, { "content-type": "application/json" }); + res.end(JSON.stringify(json)); + }; + const fail = (status: number, message: string) => send(status, { error: { code: status, message } }); + const parsed = body ? (JSON.parse(body) as Record) : {}; + if (u.pathname === "/api/tokens") { + if (parsed.identity === "manage@x" && parsed.secret === "manage-pass") return send(200, { token: "manage-token", expires: "2030-01-01T00:00:00Z" }); + if (parsed.identity === "view@x" && parsed.secret === "view-pass") return send(200, { token: "view-token", expires: "2030-01-01T00:00:00Z" }); + if (parsed.identity === "tfa@x") return send(200, { requires_2fa: true, challenge_token: "c" }); + return fail(400, "Invalid email or password"); + } + if (as === "nobody" || as === "unknown") return fail(401, "Unauthorised"); + const out = (h: FakeHost) => ({ ...h, certificate: h.certificate_id > 0 ? { id: h.certificate_id, nice_name: "example cert", domain_names: ["example.com"], provider: "letsencrypt", expires_on: "2031-01-01 00:00:00" } : null, meta: { nginx_online: true } }); + if (u.pathname === "/api/") return send(200, { status: "OK", version: { major: 2, minor: 11, revision: 3 } }); + if (u.pathname === "/api/nginx/certificates") return send(200, []); + if (u.pathname === "/api/nginx/proxy-hosts" && req.method === "GET") return send(200, hosts.map(out)); + const writing = req.method !== "GET"; + if (writing && as !== "manage") return fail(403, "Permission Denied"); + const apply = (h: FakeHost, data: Record) => { + Object.assign(h, data); + // What NPM does without saying so. + if (!h.certificate_id) { + h.ssl_forced = false; + h.http2_support = false; + } + if (!h.ssl_forced) h.hsts_enabled = false; + if (!h.hsts_enabled) h.hsts_subdomains = false; + }; + const taken = (names: unknown, except?: number) => (Array.isArray(names) ? (names as string[]).find((n) => hosts.some((h) => h.id !== except && h.domain_names.includes(n))) : undefined); + if (u.pathname === "/api/nginx/proxy-hosts" && req.method === "POST") { + const t = taken(parsed.domain_names); + if (t) return fail(400, `${t} is already in use`); + const h: FakeHost = { id: nextId++, domain_names: [], forward_scheme: "http", forward_host: "", forward_port: 80, enabled: true, ssl_forced: false, http2_support: false, hsts_enabled: false, hsts_subdomains: false, block_exploits: false, caching_enabled: false, allow_websocket_upgrade: false, certificate_id: 0, advanced_config: "" }; + apply(h, parsed); + hosts.push(h); + return send(201, out(h)); + } + const one = /^\/api\/nginx\/proxy-hosts\/(\d+)(\/enable|\/disable)?$/.exec(u.pathname); + if (one) { + const h = hosts.find((x) => x.id === Number(one[1])); + if (!h) return fail(404, `Not Found - ${one[1]}`); + if (req.method === "GET") return send(200, out(h)); + if (req.method === "PUT") { + const t = taken(parsed.domain_names, h.id); + if (t) return fail(400, `${t} is already in use`); + apply(h, parsed); + return send(200, out(h)); + } + if (req.method === "POST" && one[2]) { + const on = one[2] === "/enable"; + if (h.enabled === on) return fail(400, `Host is already ${on ? "enabled" : "disabled"}`); + h.enabled = on; + return send(200, true); + } + if (req.method === "DELETE") { + hosts = hosts.filter((x) => x.id !== h.id); + return send(200, true); + } + } + return fail(404, "Not Found"); + }); + }); + await new Promise((resolve) => fake.listen(0, "127.0.0.1", resolve)); + fakeUrl = `http://127.0.0.1:${(fake.address() as AddressInfo).port}`; +}); +after(() => { + fake.close(); +}); + +const reset = () => { + hosts = fresh(); + nextId = 10; + seen.length = 0; + clearNpmCacheForTests(); +}; +const writes = () => seen.filter((s) => s.method !== "GET" && s.path !== "/api/tokens"); + +describe("what is sent to NPM", () => { + const adapter = (over: Record = {}) => createNpmManageAdapter({ url: `${fakeUrl}/`, manageEmail: "manage@x", managePassword: "manage-pass", ...over } as never); + + test("every call signs in first, as the user for managing, and nothing else", async () => { + reset(); + await adapter().getHost(1); + assert.deepEqual(seen.map((s) => [s.method, s.path, s.as]), [["POST", "/api/tokens", "nobody"], ["GET", "/api/nginx/proxy-hosts/1?expand=certificate", "manage"]]); + assert.deepEqual(JSON.parse(seen[0].body), { identity: "manage@x", secret: "manage-pass" }); + }); + + test("a host is made, changed (only what is in the body), switched and deleted with the calls NPM's own page makes", async () => { + reset(); + const made = await adapter().createHost(settings({ domains: ["new.example.com"], certificateId: 1, sslForced: true })); + assert.deepEqual([made.id, made.domains, made.sslForced, made.certificateId], [10, ["new.example.com"], true, 1]); + assert.deepEqual(writes().map((s) => [s.method, s.path]), [["POST", "/api/nginx/proxy-hosts"]]); + const changed = await adapter().updateHost(10, { forward_port: 9000 }); + assert.equal(changed.forwardPort, 9000); + assert.equal(seen.at(-1)!.method + " " + seen.at(-1)!.path, "PUT /api/nginx/proxy-hosts/10"); + assert.equal(seen.at(-1)!.body, JSON.stringify({ forward_port: 9000 })); + await adapter().setEnabled(10, false); + assert.equal(seen.at(-1)!.path, "/api/nginx/proxy-hosts/10/disable"); + await adapter().setEnabled(10, true); + assert.equal(seen.at(-1)!.path, "/api/nginx/proxy-hosts/10/enable"); + await adapter().deleteHost(10); + assert.equal(seen.at(-1)!.method + " " + seen.at(-1)!.path, "DELETE /api/nginx/proxy-hosts/10"); + assert.equal(hosts.some((h) => h.id === 10), false); + }); + + test("what NPM says when it refuses is the error, said in kind; a user that may only view cannot write; two-factor and a wrong password are said", async () => { + reset(); + await assert.rejects( + () => adapter().createHost(settings({ domains: ["app.example.com"] })), + (err: Error & { kind?: string }) => err.kind === "invalid" && /app\.example\.com is already in use/.test(err.message), + ); + await assert.rejects( + () => adapter().getHost(99), + (err: Error & { kind?: string }) => err.kind === "missing" && /Not Found - 99/.test(err.message), + ); + await assert.rejects( + () => adapter({ manageEmail: "view@x", managePassword: "view-pass" }).updateHost(1, { forward_port: 81 }), + (err: Error & { kind?: string }) => err.kind === "denied" && /Manage on Proxy Hosts/.test(err.message), + ); + await assert.rejects(() => adapter({ manageEmail: "tfa@x" }).getHost(1), /two-factor/); + await assert.rejects( + () => adapter({ managePassword: "nope" }).getHost(1), + (err: Error & { kind?: string }) => err.kind === "denied" && /did not accept the email and password/.test(err.message), + ); + await assert.rejects(() => createNpmManageAdapter({ url: "http://127.0.0.1:1", manageEmail: "a", managePassword: "b" }).getHost(1), /could not be reached/); + }); + + test("an id that is not a whole number is never put in an address", async () => { + reset(); + for (const bad of [0, -1, 1.5, Number.NaN]) { + await assert.rejects(() => adapter().getHost(bad), /not a proxy host id/); + await assert.rejects(() => adapter().deleteHost(bad), /not a proxy host id/); + } + assert.deepEqual(seen, []); + }); +}); + +describe("the routes", () => { + let app: Server; + let base = ""; + let managed = 0; + let readOnly = 0; + let off = 0; + let other = 0; + + const as = (sub: string) => ({ "content-type": "application/json", "x-sub": sub }); + const create = (id: number, body: unknown, sub = "admin") => fetch(`${base}/${id}/hosts`, { method: "POST", headers: as(sub), body: JSON.stringify(body) }); + const edit = (id: number, hostId: number | string, body: unknown, sub = "admin") => fetch(`${base}/${id}/hosts/${hostId}`, { method: "PATCH", headers: as(sub), body: JSON.stringify(body) }); + const enable = (id: number, hostId: number, enabled: unknown, sub = "admin") => fetch(`${base}/${id}/hosts/${hostId}/enabled`, { method: "POST", headers: as(sub), body: JSON.stringify({ enabled }) }); + const remove = (id: number, hostId: number, domain: unknown, sub = "admin") => fetch(`${base}/${id}/hosts/${hostId}`, { method: "DELETE", headers: as(sub), body: JSON.stringify({ domain }) }); + const audit = async (action: string) => (await db.select().from(auditLog)).filter((e) => e.action === action); + const newHost = { domains: ["Fresh.Example.com ", "fresh.example.com"], scheme: "http", host: "10.0.0.9", port: 3000, certificateId: null, sslForced: false, http2: false, hsts: false, hstsSubdomains: false, blockExploits: true, caching: false, websocket: true }; + + before(async () => { + await db.insert(users).values([ + { oidcSub: "admin", name: "Alma", role: "admin" }, + { oidcSub: "operator", name: "Olle", role: "operator" }, + { oidcSub: "viewer", name: "Vic", role: "viewer" }, + ]); + const both = (await db.insert(integrationCredentials).values({ name: "npm:Front", encryptedSecret: encryptSecret(JSON.stringify({ password: "view-pass", managePassword: "manage-pass" })) }).returning({ id: integrationCredentials.id }))[0]; + const viewOnly = (await db.insert(integrationCredentials).values({ name: "npm:Watched", encryptedSecret: encryptSecret(JSON.stringify({ password: "view-pass" })) }).returning({ id: integrationCredentials.id }))[0]; + managed = (await db.insert(integrations).values({ type: "npm", name: "Front", baseUrl: fakeUrl, config: JSON.stringify({ url: fakeUrl, email: "view@x", manageEmail: "manage@x" }), credentialId: both.id }).returning({ id: integrations.id }))[0].id; + readOnly = (await db.insert(integrations).values({ type: "npm", name: "Watched", baseUrl: fakeUrl, config: JSON.stringify({ url: fakeUrl, email: "view@x" }), credentialId: viewOnly.id }).returning({ id: integrations.id }))[0].id; + off = (await db.insert(integrations).values({ type: "npm", name: "Off", baseUrl: fakeUrl, config: JSON.stringify({ url: fakeUrl, email: "view@x", manageEmail: "manage@x" }), credentialId: both.id, enabled: false }).returning({ id: integrations.id }))[0].id; + other = (await db.insert(integrations).values({ type: "jellyfin", name: "Media", baseUrl: fakeUrl, config: "{}", credentialId: both.id }).returning({ id: integrations.id }))[0].id; + const a = express(); + a.use(express.json()); + a.use((req, _res, next) => { + (req as unknown as { session: unknown }).session = { user: { sub: String(req.headers["x-sub"] ?? "viewer") } }; + next(); + }); + a.use("/api/npm", npmRouter); + app = await new Promise((resolve) => { + const s = a.listen(0, "127.0.0.1", () => resolve(s)); + }); + base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api/npm`; + }); + after(() => { + app.close(); + try { + rmSync(dir, { recursive: true, force: true }); + } catch { + // Windows keeps the database file locked until the process exits. + } + }); + + test("the page says which NPM has a user to manage with — a yes or no, never who or the password — and reading never uses that user", async () => { + reset(); + const res = await fetch(base, { headers: as("viewer") }); + const text = await res.text(); + assert.equal(/manage@x|manage-pass|view-pass/.test(text), false); + const body = JSON.parse(text) as { integrations: { id: number; canManage: boolean; hosts: unknown[] }[] }; + const can = Object.fromEntries(body.integrations.map((i) => [i.id, i.canManage])); + assert.deepEqual([can[managed], can[readOnly]], [true, false]); + assert.equal(seen.some((s) => s.as === "manage"), false, "the reading was done as the user that views"); + }); + + test("only an administrator makes, changes, switches or deletes a host; nothing reaches NPM for anyone else", async () => { + reset(); + for (const sub of ["viewer", "operator"]) { + assert.equal((await create(managed, newHost, sub)).status, 403, sub); + assert.equal((await edit(managed, 1, { port: 81 }, sub)).status, 403, sub); + assert.equal((await enable(managed, 1, false, sub)).status, 403, sub); + assert.equal((await remove(managed, 1, "app.example.com", sub)).status, 403, sub); + } + assert.deepEqual(seen, []); + }); + + test("a host is made with its names written for NPM and listed once, and the page then shows it; the audit log says who made what", async () => { + reset(); + const res = await create(managed, newHost); + assert.equal(res.status, 201); + const { host } = (await res.json()) as { host: { id: number; domains: string[] } }; + assert.deepEqual(host.domains, ["fresh.example.com"]); + assert.deepEqual(writes().map((s) => [s.method, s.path, s.as]), [["POST", "/api/nginx/proxy-hosts", "manage"]]); + assert.deepEqual(JSON.parse(writes()[0].body), { + domain_names: ["fresh.example.com"], + forward_scheme: "http", + forward_host: "10.0.0.9", + forward_port: 3000, + certificate_id: 0, + ssl_forced: false, + http2_support: false, + hsts_enabled: false, + hsts_subdomains: false, + block_exploits: true, + caching_enabled: false, + allow_websocket_upgrade: true, + }); + const page = (await (await fetch(base, { headers: as("viewer") })).json()) as { integrations: { id: number; hosts: { domains: string[] }[] }[] }; + assert.equal(page.integrations.find((i) => i.id === managed)!.hosts.some((h) => h.domains[0] === "fresh.example.com"), true, "the cache was refreshed"); + const [entry] = await audit("create_proxy_host"); + assert.deepEqual([entry.category, entry.targetType, entry.targetId], ["integration", "proxy_host", String(host.id)]); + assert.deepEqual(JSON.parse(entry.detail ?? "{}"), { integrationId: managed, integration: "Front", domains: ["fresh.example.com"], forwardsTo: "http://10.0.0.9:3000" }); + }); + + test("what is wrong with a host is said before NPM is asked", async () => { + reset(); + const bad: unknown[] = [ + {}, + { ...newHost, domains: [] }, + { ...newHost, domains: ["a b.example.com"] }, + { ...newHost, domains: ["a/b.example.com"] }, + { ...newHost, host: "" }, + { ...newHost, host: "a b" }, + { ...newHost, port: 0 }, + { ...newHost, port: 70000 }, + { ...newHost, scheme: "ftp" }, + { ...newHost, sslForced: true }, + { ...newHost, certificateId: 1, hsts: true }, + { ...newHost, certificateId: 1, sslForced: true, hstsSubdomains: true }, + { ...newHost, certificateId: 0 }, + ]; + for (const body of bad) { + const res = await create(managed, body); + assert.equal(res.status, 400, JSON.stringify(body)); + assert.equal(typeof ((await res.json()) as { message: string }).message, "string"); + } + assert.deepEqual(seen, []); + }); + + test("a name another host has is NPM's own words, and nothing is written in the audit log", async () => { + reset(); + const before = (await audit("create_proxy_host")).length; + const res = await create(managed, { ...newHost, domains: ["app.example.com"] }); + assert.equal(res.status, 400); + assert.match(((await res.json()) as { message: string }).message, /app\.example\.com is already in use/); + assert.equal((await audit("create_proxy_host")).length, before); + }); + + test("an edit sends only what differs, and what NPM keeps of the host that was not asked (its custom configuration) is not in it", async () => { + reset(); + const res = await edit(managed, 1, { port: 9090, websocket: true, domains: ["App.Example.com"], sslForced: true }); + assert.equal(res.status, 200); + const body = (await res.json()) as { changed: string[]; host: { forwardPort: number; websocket: boolean } }; + assert.deepEqual([body.changed, body.host.forwardPort, body.host.websocket], [["port", "websocket"], 9090, true]); + assert.deepEqual(writes().map((s) => [s.method, s.path, JSON.parse(s.body)]), [["PUT", "/api/nginx/proxy-hosts/1", { forward_port: 9090, allow_websocket_upgrade: true }]]); + assert.equal(hosts.find((h) => h.id === 1)!.advanced_config, "proxy_set_header X-Test 1;"); + const [entry] = await audit("update_proxy_host"); + assert.deepEqual(JSON.parse(entry.detail ?? "{}"), { integrationId: managed, integration: "Front", domains: ["app.example.com"], changed: ["port", "websocket"] }); + }); + + test("an edit that changes nothing sends nothing and writes nothing", async () => { + reset(); + const before = (await audit("update_proxy_host")).length; + const res = await edit(managed, 1, { port: 8080, scheme: "http", blockExploits: true }); + assert.deepEqual(((await res.json()) as { changed: string[] }).changed, []); + assert.deepEqual(writes(), []); + assert.equal((await audit("update_proxy_host")).length, before); + }); + + test("an edit that NPM would quietly undo is refused with the reason; so is an unknown field, an empty edit, a host that is not there and an id that is no id", async () => { + reset(); + assert.match(((await (await edit(managed, 2, { sslForced: true })).json()) as { message: string }).message, /need a certificate/); + assert.match(((await (await edit(managed, 1, { certificateId: null })).json()) as { message: string }).message, /need a certificate/); + assert.equal((await edit(managed, 1, { advancedConfig: "x" })).status, 400); + assert.equal((await edit(managed, 1, { port: "x" })).status, 400); + assert.equal((await edit(managed, 99, { port: 81 })).status, 404); + assert.equal((await edit(managed, "abc", { port: 81 })).status, 400); + assert.deepEqual(writes(), []); + // Taking the certificate away with what needs it is fine, and the host ends as asked. + const ok = await edit(managed, 1, { certificateId: null, sslForced: false, http2: false }); + assert.equal(ok.status, 200); + assert.deepEqual([hosts.find((h) => h.id === 1)!.certificate_id, hosts.find((h) => h.id === 1)!.ssl_forced], [0, false]); + }); + + test("a host is switched off and on; what is already so asks nothing", async () => { + reset(); + assert.deepEqual(await (await enable(managed, 1, false)).json(), { enabled: false, changed: true }); + assert.equal(hosts.find((h) => h.id === 1)!.enabled, false); + assert.deepEqual(writes().map((s) => s.path), ["/api/nginx/proxy-hosts/1/disable"]); + assert.deepEqual(await (await enable(managed, 1, false)).json(), { enabled: false, changed: false }); + assert.equal(writes().length, 1); + assert.deepEqual(await (await enable(managed, 2, true)).json(), { enabled: true, changed: true }); + assert.equal((await enable(managed, 1, "yes")).status, 400); + assert.equal((await audit("disable_proxy_host")).length, 1); + assert.equal((await audit("enable_proxy_host")).length, 1); + }); + + test("a host is deleted with its first name typed, checked against the host as NPM has it now; a wrong name deletes nothing", async () => { + reset(); + assert.equal((await remove(managed, 2, undefined)).status, 400); + const wrong = await remove(managed, 2, "app.example.com"); + assert.equal(wrong.status, 400); + assert.equal(((await wrong.json()) as { error: string }).error, "name_mismatch"); + assert.equal((await remove(managed, 2, "legacy.example.com")).status, 400, "the first name, not any"); + assert.equal(hosts.length, 2); + assert.deepEqual(writes(), []); + assert.equal((await remove(managed, 2, " Old.Example.com ")).status, 204); + assert.deepEqual(hosts.map((h) => h.id), [1]); + const [entry] = await audit("delete_proxy_host"); + assert.deepEqual(JSON.parse(entry.detail ?? "{}"), { integrationId: managed, integration: "Front", domains: ["old.example.com", "legacy.example.com"], forwardsTo: "http://10.0.0.6:80" }); + assert.equal((await remove(managed, 99, "x")).status, 404); + }); + + test("an NPM with no user to manage with, a switched-off one, another kind of integration and an unknown one are not written to", async () => { + reset(); + const none = await create(readOnly, newHost); + assert.equal(none.status, 400); + assert.equal(((await none.json()) as { error: string }).error, "no_manage_login"); + assert.equal(((await (await create(off, newHost)).json()) as { error: string }).error, "integration_disabled"); + assert.equal(((await (await create(other, newHost)).json()) as { error: string }).error, "wrong_type"); + assert.equal((await create(999999, newHost)).status, 404); + assert.equal((await fetch(`${base}/abc/hosts`, { method: "POST", headers: as("admin"), body: JSON.stringify(newHost) })).status, 400); + assert.deepEqual(seen, []); + }); + + test("the user for managing can be taken away; the one that reads stays, and the audit log says it", async () => { + reset(); + assert.equal((await fetch(`${base}/${managed}/manage`, { method: "DELETE", headers: as("operator") })).status, 403); + assert.equal((await fetch(`${base}/${managed}/manage`, { method: "DELETE", headers: as("admin") })).status, 204); + const loaded = await loadIntegrationConfig(managed); + assert.deepEqual([loaded?.config.manageEmail, loaded?.config.managePassword, loaded?.config.email, loaded?.config.password], [undefined, undefined, "view@x", "view-pass"]); + assert.equal((await create(managed, newHost)).status, 400); + assert.equal((await audit("remove_npm_manage_login")).length, 1); + assert.equal((await fetch(`${base}/${managed}/manage`, { method: "DELETE", headers: as("admin") })).status, 204); + assert.equal((await audit("remove_npm_manage_login")).length, 1, "nothing more to take away, nothing more written"); + assert.equal((await fetch(`${base}/${other}/manage`, { method: "DELETE", headers: as("admin") })).status, 400); + assert.equal((await fetch(`${base}/999999/manage`, { method: "DELETE", headers: as("admin") })).status, 404); + }); +}); diff --git a/web/src/api/client.ts b/web/src/api/client.ts index b698d74..5003123 100644 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -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(`/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) => 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(`/api/npm/${integrationId}/hosts/${hostId}`, { method: "DELETE", body: JSON.stringify({ domain }) }), }, homeAssistant: { overview: () => request("/api/home-assistant"), diff --git a/web/src/components/ProxyHostForm.tsx b/web/src/components/ProxyHostForm.tsx new file mode 100644 index 0000000..6636217 --- /dev/null +++ b/web/src/components/ProxyHostForm.tsx @@ -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(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(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) => ( + + ); + + return ( +
+
+

{host ? `Change ${host.domains[0]}` : "New proxy host"}

+
{integrationName}
+
+
+ +
+ +