Manage Nginx Proxy Manager proxy hosts from the Proxy hosts page

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

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

No files matched your search

+2
View File
@@ -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: "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: "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" },
],
homeassistant: [
+1 -1
View File
@@ -15,7 +15,7 @@ export interface JsonResponse {
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) => {
let parsed: URL;
try {
+19 -1
View File
@@ -5,6 +5,7 @@
* NPM has no API keys: its API is the one its own web page uses, and signs in with the administrator's email and password (`POST /api/tokens` answers with a bearer
* token, which the rest take). So this logs in for each read — and only ever reads: the proxy hosts (what is proxied to what, with its certificate) and the
* certificates. Use a dedicated user with the "view only" permission on proxy hosts and certificates (Users → Permissions) rather than the administrator's own.
* Managing the hosts is ./manage.ts, with a user of its own.
*
* Endpoints and field names are from NPM's own API as the web page uses it (`/api/nginx/proxy-hosts?expand=certificate`, `/api/nginx/certificates`), and have
* not been checked against a live NPM here; every field is read defensively, so one a version renames is left blank rather than breaking the read.
@@ -36,6 +37,15 @@ export interface NpmProxyHost {
forwardPort: number | null;
enabled: boolean;
sslForced: boolean;
/** What else is switched on for the host. */
http2: boolean;
hsts: boolean;
hstsSubdomains: boolean;
blockExploits: boolean;
caching: boolean;
websocket: boolean;
/** The certificate it uses, by id (even when NPM did not say which it is); null for none. */
certificateId: number | null;
certificate: { id: number; name: string; expiresAt: string | null } | null;
/** NPM says its nginx did not accept this host's configuration. */
online: boolean;
@@ -59,6 +69,7 @@ const num = (v: unknown): number | null => {
const n = typeof v === "number" ? v : typeof v === "string" && v.trim() !== "" ? Number(v) : NaN;
return Number.isFinite(n) ? n : null;
};
const on = (v: unknown): boolean => v === true || v === 1;
const domainsOf = (v: unknown): string[] => (Array.isArray(v) ? v.filter((d): d is string => typeof d === "string" && d !== "") : []);
/** NPM writes times as "2026-12-31 23:59:59" (UTC) or as ISO; either becomes ISO. */
@@ -90,7 +101,14 @@ export function hostFrom(raw: unknown): NpmProxyHost | null {
forwardHost: str(h.forward_host) ?? "",
forwardPort: num(h.forward_port),
enabled: h.enabled !== false && h.enabled !== 0,
sslForced: h.ssl_forced === true || h.ssl_forced === 1,
sslForced: on(h.ssl_forced),
http2: on(h.http2_support),
hsts: on(h.hsts_enabled),
hstsSubdomains: on(h.hsts_subdomains),
blockExploits: on(h.block_exploits),
caching: on(h.caching_enabled),
websocket: on(h.allow_websocket_upgrade),
certificateId: (num(h.certificate_id) ?? 0) > 0 ? num(h.certificate_id) : cert ? cert.id : null,
certificate: cert ? { id: cert.id, name: cert.name, expiresAt: cert.expiresAt } : null,
// NPM says "online" unless its own check of the generated configuration failed.
online: meta.nginx_online !== false && !err,
+105
View File
@@ -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 };
}
+107
View File
@@ -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
View File
@@ -1,7 +1,15 @@
import { Router } from "express";
import { Router, type Response } from "express";
import { eq } from "drizzle-orm";
import { z } from "zod";
import { db } from "../db/client.js";
import { servers } from "../db/schema.js";
import { requireAuth } from "../auth/middleware.js";
import { integrationCredentials, integrations, servers } from "../db/schema.js";
import { requireAuth, requireRole } from "../auth/middleware.js";
import { decryptSecret, encryptSecret } from "../crypto.js";
import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
import { checkHost, normaliseDomain, planHostEdit, settingsOf, type HostSettings } from "../integrations/npm/hostPlan.js";
import { createNpmManageAdapter, NpmManageError, type NpmManageAdapter } from "../integrations/npm/manage.js";
import { invalidateAlertsCache } from "../services/alerts.js";
import { recordAudit } from "../services/audit.js";
import { npmIntegrationIds, npmProblems, readNpm } from "../services/npmReader.js";
import { matchServerForTarget } from "../services/uptimeKumaMatch.js";
import { asyncHandler } from "../utils/asyncHandler.js";
@@ -29,9 +37,12 @@ npmRouter.get("/", asyncHandler(async (req, res) => {
const out = [];
for (const i of await npmIntegrationIds()) {
const read = await readNpm(i.id, force);
// Whether it has a user to manage with — only that, never what it is.
const canManage = await loadIntegrationConfig(i.id).then((l) => !!l && hasManageLogin(l.config)).catch(() => false);
out.push({
id: i.id,
name: i.name,
canManage,
readAt: read.at,
error: read.error,
version: read.snapshot?.version ?? null,
@@ -45,3 +56,200 @@ npmRouter.get("/", asyncHandler(async (req, res) => {
}
res.json({ integrations: out });
}));
// ─── Managing proxy hosts ─────────────────────────────────────────────────────
//
// Only for an administrator, and only for an NPM that was given a user to manage with (manageEmail, managePassword): the user that reads is view-only and is never used to write.
const hasManageLogin = (config: Record<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();
}));