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:
1 parent
672c7f2f66
commit
4dd7901f1c
13 files changed
+1286
-14
No files matched your search
+8
-3
@@ -315,9 +315,9 @@ osTicket's API cannot close a ticket, so this is the one place in the app that *
|
|||||||
|
|
||||||
### Nginx Proxy Manager
|
### 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
|
- **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 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.
|
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.
|
- 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.
|
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.
|
- 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.
|
- 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.
|
field is read defensively. If a read fails or comes back empty, the **Diagnostic Log** has what NPM answered.
|
||||||
|
|
||||||
### Home Assistant
|
### Home Assistant
|
||||||
|
|||||||
@@ -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
|
**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
|
(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
|
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
|
**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.
|
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.
|
||||||
|
|||||||
@@ -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.
|
- **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.
|
- **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.
|
- **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
|
- **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.
|
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.
|
- **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.
|
||||||
|
|||||||
@@ -92,6 +92,8 @@ export const INTEGRATION_FIELDS: Partial<Record<IntegrationType, IntegrationFiel
|
|||||||
{ key: "url", label: "Nginx Proxy Manager URL", secret: false, placeholder: "https://npm.example.lan:81 (its admin page)" },
|
{ key: "url", label: "Nginx Proxy Manager URL", secret: false, placeholder: "https://npm.example.lan:81 (its admin page)" },
|
||||||
{ key: "email", label: "Email of a user that may view", secret: false, placeholder: "a dedicated user with view-only access to proxy hosts and certificates" },
|
{ key: "email", label: "Email of a user that may view", secret: false, placeholder: "a dedicated user with view-only access to proxy hosts and certificates" },
|
||||||
{ key: "password", label: "Password", secret: true, type: "password" },
|
{ key: "password", label: "Password", secret: true, type: "password" },
|
||||||
|
{ key: "manageEmail", label: "Email of a user that may manage (optional)", secret: false, optional: true, placeholder: "only to make, change and delete proxy hosts from here; a user with Manage on Proxy Hosts, without two-factor sign-in" },
|
||||||
|
{ key: "managePassword", label: "Password of that user (optional)", secret: true, optional: true, type: "password" },
|
||||||
{ key: "insecure", label: "Allow self-signed certificate", secret: false, type: "checkbox" },
|
{ key: "insecure", label: "Allow self-signed certificate", secret: false, type: "checkbox" },
|
||||||
],
|
],
|
||||||
homeassistant: [
|
homeassistant: [
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ export interface JsonResponse {
|
|||||||
|
|
||||||
const TIMEOUT_MS = 15_000;
|
const TIMEOUT_MS = 15_000;
|
||||||
|
|
||||||
export function requestJson(url: string, opts: { method?: "GET" | "POST" | "PATCH" | "DELETE"; headers?: Record<string, string>; body?: unknown; insecure?: boolean; timeoutMs?: number } = {}): Promise<JsonResponse> {
|
export function requestJson(url: string, opts: { method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE"; headers?: Record<string, string>; body?: unknown; insecure?: boolean; timeoutMs?: number } = {}): Promise<JsonResponse> {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
let parsed: URL;
|
let parsed: URL;
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -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
|
* 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
|
* 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.
|
* 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
|
* 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.
|
* 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;
|
forwardPort: number | null;
|
||||||
enabled: boolean;
|
enabled: boolean;
|
||||||
sslForced: 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;
|
certificate: { id: number; name: string; expiresAt: string | null } | null;
|
||||||
/** NPM says its nginx did not accept this host's configuration. */
|
/** NPM says its nginx did not accept this host's configuration. */
|
||||||
online: boolean;
|
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;
|
const n = typeof v === "number" ? v : typeof v === "string" && v.trim() !== "" ? Number(v) : NaN;
|
||||||
return Number.isFinite(n) ? n : null;
|
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 !== "") : []);
|
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. */
|
/** 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) ?? "",
|
forwardHost: str(h.forward_host) ?? "",
|
||||||
forwardPort: num(h.forward_port),
|
forwardPort: num(h.forward_port),
|
||||||
enabled: h.enabled !== false && h.enabled !== 0,
|
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,
|
certificate: cert ? { id: cert.id, name: cert.name, expiresAt: cert.expiresAt } : null,
|
||||||
// NPM says "online" unless its own check of the generated configuration failed.
|
// NPM says "online" unless its own check of the generated configuration failed.
|
||||||
online: meta.nginx_online !== false && !err,
|
online: meta.nginx_online !== false && !err,
|
||||||
|
|||||||
@@ -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<string, unknown> {
|
||||||
|
return Object.fromEntries(FIELDS.map((f) => [f.api, valueForApi(f.key, s[f.key])]));
|
||||||
|
}
|
||||||
|
|
||||||
|
export type HostPlan = { send: Record<string, unknown>; 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<HostSettings>): 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 };
|
||||||
|
}
|
||||||
@@ -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<NpmProxyHost>;
|
||||||
|
createHost(settings: HostSettings): Promise<NpmProxyHost>;
|
||||||
|
/** Changes only what is in `body` (NPM's own names for the settings). */
|
||||||
|
updateHost(id: number, body: Record<string, unknown>): Promise<NpmProxyHost>;
|
||||||
|
setEnabled(id: number, enabled: boolean): Promise<void>;
|
||||||
|
deleteHost(id: number): Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const obj = (v: unknown): Record<string, unknown> => (v !== null && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {});
|
||||||
|
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<string> {
|
||||||
|
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<unknown> {
|
||||||
|
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<NpmProxyHost> {
|
||||||
|
return host(await call("GET", `/api/nginx/proxy-hosts/${wholeNumber(id)}?expand=certificate`));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createHost(settings: HostSettings): Promise<NpmProxyHost> {
|
||||||
|
return host(await call("POST", "/api/nginx/proxy-hosts", createBody(settings)));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function updateHost(id: number, body: Record<string, unknown>): Promise<NpmProxyHost> {
|
||||||
|
return host(await call("PUT", `/api/nginx/proxy-hosts/${wholeNumber(id)}`, body));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function setEnabled(id: number, enabled: boolean): Promise<void> {
|
||||||
|
await call("POST", `/api/nginx/proxy-hosts/${wholeNumber(id)}/${enabled ? "enable" : "disable"}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteHost(id: number): Promise<void> {
|
||||||
|
await call("DELETE", `/api/nginx/proxy-hosts/${wholeNumber(id)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return withDiagLogging("npm", { getHost, createHost, updateHost, setEnabled, deleteHost });
|
||||||
|
}
|
||||||
+211
-3
@@ -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 { db } from "../db/client.js";
|
||||||
import { servers } from "../db/schema.js";
|
import { integrationCredentials, integrations, servers } from "../db/schema.js";
|
||||||
import { requireAuth } from "../auth/middleware.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 { npmIntegrationIds, npmProblems, readNpm } from "../services/npmReader.js";
|
||||||
import { matchServerForTarget } from "../services/uptimeKumaMatch.js";
|
import { matchServerForTarget } from "../services/uptimeKumaMatch.js";
|
||||||
import { asyncHandler } from "../utils/asyncHandler.js";
|
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||||
@@ -29,9 +37,12 @@ npmRouter.get("/", asyncHandler(async (req, res) => {
|
|||||||
const out = [];
|
const out = [];
|
||||||
for (const i of await npmIntegrationIds()) {
|
for (const i of await npmIntegrationIds()) {
|
||||||
const read = await readNpm(i.id, force);
|
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({
|
out.push({
|
||||||
id: i.id,
|
id: i.id,
|
||||||
name: i.name,
|
name: i.name,
|
||||||
|
canManage,
|
||||||
readAt: read.at,
|
readAt: read.at,
|
||||||
error: read.error,
|
error: read.error,
|
||||||
version: read.snapshot?.version ?? null,
|
version: read.snapshot?.version ?? null,
|
||||||
@@ -45,3 +56,200 @@ npmRouter.get("/", asyncHandler(async (req, res) => {
|
|||||||
}
|
}
|
||||||
res.json({ integrations: out });
|
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<string, unknown>) => 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<HostSettings>;
|
||||||
|
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<string, unknown>;
|
||||||
|
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<string, unknown>) : {};
|
||||||
|
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();
|
||||||
|
}));
|
||||||
@@ -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> = {}): 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<string, unknown>) : {};
|
||||||
|
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<string, unknown>) => {
|
||||||
|
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<void>((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<string, unknown> = {}) => 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<Server>((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);
|
||||||
|
});
|
||||||
|
});
|
||||||
+29
-1
@@ -2258,6 +2258,14 @@ export interface NpmHost {
|
|||||||
forwardPort: number | null;
|
forwardPort: number | null;
|
||||||
enabled: boolean;
|
enabled: boolean;
|
||||||
sslForced: 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;
|
certificate: { id: number; name: string; expiresAt: string | null } | null;
|
||||||
online: boolean;
|
online: boolean;
|
||||||
error: string | null;
|
error: string | null;
|
||||||
@@ -2280,8 +2288,24 @@ export interface IntegrationProblem {
|
|||||||
message: string;
|
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 {
|
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 {
|
export interface HaSyncStatus {
|
||||||
@@ -3690,6 +3714,10 @@ export const api = {
|
|||||||
},
|
},
|
||||||
npm: {
|
npm: {
|
||||||
overview: (refresh = false) => request<NpmOverview>(`/api/npm${refresh ? "?refresh=1" : ""}`),
|
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: {
|
homeAssistant: {
|
||||||
overview: () => request<HaOverview>("/api/home-assistant"),
|
overview: () => request<HaOverview>("/api/home-assistant"),
|
||||||
|
|||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import { Link } from "react-router-dom";
|
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 { api, type CurrentUser, type IntegrationProblem, type NpmHost, type NpmOverview } from "../api/client";
|
||||||
import SortableTh from "../components/SortableTh";
|
import SortableTh from "../components/SortableTh";
|
||||||
import Pagination from "../components/Pagination";
|
import Pagination from "../components/Pagination";
|
||||||
@@ -12,11 +13,12 @@ import { useSortable } from "../hooks/useSortable";
|
|||||||
import { useTableSearch } from "../hooks/useTableSearch";
|
import { useTableSearch } from "../hooks/useTableSearch";
|
||||||
import { usePagination } from "../hooks/usePagination";
|
import { usePagination } from "../hooks/usePagination";
|
||||||
import { downloadCsv } from "../utils/csv";
|
import { downloadCsv } from "../utils/csv";
|
||||||
|
import { confirmDialog, promptDialog } from "../utils/dialogs";
|
||||||
import { formatDate } from "../utils/date";
|
import { formatDate } from "../utils/date";
|
||||||
import { readableError } from "../utils/errors";
|
import { readableError } from "../utils/errors";
|
||||||
import { toast } from "../utils/toast";
|
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 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);
|
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) =>
|
(data?.integrations ?? []).flatMap((i) =>
|
||||||
i.hosts.map((h) => ({
|
i.hosts.map((h) => ({
|
||||||
...h,
|
...h,
|
||||||
|
integrationId: i.id,
|
||||||
|
canManage: i.canManage,
|
||||||
integrationName: i.name,
|
integrationName: i.name,
|
||||||
domain: h.domains.join(", "),
|
domain: h.domains.join(", "),
|
||||||
target: `${h.forwardScheme}://${h.forwardHost}${h.forwardPort !== null ? `:${h.forwardPort}` : ""}`,
|
target: `${h.forwardScheme}://${h.forwardHost}${h.forwardPort !== null ? `:${h.forwardPort}` : ""}`,
|
||||||
@@ -95,6 +99,51 @@ export default function ProxyHosts({ user }: { user: CurrentUser }) {
|
|||||||
),
|
),
|
||||||
[data],
|
[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 tableSearch = useTableSearch(rows);
|
||||||
const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered, "statusRank", "asc", { url: true });
|
const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered, "statusRank", "asc", { url: true });
|
||||||
const { pageItems, page, setPage, pageCount, totalCount } = usePagination(sorted);
|
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>
|
<h2 className="page-title mb-0">Proxy hosts</h2>
|
||||||
{(user.role === "admin" || user.role === "operator") && data && data.integrations.length > 0 && (
|
{(user.role === "admin" || user.role === "operator") && data && data.integrations.length > 0 && (
|
||||||
<div className="ms-auto btn-list">
|
<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}>
|
<button className="btn btn-outline-secondary" onClick={() => void readNow()} disabled={reading}>
|
||||||
{reading ? "Reading…" : "Read now"}
|
{reading ? "Reading…" : "Read now"}
|
||||||
</button>
|
</button>
|
||||||
@@ -124,9 +178,44 @@ export default function ProxyHosts({ user }: { user: CurrentUser }) {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-secondary mb-3">
|
<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’t set up, is an alert.
|
two weeks, or a host NPM can’t set up, is an alert.
|
||||||
</div>
|
</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} />
|
<ErrorNotice error={error} />
|
||||||
{data === null && !error && <BlockSkeleton lines={4} />}
|
{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="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="Forwards to" sortKeyName="target" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||||
<SortableTh<Row> label="Certificate" sortKeyName="certDays" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
<SortableTh<Row> label="Certificate" sortKeyName="certDays" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||||
|
{canManageAny && <th />}
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<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) => (
|
{(pageItems ?? []).map((h) => (
|
||||||
<tr key={`${h.integrationName}-${h.id}`}>
|
<tr key={`${h.integrationName}-${h.id}`}>
|
||||||
<td>
|
<td>
|
||||||
@@ -228,6 +318,23 @@ export default function ProxyHosts({ user }: { user: CurrentUser }) {
|
|||||||
<td className="stack-label" data-label="Certificate">
|
<td className="stack-label" data-label="Certificate">
|
||||||
<CertBadge h={h} />
|
<CertBadge h={h} />
|
||||||
</td>
|
</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>
|
</tr>
|
||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
|
|||||||
Reference in new issue
Block a user