"use strict"; const assert = require("node:assert/strict"); const { createHmac, randomBytes } = require("node:crypto"); const fs = require("node:fs"); const http = require("node:http"); const https = require("node:https"); const net = require("node:net"); const os = require("node:os"); const path = require("node:path"); const { spawn, spawnSync, execFileSync } = require("node:child_process"); const { once } = require("node:events"); const { setTimeout: delay } = require("node:timers/promises"); const source = path.resolve(__dirname, ".."); const files = ["index.js", "db.js", "nodes.js", "package.json", "mysql-schema.sql", "initialize.sh"]; const directories = ["AgentWorker", "public", "views", "services", "utils", "routes", "scripts", "node_modules"]; const originPort = 13001; const httpPort = 18080; const tlsPort = 18443; const email = "operator@example.test"; const password = "Synthetic-local-password-123!"; const fleetSecret = "synthetic-node-signing-secret-for-loopback-fixture"; const nodeId = "fixture-node"; const nodeToken = "fixture-node-bearer-token"; function runIsolated() { const nginx = path.resolve(process.env.NGINX_BIN || "/usr/sbin/nginx"); fs.accessSync(nginx, fs.constants.X_OK); const binds = [...files, ...directories].flatMap(name => ["--ro-bind", path.join(source, name), `/source/${name}`]); const result = spawnSync("bwrap", [ "--unshare-all", "--die-with-parent", "--uid", "0", "--gid", "0", "--clearenv", "--setenv", "PATH", "/tools:/usr/bin:/usr/sbin:/bin:/sbin", "--setenv", "HOME", "/tmp", "--ro-bind", "/usr", "/usr", "--symlink", "usr/bin", "/bin", "--symlink", "usr/sbin", "/sbin", "--symlink", "usr/lib", "/lib", "--symlink", "usr/lib64", "/lib64", "--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp", "--tmpfs", "/run", "--tmpfs", "/etc", "--dir", "/etc/alternatives", "--symlink", "/usr/bin/gawk", "/etc/alternatives/awk", "--ro-bind", nginx, "/tools/nginx", "--dir", "/var/log/nginx", ...["body", "proxy", "fastcgi", "uwsgi", "scgi"].flatMap(name => ["--dir", `/var/lib/nginx/${name}`]), ...binds, "--chdir", "/tmp", "/usr/bin/node", "/source/scripts/verify-prelogin.js", "--isolated", ], { stdio: "inherit", timeout: 150_000 }); if (result.error) throw result.error; process.exitCode = result.status ?? 1; } async function until(label, check) { const deadline = Date.now() + 25_000; do { const result = await check(); if (result) return result; await delay(50); } while (Date.now() < deadline); throw new Error(`Timed out waiting for ${label}`); } function request(port, route, { method = "GET", headers = {}, body, ipv6 = false } = {}) { const tls = port === tlsPort; return new Promise((resolve, reject) => { const client = tls ? https : http; const req = client.request({ hostname: ipv6 ? "::1" : "127.0.0.1", localAddress: ipv6 ? "::1" : tls ? "127.0.0.4" : port === httpPort ? "127.0.0.3" : "127.0.0.2", port, path: route, method, headers, ...(tls ? { ca: fs.readFileSync("/tmp/cert.pem"), ...(ipv6 ? { servername: "panel.example.test" } : {}) } : {}), }, res => { let text = ""; res.setEncoding("utf8"); res.on("data", chunk => { text += chunk; }); res.on("aborted", () => reject(new Error("Fixture response aborted"))); res.on("error", reject); res.on("end", () => resolve({ status: res.statusCode, headers: res.headers, text })); }); req.on("error", reject); req.setTimeout(5000, () => req.destroy(new Error("Fixture request timed out"))); req.end(body); }); } async function checkLogin(port) { const tls = port === tlsPort; const url = `${tls ? "https" : "http"}://127.0.0.1:${port}`; const health = await request(port, "/healthz"); assert.equal(health.status, 200); assert.equal(JSON.parse(health.text).ok, true); assert.deepEqual(Object.keys(JSON.parse(health.text)).sort(), ["ok", "ts"]); assert.match(health.headers["cache-control"], /no-store/); assert.equal(health.headers["x-powered-by"], undefined); assert.equal(health.headers.server, port === originPort ? undefined : "nginx"); assert.equal(health.headers["set-cookie"], undefined); assert.deepEqual(Object.keys(JSON.parse((await request(port, "/healtz")).text)).sort(), ["ok", "ts"]); for (const method of ["GET", "HEAD"]) { const favicon = await request(port, "/favicon.ico", { method }); assert.equal(favicon.status, 204); assert.equal(favicon.text, ""); assert.equal(favicon.headers.location, undefined); assert.equal(favicon.headers["set-cookie"], undefined); assert.match(favicon.headers["cache-control"], /no-store.*private/); } const entry = await request(port, "/"); assert.equal(entry.status, 302); assert.equal(entry.headers.location, "/login"); assert.match(entry.headers["cache-control"], /no-store/); const closed = await request(port, "/register", { headers: { accept: "application/json" } }); assert.equal(closed.status, 404); assert.equal(closed.text, "Not Found"); assert.match(closed.headers["content-type"], /^text\/plain\b/); assert.match(closed.headers["cache-control"], /no-store/); const browser = { "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36", accept: "text/html", "sec-fetch-site": "same-origin", origin: url, referer: `${url}/login` }; const probe = await request(port, "/login"); assert.equal(probe.status, 200); assert.match(probe.text, /
Sign in<\/title>/); assert.match(signin.text, /name="robots" content="noindex, noarchive"/); assert.match(signin.text, / value.startsWith("adpanel.sid=")); assert.ok(session); assert.equal(signin.headers["set-cookie"].length, 1); assert.match(session, /HttpOnly/i); assert.equal(/; Secure(?:;|$)/i.test(session), tls); const botProof = signin.text.match(/name="botProof"[^>]*value="([a-f0-9]+)"/)?.[1]; const csrf = signin.text.match(/name="_csrf"[^>]*value="([a-f0-9]+)"/)?.[1]; assert.ok(botProof && csrf); const login = await request(port, "/login", { method: "POST", headers: { ...browser, cookie: session.split(";", 1)[0], "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ email, password, botProof, _csrf: csrf }).toString(), }); assert.equal(login.status, 303, `Native form login on port ${port} returned ${login.status}`); assert.equal(login.headers.location, "/"); const rotatedSession = login.headers["set-cookie"].find(value => value.startsWith("adpanel.sid=")); assert.ok(rotatedSession); const signedIn = await request(port, "/login", { headers: { ...browser, cookie: rotatedSession.split(";", 1)[0] } }); assert.equal(signedIn.status, 303); assert.equal(signedIn.headers.location, "/"); assert.equal((await request(port, "/forgot-password")).status, 200); const icon = signin.text.match(/id="favicon"[^>]*href="(\/[^"?]+)/)?.[1]; assert.ok(icon); assert.equal((await request(port, icon, { method: "HEAD" })).status, 200); assert.equal((await request(port, "/auth-assets/background", { method: "HEAD" })).status, 200); console.log(`PASS ${url}: neutral health and implicit icon, normal form sign-in and assets, no gate cookie`); } async function checkHeartbeat(port) { const { deriveNodeHmacSecret } = require("../utils/node-hmac"); const { heartbeatSignatureBase, heartbeatBodySha256 } = require("../utils/heartbeat-auth"); const route = `/api/nodes/${nodeId}/heartbeat`; const body = "{}"; const digest = heartbeatBodySha256(body); const timestamp = String(Date.now()); const nonce = randomBytes(16).toString("hex"); const signed = createHmac("sha256", deriveNodeHmacSecret(fleetSecret, nodeId)) .update(heartbeatSignatureBase(nodeId, timestamp, nonce, digest)).digest("hex"); const headers = { "content-type": "application/json", authorization: `Bearer ${nodeToken}` }; assert.equal((await request(port, route, { method: "POST", body, headers })).status, 401); const heartbeat = await request(port, route, { method: "POST", body, headers: { ...headers, "x-node-ts": timestamp, "x-node-nonce": nonce, "x-node-body-hash": digest, "x-node-sign": signed, } }); assert.equal(heartbeat.status, 200, heartbeat.text); assert.equal(JSON.parse(heartbeat.text).ok, true); } function checkCertbotWiring(installer, panel, tokenHelper) { const fixtureDomain = "panel.example.test"; const live = `/etc/letsencrypt/live/${fixtureDomain}`; const callsPath = "/tmp/fixture-certbot-args"; const from = installer.indexOf("\nnginx_loopback_reply_matches() {"); const to = installer.indexOf("\ninstall_nginx() {", from); assert.ok(from >= 0 && to > from); execFileSync("openssl", ["req", "-config", "/tmp/openssl.cnf", "-x509", "-new", "-key", "/tmp/key.pem", "-addext", `subjectAltName=DNS:${fixtureDomain}`, "-out", "/tmp/dedicated.pem", "-subj", `/CN=${fixtureDomain}`], { stdio: "pipe" }); const certificate = `ui_error() { printf '%s\\n' "$*" >&2; } fixture_cert_root() { if [ "$1" != certbot ]; then "$@"; return $?; fi shift printf '%s\\0' CERTBOT "$@" >> "$FIXTURE_CALLS" if [ "$1" = "$FIXTURE_FAIL_VERB" ]; then return 1; fi if [ "$1" = certonly ]; then mkdir -p "$FIXTURE_LIVE" cp /tmp/dedicated.pem "$FIXTURE_LIVE/fullchain.pem" cp /tmp/key.pem "$FIXTURE_LIVE/privkey.pem" fi } ${installer.slice(from, to)} ${tokenHelper} obtain_panel_certificate || exit "$?" printf '%s\\n' "$SSL_CERT_PATH" "$SSL_KEY_PATH"`; function obtain({ status = 0, failVerb = "", proxied = true, domain = fixtureDomain, webrootPanel = panel } = {}) { fs.writeFileSync(callsPath, ""); const result = spawnSync("/bin/bash", ["-s"], { input: certificate, encoding: "utf8", env: { ...process.env, SUDO: "fixture_cert_root", PANEL_ROOT: webrootPanel, PANEL_DOMAIN: domain, EMAIL: email, HTTP_PORT: String(httpPort), NGINX_ENABLED: String(proxied), FIXTURE_CALLS: callsPath, FIXTURE_LIVE: live, FIXTURE_FAIL_VERB: failVerb, } }); assert.equal(result.status, status, result.stderr); assert.equal(result.stdout, status === 0 ? `${live}/fullchain.pem\n${live}/privkey.pem\n` : ""); return fs.readFileSync(callsPath, "utf8").split("CERTBOT\0").slice(1).map(call => call.split("\0").slice(0, -1)); } const webroot = ["--webroot", "-w", `${panel}/public`, "--preferred-challenges", "http-01", "--installer", "none", "--no-directory-hooks", "--pre-hook", "", "--post-hook", "", "--deploy-hook", "nginx -t && nginx -s reload"]; assert.deepEqual(obtain({ status: 2, domain: "unmatched.example.test" }), []); assert.deepEqual(obtain({ status: 2, webrootPanel: "/tmp/wrong-webroot" }), []); assert.deepEqual(fs.readdirSync("/tmp/wrong-webroot/public/.well-known/acme-challenge"), []); assert.deepEqual(obtain(), [["certonly", "--cert-name", fixtureDomain, "-d", fixtureDomain, "--non-interactive", "--agree-tos", "-m", email, "--keep-until-expiring", ...webroot]]); assert.deepEqual(fs.readdirSync(`${panel}/public/.well-known/acme-challenge`), ["fixture"]); assert.deepEqual(obtain({ status: 2 }), []); fs.mkdirSync("/etc/letsencrypt/renewal", { recursive: true }); const renewal = `/etc/letsencrypt/renewal/${fixtureDomain}.conf`; fs.writeFileSync(renewal, "[renewalparams]\nauthenticator = standalone\n"); const reconfigure = ["reconfigure", "--cert-name", fixtureDomain, "--non-interactive", ...webroot]; const renew = ["renew", "--cert-name", fixtureDomain, "--non-interactive", "--no-directory-hooks"]; assert.deepEqual(obtain(), [reconfigure, renew]); fs.writeFileSync(renewal, "[renewalparams]\nauthenticator = dns-cloudflare\npref_challs = dns-01,\n"); assert.deepEqual(obtain(), [reconfigure, renew]); assert.deepEqual(obtain({ status: 2, failVerb: "reconfigure" }), [reconfigure]); assert.deepEqual(obtain({ status: 2, failVerb: "renew" }), [reconfigure, renew]); fs.copyFileSync("/tmp/cert.pem", `${live}/fullchain.pem`); assert.deepEqual(obtain({ status: 2 }), []); assert.deepEqual(obtain({ proxied: false }), [["certonly", "--standalone", "-d", fixtureDomain, "--non-interactive", "--agree-tos", "-m", email, "--keep-until-expiring"]]); console.log("PASS synthetic Certbot: active webroot required, fresh issuance, named lineage reconfiguration and failure handling"); } async function verify() { assert.equal(source, "/source"); assert.equal(process.getuid(), 0); assert.ok(Object.values(os.networkInterfaces()).flat().every(address => address.internal)); assert.ok(!fs.existsSync("/run/systemd/private")); const panel = "/tmp/panel"; fs.mkdirSync(panel); for (const name of files) fs.copyFileSync(`/source/${name}`, `${panel}/${name}`); for (const name of directories.filter(name => name !== "node_modules")) fs.cpSync(`/source/${name}`, `${panel}/${name}`, { recursive: true }); fs.symlinkSync("/source/node_modules", `${panel}/node_modules`); fs.writeFileSync(`${panel}/public/js/fixture.js`, "/* fixture */"); fs.writeFileSync(`${panel}/public/js/fixture.js.map`, "fixture debug data"); fs.mkdirSync(`${panel}/public/.well-known/acme-challenge`, { recursive: true }); fs.writeFileSync(`${panel}/public/.well-known/acme-challenge/fixture`, "fixture challenge"); fs.writeFileSync("/etc/passwd", "root:x:0:0:root:/tmp:/bin/bash\n"); fs.writeFileSync("/etc/group", "root:x:0:\n"); fs.writeFileSync("/etc/hosts", "127.0.0.1 localhost\n::1 localhost\n"); fs.writeFileSync("/etc/nsswitch.conf", "passwd: files\ngroup: files\nhosts: files\n"); fs.mkdirSync("/tmp/bin"); fs.writeFileSync("/tmp/bin/systemctl", `#!/bin/sh case "$1:$2" in list-unit-files:mariadb.service) printf '%s\\n' 'mariadb.service enabled' ;; is-active:mariadb) printf '%s\\n' active ;; *) exit 1 ;; esac `, { mode: 0o700 }); const nginxMain = "user root root; pid /run/nginx.pid; error_log stderr notice; events {} http { access_log off; types { image/svg+xml svg; application/javascript js; } include /etc/nginx/conf.d/*.conf; }\n"; fs.mkdirSync("/etc/nginx/conf.d", { recursive: true }); fs.writeFileSync("/etc/nginx/nginx.conf", nginxMain); fs.writeFileSync("/tmp/openssl.cnf", "[req]\ndistinguished_name=dn\n[dn]\n"); execFileSync("openssl", ["req", "-config", "/tmp/openssl.cnf", "-x509", "-newkey", "rsa:2048", "-nodes", "-addext", "subjectAltName=IP:127.0.0.1,DNS:panel.example.test", "-keyout", "/tmp/key.pem", "-out", "/tmp/cert.pem", "-subj", "/CN=127.0.0.1"], { stdio: "pipe" }); const installer = fs.readFileSync(`${panel}/initialize.sh`, "utf8"); const gateSettingStart = installer.indexOf("\n local stealth_mode_line="); const gateSettingEnd = installer.indexOf("\n SECRET=", gateSettingStart); assert.ok(gateSettingStart >= 0 && gateSettingEnd > gateSettingStart); const gateSetting = `read_gate_setting() { ${installer.slice(gateSettingStart, gateSettingEnd)} printf '%s' "$stealth_mode_line"; }; read_gate_setting`; assert.match(execFileSync("bash", ["-c", gateSetting], { cwd: panel, encoding: "utf8" }), /^# STEALTH_MODE is unset/); for (const value of ["true", "false"]) { fs.writeFileSync(`${panel}/.env`, `STEALTH_MODE = "${value}" # existing setting\n`); assert.equal(execFileSync("bash", ["-c", gateSetting], { cwd: panel, encoding: "utf8" }), `STEALTH_MODE=${value}`); } fs.unlinkSync(`${panel}/.env`); const urlHelperStart = installer.indexOf("\nformat_url_host() {"); const urlHelperEnd = installer.indexOf("\nrequire_sudo_if_needed() {", urlHelperStart); const reloadStart = installer.indexOf("\nservice_reload() {"); const reloadEnd = installer.indexOf("\nensure_panel_env_permissions() {", reloadStart); const layoutStart = installer.indexOf("\ndetect_nginx_layout() {"); const layoutEnd = installer.indexOf("\ndetect_nginx_user() {", layoutStart); const probeStart = installer.indexOf("\nnginx_loopback_reply_matches() {"); const probeEnd = installer.indexOf("\nnginx_acme_route_ready() (", probeStart); const tokenStart = installer.indexOf("\ngenerate_base64url_token() {"); const tokenEnd = installer.indexOf("\n# enforce_secret_file_acl", tokenStart); const generatorStart = installer.indexOf("\nbackup_path_for_restore() {"); const generatorEnd = installer.indexOf("\nBCRYPT_CODE=", generatorStart); assert.ok(urlHelperStart >= 0 && urlHelperEnd > urlHelperStart); assert.ok(reloadStart >= 0 && reloadEnd > reloadStart); assert.ok(layoutStart >= 0 && layoutEnd > layoutStart); assert.ok(probeStart >= 0 && probeEnd > probeStart && tokenStart >= 0 && tokenEnd > tokenStart); assert.ok(generatorStart >= 0 && generatorEnd > generatorStart); const tokenHelper = installer.slice(tokenStart, tokenEnd); const urlHelper = installer.slice(urlHelperStart, urlHelperEnd); for (const host of ["::1", "[::1]"]) { assert.equal(execFileSync("bash", ["-c", `${urlHelper}\nbuild_public_url http "$1" ${httpPort}`, "fixture", host], { encoding: "utf8" }), `http://[::1]:${httpPort}`); } const generator = `trim_ws() { printf '%s' "$1"; } ui_info() { :; } ui_success() { :; } ui_warn() { printf '%s\\n' "$*"; } ui_error() { printf '%s\\n' "$*" >&2; } install_optional_nginx_brotli_module() { exit 90; } fix_nginx_static_permissions() { :; } curl() { if [ "$FIXTURE_REAL_RELOAD" = 1 ]; then command curl "$@"; return $?; fi local url="\${!#}" printf '%s200' "\${url##*/.adpanel-ready-}" } fixture_root() { case "$1:$2:$3" in systemctl:reload:nginx) printf 'reload\\n' >> /tmp/fixture-reloads if [ "$FIXTURE_RELOAD_FAIL" = 1 ] && [ "$(wc -l < /tmp/fixture-reloads)" -eq 1 ]; then return 1; fi if [ "$FIXTURE_REAL_RELOAD" = 1 ]; then nginx -s reload; return $?; fi ;; cp:-aT:--) if [ "$FIXTURE_RESTORE_FAIL" = 1 ] && [[ "$4" == /tmp/adpanel-nginx.*/adpanel.conf.file ]]; then return 1; fi "$@" ;; install:-m:0644) if [ -n "$FIXTURE_VHOST_EDIT" ] && [[ "$5" == /tmp/adpanel-nginx.*/next-$FIXTURE_VHOST_EDIT.file ]]; then printf '# concurrent operator edit\\n' >> "/etc/nginx/conf.d/$FIXTURE_VHOST_EDIT" fi "$@" ;; *) "$@" ;; esac } ${urlHelper} ${installer.slice(reloadStart, reloadEnd)} ${installer.slice(layoutStart, layoutEnd)} ${installer.slice(probeStart, probeEnd)} ${tokenHelper} ${installer.slice(generatorStart, generatorEnd)} if [ "$FIXTURE_HOLD_LOCK" = 1 ]; then exec {fixture_lock} name.startsWith("adpanel-nginx.")); assert.equal(backups.length, 1); const retainedBackup = `/tmp/${backups[0]}`; assert.equal(fs.readFileSync(`${retainedBackup}/adpanel.conf.file`, "utf8"), generated); fs.writeFileSync(vhost, generated); fs.rmSync(retainedBackup, { recursive: true }); assert.equal(fs.readFileSync("/etc/nginx/nginx.conf", "utf8"), nginxMain); const processes = []; function start(command, args, env = process.env) { const child = spawn(command, args, { cwd: panel, env, stdio: ["ignore", "pipe", "pipe"] }); const entry = { child, output: "", finished: once(child, "close") }; for (const stream of [child.stdout, child.stderr]) stream.on("data", chunk => { entry.output = (entry.output + chunk).slice(-6000); }); processes.push(entry); return entry; } async function stop(entry) { entry.child.kill(); const hardStop = setTimeout(() => entry.child.kill("SIGKILL"), 3000); try { await entry.finished; } finally { clearTimeout(hardStop); } } const mysql = require("mysql2/promise"); const mysqlOptions = { host: "127.0.0.1", user: "root", connectTimeout: 1000 }; try { execFileSync("mariadb-install-db", ["--no-defaults", "--user=root", "--datadir=/tmp/mysql", "--auth-root-authentication-method=normal", "--skip-test-db", "--force"], { stdio: "pipe" }); start("mariadbd", ["--no-defaults", "--user=root", "--datadir=/tmp/mysql", "--socket=/run/mysql.sock", "--pid-file=/run/mysql.pid", "--bind-address=127.0.0.1", "--innodb-buffer-pool-size=64M"]); start("redis-server", ["--bind", "127.0.0.1", "--save", "", "--appendonly", "no", "--dir", "/tmp"]); const database = await until("MariaDB", () => mysql.createConnection(mysqlOptions).catch(() => null)); try { await database.query("CREATE DATABASE prelogin_fixture"); } finally { await database.end(); } const panelEnv = { ...process.env, PATH: `/tmp/bin:${process.env.PATH}`, HOST: "127.0.0.1", HTTP_PORT: String(originPort), SESSION_STORE: "redis", REDIS_URL: "redis://127.0.0.1:6379", REDIS_ENSURE_PERSISTENCE: "false", ADPANEL_AGENT_ENABLED: "OFF", MYSQL_USER: "root", MYSQL_DATABASE: "prelogin_fixture", SESSION_SECRET: "synthetic-secret-for-isolated-prelogin-test-only", PANEL_HMAC_SECRET: fleetSecret }; let app = start(process.execPath, ["index.js"], panelEnv); await until("Express listener", () => request(originPort, "/healthz").then(reply => reply.status === 200).catch(() => false)); const signup = await mysql.createConnection({ ...mysqlOptions, database: "prelogin_fixture" }); try { const hash = await require("bcryptjs").hash(password, 10); await signup.execute("INSERT INTO users (email, password) VALUES (?, ?)", [email, hash]); const sealedToken = execFileSync(process.execPath, ["-e", 'process.stdout.write(require("./utils/node-token-crypto").encryptNodeToken(process.env.FIXTURE_NODE_TOKEN))'], { cwd: panel, encoding: "utf8", env: { ...panelEnv, FIXTURE_NODE_TOKEN: nodeToken } }); await signup.execute("INSERT INTO nodes (id, uuid, name, address, ports, token) VALUES (?, ?, ?, '127.0.0.1', '{}', ?)", [nodeId, nodeId, nodeId, sealedToken]); } finally { await signup.end(); } const savedGateFile = `${panel}/data/stealth.json`; assert.equal(JSON.parse(fs.readFileSync(savedGateFile, "utf8")).enabled, false); await checkLogin(originPort); await checkHeartbeat(originPort); await stop(app); const nginxMode = { ...panelEnv, NGINX_ENABLED: "1", APP_HOST: "127.0.0.1", APP_PORT: String(originPort), HTTP_PORT: String(httpPort) }; app = start(process.execPath, ["index.js"], nginxMode); await until("proxied Express listener", () => request(originPort, "/healthz").then(reply => reply.status === 200).catch(() => false)); const proxy = start("nginx", ["-g", "daemon off;"]); await until("Nginx", () => request(httpPort, "/healthz").then(reply => reply.status === 200).catch(() => false)); const occupied = net.createServer(); occupied.listen(0, "127.0.0.1"); await once(occupied, "listening"); try { render({ realReload: true, force: true, httpsPort: occupied.address().port, status: 3 }); assert.equal(fs.readFileSync(vhost, "utf8"), generated); assert.equal(fs.readFileSync(tlsVhost, "utf8"), generatedTls); assert.equal(fs.readFileSync("/tmp/fixture-reloads", "utf8"), "reload\nreload\n"); } finally { occupied.close(); } for (const port of [httpPort, tlsPort]) { await checkLogin(port); await checkHeartbeat(port); const asset = await request(port, "/js/fixture.js"); assert.equal(asset.text, "/* fixture */"); assert.match(asset.headers["cache-control"], /immutable/); assert.equal((await request(port, "/js/fixture.js.map")).status, 404); const error = await request(port, "/missing.css"); assert.equal(error.status, 404); assert.equal(error.text, "Request failed\n"); assert.match(error.headers["cache-control"], /no-store/); if (port === tlsPort) assert.ok(error.headers["strict-transport-security"]); } fs.writeFileSync(`${panel}/data/maintenance.json`, JSON.stringify({ enabled: true, reason: "Fixture maintenance" })); for (const port of [originPort, httpPort, tlsPort]) { const page = await until("maintenance activation", () => request(port, "/").then(reply => reply.status === 503 && reply)); assert.match(page.text, /Under Maintenance<\/title>/); assert.match(page.text, /Fixture maintenance/); assert.doesNotMatch(page.text, /adpanel|\/auth-assets\/favicon/i); assert.match(page.headers["cache-control"], /no-store/); const poll = await request(port, "/api/maintenance/status"); assert.equal(poll.status, 200); assert.match(poll.headers["cache-control"], /no-store/); assert.deepEqual(JSON.parse(poll.text), { active: true, scheduled_at: null }); } fs.unlinkSync(`${panel}/data/maintenance.json`); fs.linkSync(vhost, "/etc/nginx/original-managed-vhost"); render({ force: true, realReload: true }); assert.equal(fs.readFileSync("/etc/nginx/original-managed-vhost", "utf8"), generated); const redirect = await until("HTTP redirect", () => request(httpPort, "/login?fixture=1") .then(reply => reply.status === 301 && reply).catch(() => null)); assert.equal(redirect.headers.location, `https://127.0.0.1:${tlsPort}/login?fixture=1`); for (const port of [httpPort, tlsPort]) { const challenge = await request(port, "/.well-known/acme-challenge/fixture"); assert.equal(challenge.status, 200); assert.equal(challenge.text, "fixture challenge"); } await stop(app); const unavailable = await request(tlsPort, "/login"); assert.equal(unavailable.status, 502); assert.equal(unavailable.text, "Request failed\n"); assert.match(unavailable.headers["cache-control"], /no-store/); const gated = start(process.execPath, ["index.js"], { ...nginxMode, STEALTH_MODE: "true" }); await until("legacy gate listener", () => request(originPort, "/healthz").then(reply => reply.status === 200).catch(() => false)); assert.equal(JSON.parse(fs.readFileSync(savedGateFile, "utf8")).enabled, false); for (const port of [originPort, tlsPort]) { const icon = await request(port, "/auth-assets/favicon"); assert.equal(icon.status, port === originPort ? 204 : 404); assert.equal(icon.text, ""); assert.match(icon.headers["cache-control"], /no-store/); const login = await request(port, "/login", { headers: { "user-agent": "Mozilla/5.0", accept: "text/html" } }); assert.equal(login.status, 200); assert.match(login.headers["cache-control"], /no-store/); assert.doesNotMatch(login.text, /<form method="POST" action="\/login"/); } await stop(gated); await stop(proxy); fs.mkdirSync("/etc/nginx/sites-available"); fs.mkdirSync("/etc/nginx/sites-enabled"); fs.writeFileSync("/etc/nginx/nginx.conf", nginxMain.replace("conf.d/*.conf", "sites-enabled/*")); const defaultSite = "/etc/nginx/sites-enabled/default"; const defaultVhost = `server { listen ${httpPort} default_server; listen [::]:${httpPort} default_server; return 204; }\n`; fs.writeFileSync(defaultSite, defaultVhost); const enabled = "/etc/nginx/sites-enabled/adpanel.conf"; fs.symlinkSync(defaultSite, enabled); render({ status: 2 }); assert.equal(fs.readlinkSync(enabled), defaultSite); fs.unlinkSync(enabled); const challengePath = "/.well-known/acme-challenge/fixture"; const serverName = "panel.example.test"; const nameHeader = { headers: { Host: serverName } }; const ipv6Request = { ...nameHeader, ipv6: true }; render({ force: true, tls: false, serverName, bootstrap: true }); const debianHttp = "/etc/nginx/sites-available/adpanel.conf"; const debianTls = "/etc/nginx/sites-available/adpanel-ssl.conf"; const enabledTls = "/etc/nginx/sites-enabled/adpanel-ssl.conf"; const bootstrapVhost = fs.readFileSync(debianHttp, "utf8"); render({ force: true, serverName, reloadFails: true, status: 3 }); assert.equal(fs.readFileSync(debianHttp, "utf8"), bootstrapVhost); assert.equal(fs.readlinkSync(enabled), debianHttp); assert.throws(() => fs.lstatSync(debianTls), { code: "ENOENT" }); assert.throws(() => fs.lstatSync(enabledTls), { code: "ENOENT" }); start("nginx", ["-g", "daemon off;"]); const bootstrapChallenge = await until("IPv6 ACME bootstrap", () => request(httpPort, challengePath, ipv6Request).catch(() => null)); assert.equal(bootstrapChallenge.status, 200); assert.equal(bootstrapChallenge.text, "fixture challenge"); checkCertbotWiring(installer, panel, tokenHelper); render({ force: true, serverName, realReload: true }); assert.equal(fs.readlinkSync(enabled), debianHttp); assert.equal(fs.readlinkSync(enabledTls), debianTls); assert.equal(fs.readFileSync(defaultSite, "utf8"), defaultVhost); const debianRedirect = await until("Debian HTTP redirect", () => request(httpPort, "/login", nameHeader) .then(reply => reply.status === 301 && reply).catch(() => null)); assert.equal(debianRedirect.headers.location, `https://${serverName}:${tlsPort}/login`); for (const port of [httpPort, tlsPort]) { for (const options of [nameHeader, ipv6Request]) { const challenge = await request(port, challengePath, options); assert.equal(challenge.status, 200); assert.equal(challenge.text, "fixture challenge"); } } assert.equal((await request(httpPort, "/", { headers: { Host: "unmatched.example.test" } })).status, 204); assert.equal((await request(httpPort, "/", { ipv6: true, headers: { Host: "unmatched.example.test" } })).status, 204); start(process.execPath, ["index.js"], nginxMode); await until("Debian TLS origin", () => request(tlsPort, "/healthz").then(reply => reply.status === 200).catch(() => false)); await checkLogin(tlsPort); await checkHeartbeat(tlsPort); render({ tls: false, serverName: "::1", realReload: true }); const literalChallenge = await until("IPv6 literal vhost", () => request(httpPort, challengePath, { ipv6: true, headers: { Host: "[::1]" }, }).then(reply => reply.status === 200 && reply).catch(() => null)); assert.equal(literalChallenge.text, "fixture challenge"); assert.equal(fs.readFileSync(defaultSite, "utf8"), defaultVhost); console.log("PASS signed node heartbeats and unsigned rejection on all three paths"); console.log("PASS generated proxy: maintenance, local errors, dual-stack ACME, both config layouts, operator file preservation, reload and rollback faults, legacy gate"); } catch (error) { for (const { output } of processes) if (output) console.error(output); throw error; } finally { await Promise.all(processes.map(stop)); } } if (process.argv[2] === "--isolated") { verify().catch(error => { console.error(error); process.exitCode = 1; }); } else { runIsolated(); }