nginx-proxy-manager/backend/app.js
Tom Winnerl d50d5c7287 feat(nginx): serialised configure that tests, rolls back and repairs other hosts
Every write of a host config now goes through one configure() that runs
under a re-entrant lock (lib/nginx-lock.js), so concurrent saves can't test
or rename each other's files:

- the new config is written and checked with nginx -t; when nginx rejects
  this host, the previous file (and .err file) is put back and an
  NginxConfigError with structured details is thrown (scope host/global,
  file, line, humanised message and hint, raw nginx output)
- when another host's file breaks the test, that host is only blamed when it
  fails on its own (lib/nginx-blame.js). It is regenerated from its database
  row first and only moved to .err and marked offline when that fails too.
  A conflict with the change being saved fails the save instead. An error
  that names no file (eg. an unknown variable) is only a conflict when it
  goes away with every other host's config moved aside; otherwise it is the
  host's own error and, when its advanced config uses the variable or path,
  reads "Advanced configuration: ..."
- errors are humanised (lib/nginx-errors.js) and mapped to the advanced
  config of the host where possible (new begin/end markers in the templates)
- the API returns error.details; a middleware redacts details that name a
  host the user can't see
- bulkGenerateConfigs (certificates) and the default site go through the
  same path, a host nginx rejects is taken offline instead of failing all
- nginx -s reload only signals the master, which reads the config later.
  reloadNginx() waits (bounded, 5 s) until the master runs a new generation
  of workers and the old ones are shutting down (lib/nginx-reload.js, from
  /proc) before the lock is released,
  otherwise the next holder's rejected candidate file could be what the
  master reads and the change saved before would never be applied. A reload
  that can't be confirmed is repeated once at the end of the locked section,
  after every rollback. When nginx logs an [emerg] for the reload (eg. a
  listen port in use, which nginx -t doesn't catch) the wait ends as soon
  as nginx gives up on it (for a bind() after its own retries), and after
  a repeated reload that isn't confirmed either, later saves don't repeat
  it until a reload is confirmed again, so they don't each wait 10 s
- reconcile() regenerates missing / moved-aside configs and retries hosts
  whose upstream didn't resolve yet; the startup commit runs it from
  backend/index.js (NPM_RECONCILE_ON_START)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 13:47:08 +01:00

110 lines
2.8 KiB
JavaScript

import bodyParser from "body-parser";
import compression from "compression";
import express from "express";
import fileUpload from "express-fileupload";
import internalNginx from "./internal/nginx.js";
import { isDebugMode } from "./lib/config.js";
import errs from "./lib/error.js";
import cors from "./lib/express/cors.js";
import jwt from "./lib/express/jwt.js";
import { debug, express as logger } from "./logger.js";
import mainRoutes from "./routes/main.js";
/**
* App
*/
const app = express();
app.use(fileUpload());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Gzip
app.use(compression());
/**
* General Logging, BEFORE routes
*/
app.disable("x-powered-by");
app.enable("trust proxy", ["loopback", "linklocal", "uniquelocal"]);
app.enable("strict routing");
// pretty print JSON when not live
if (isDebugMode()) {
app.set("json spaces", 2);
}
// CORS for everything
app.use(cors);
// General security/cache related headers + server header
app.use((_, res, next) => {
let x_frame_options = "DENY";
if (typeof process.env.X_FRAME_OPTIONS !== "undefined" && process.env.X_FRAME_OPTIONS) {
x_frame_options = process.env.X_FRAME_OPTIONS;
}
res.set({
"X-XSS-Protection": "1; mode=block",
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": x_frame_options,
"Cache-Control": "no-cache, no-store, max-age=0, must-revalidate",
Pragma: "no-cache",
Expires: 0,
});
next();
});
app.use(jwt());
app.use("/", mainRoutes);
// Nginx errors can name another host, only show those details to users who can see that host
app.use((err, _req, res, next) => {
if (!(err instanceof errs.NginxConfigError) || !res.locals.access) {
next(err);
return;
}
internalNginx.redactConfigError(res.locals.access, err).then(
() => next(err),
() => next(err),
);
});
// production error handler
// no stacktraces leaked to user
app.use((err, req, res, _) => {
const payload = {
error: {
code: err.status || 500,
message: err.public ? err.message : "Internal Error",
},
};
if (typeof err.message_i18n !== "undefined") {
payload.error.message_i18n = err.message_i18n;
}
if (err.public && err.details && typeof err.details === "object") {
payload.error.details = err.details;
}
if (isDebugMode() || (req.baseUrl + req.path).includes("nginx/certificates")) {
payload.debug = {
stack: typeof err.stack !== "undefined" && err.stack ? err.stack.split("\n") : null,
previous: err.previous,
};
}
// Not every error is worth logging - but this is good for now until it gets annoying.
if (typeof err.stack !== "undefined" && err.stack) {
debug(logger, err.stack);
if (typeof err.public === "undefined" || !err.public) {
logger.warn(err.message);
}
}
res.status(err.status || 500).send(payload);
});
export default app;