"use strict"; // Tests for audit findings 4-8 (branding / theming / maintenance hardening). // // 4. Branding writes were invisible to the audit trail: the global alert // endpoints wrote recordActivity entries while the branding, // login-background and dashboard-background POSTs only console.log'd — // an admin defacing the logo/background left no activity entry. All three // now record `_system` activity, and the heavy branding writes carry a // dedicated always-on rate limiter (the global /api limiter is // operator-toggleable via security.json and was disabled in this deploy). // // 5. Replaced logo uploads were never unlinked: disk creep, and the old // logo stayed downloadable at its random /images/ URL. The upload path // now removes the replaced file — but only ever files matching the // generated `logo-<16 hex>.` shape, so fixed-name assets // (favicon.ico, logo.webp, adpanel-dark.webp) can never be unlinked. // // 6. setBodyBackgroundInFile rewrote the live theme CSS with a plain // writeFileSync (a crash mid-write could truncate the stylesheet) and // interpolated the value as a String.replace replacement STRING, so // "$&"/"$'"/"$`" inside a legal URL expanded as replacement patterns and // mangled the CSS. Now: replacer functions + temp/rename. // // 7. /auth-assets/favicon fetched a hardcoded cdn.jsdelivr.net URL first — // an availability dependency for every login page and a supply-chain // trust decision in a third-party CDN repo; the ICO "replace favicon.ico" // upload was dead code because local files were never consulted. The // route is now local-first (upload -> configured URL -> built-in -> // CDN last resort, env-overridable), and DEFAULT_LOGO_URL points at the // panel's own asset. // // 8. Cosmetic/low: login-background mode "none" was reported as "upload"; // restoreAlertAfterMaintenance deleted the first alert matching the // injected text (an admin alert with identical wording could be removed); // the blanket JSON body limit default was 50MB on every authenticated // POST. // // index.js boots servers on require, so route-level behavior is locked with // source assertions (same technique as audit-p32-p41-p42.test.js); the // policy-only helpers (setBodyBackgroundInFile, removeOldLogoFile, // restoreAlertAfterMaintenance) are extracted from the source and exercised // directly against real/fake dependencies. const test = require("node:test"); const assert = require("node:assert"); const fs = require("node:fs"); const os = require("node:os"); const path = require("node:path"); const ROOT = path.join(__dirname, ".."); const INDEX_JS = path.join(ROOT, "index.js"); const BRANDING_JS = path.join(ROOT, "utils", "branding.js"); const BACKGROUND_JS = path.join(ROOT, "utils", "background.js"); const SETTINGS_JS = path.join(ROOT, "public", "js", "settings.js"); const NOTFOUND_EJS = path.join(ROOT, "views", "404.ejs"); const indexSource = fs.readFileSync(INDEX_JS, "utf8"); const brandingSource = fs.readFileSync(BRANDING_JS, "utf8"); const settingsJsSource = fs.readFileSync(SETTINGS_JS, "utf8"); const notFoundEjsSource = fs.readFileSync(NOTFOUND_EJS, "utf8"); const { makeCssBackground } = require("../utils/background"); const branding = require("../utils/branding"); function endIndexOfFunction(source, startMarker) { const start = source.indexOf(startMarker); assert.ok(start >= 0, `marker ${startMarker} not found`); const bodyStart = source.indexOf("{", start); let depth = 0; for (let i = bodyStart; i < source.length; i += 1) { if (source[i] === "{") depth += 1; else if (source[i] === "}") { depth -= 1; if (depth === 0) return i + 1; } } assert.fail(`unbalanced braces after marker ${startMarker}`); } function extractFunction(source, startMarker) { const start = source.indexOf(startMarker); assert.ok(start >= 0, `marker ${startMarker} not found`); const end = endIndexOfFunction(source, startMarker); return source.slice(start, end); } // --------------------------------------------------------------------------- // Finding 4 — audit logging + dedicated rate limiter on branding writes // --------------------------------------------------------------------------- test("finding 4: branding update records a _system branding_update activity entry", () => { const start = indexSource.indexOf('app.post("/api/admin/branding/update"'); const end = endIndexOfFunction(indexSource.slice(start), "async (req, res) => {") + start; const handler = indexSource.slice(start, end); assert.ok(handler.includes('recordActivity("_system", "branding_update"'), "branding_update activity entry required"); const savedGate = handler.indexOf("invalidateBrandingCache();"); const recordAt = handler.indexOf("recordActivity"); assert.ok(savedGate >= 0 && recordAt > savedGate, "the activity entry must only be written after a successful save"); }); test("finding 4: login background update records a _system activity entry", () => { const start = indexSource.indexOf('app.post("/api/admin/login-background"'); const end = endIndexOfFunction(indexSource.slice(start), "async (req, res) => {") + start; const handler = indexSource.slice(start, end); assert.ok(handler.includes('recordActivity("_system", "login_background_update"'), "login_background_update activity entry required"); }); test("finding 4: dashboard background update records a _system activity entry", () => { const start = indexSource.indexOf('app.post("/api/settings/background"'); const end = endIndexOfFunction(indexSource.slice(start), "async (req, res) => {") + start; const handler = indexSource.slice(start, end); assert.ok(handler.includes('recordActivity("_system", "dashboard_background_update"'), "dashboard_background_update activity entry required"); // Data-URL values can be tens of MB — they must be summarized, not logged raw. assert.ok(handler.includes("data-url"), "oversized data-URL values must be summarized in the audit entry"); }); test("finding 4: the branding write limiter exists and is mounted on all three POSTs", () => { assert.ok(indexSource.includes("brandingWriteRateLimiter") && indexSource.includes("createSettingsRateLimiters("), "the shared brandingWriteRateLimiter must be bound"); const policy = require("../services/settings-rate-limiters").SETTINGS_OPERATION_POLICIES.brandingWriteRateLimiter; assert.equal(policy.windowMs, 15 * 60 * 1000, "15-minute window"); assert.equal(policy.sessionMax, 20, "20 writes per session window"); assert.equal(policy.prefix, "branding-write:", "namespaced key"); const options = []; require("../utils/login-throttle").createAccountOperationLimiter({ ...policy, rateLimit: (config) => { options.push(config); return () => {}; } }); assert(options.every((config) => config.skip({ session: null })), "both tiers skip unauthenticated requests"); for (const route of [ 'app.post("/api/admin/branding/update", brandingWriteRateLimiter,', 'app.post("/api/admin/login-background", brandingWriteRateLimiter,', 'app.post("/api/settings/background", brandingWriteRateLimiter,', ]) { assert.ok(indexSource.includes(route), `missing dedicated limiter on ${route}`); } }); // --------------------------------------------------------------------------- // Finding 5 — replaced logo uploads are removed, and only generated ones // --------------------------------------------------------------------------- function loadRemoveOldLogoFile() { const fnSrc = extractFunction(indexSource, "function removeOldLogoFile("); const files = new Map(); const fakeFs = { existsSync: (p) => files.has(String(p)), unlinkSync: (p) => { if (!files.delete(String(p))) { const err = new Error("ENOENT"); throw err; } }, }; // The function references index.js's module-scope __dirname; the sandbox // binds it to the repo root so the image paths line up with the fakes. const api = new Function( "fs", "path", "console", "__dirname", "GENERATED_LOGO_FILENAME_RE", `${fnSrc}\nreturn { removeOldLogoFile };` )(fakeFs, path, console, ROOT, branding.GENERATED_LOGO_FILENAME_RE); return { ...api, files }; } test("finding 5: removeOldLogoFile unlinks a generated logo- file", () => { const { removeOldLogoFile, files } = loadRemoveOldLogoFile(); const name = "logo-0123456789abcdef.webp"; files.set(path.join(ROOT, "public", "images", name), true); removeOldLogoFile(name, null); assert.equal(files.size, 0, "the replaced logo must be deleted"); }); test("finding 5: removeOldLogoFile refuses fixed-name and non-generated assets", () => { const { removeOldLogoFile, files } = loadRemoveOldLogoFile(); for (const name of [ "favicon.ico", "logo.webp", "adpanel-dark.webp", "adpanel-dark.svg", "logo-555ab3848c936.webp", // 15 chars, not the generator's 16 hex "logo-ZZZZZZZZZZZZZZZZ.webp", // not hex "logo-555ab3848c9362f6.webp.exe", "../adpanel-dark.webp", ]) { files.set(path.join(ROOT, "public", "images", name), true); removeOldLogoFile(name, null); assert.ok(files.has(path.join(ROOT, "public", "images", name)), `${name} must never be unlinked`); } }); test("finding 5: removeOldLogoFile no-ops when the filename is the replacement", () => { const { removeOldLogoFile, files } = loadRemoveOldLogoFile(); const name = "logo-ffffffffffffffff.png"; files.set(path.join(ROOT, "public", "images", name), true); removeOldLogoFile(name, name); assert.ok(files.has(path.join(ROOT, "public", "images", name)), "same-file no-op"); }); test("finding 5: the branding route removes the replaced logo and cleans orphan writes", () => { const start = indexSource.indexOf('app.post("/api/admin/branding/update"'); const end = endIndexOfFunction(indexSource.slice(start), "async (req, res) => {") + start; const handler = indexSource.slice(start, end); assert.ok(handler.includes("removeOldLogoFile(previousLogoPath, localLogoPath)"), "replaced logo must be removed after a successful save"); assert.ok(handler.includes("removeOldLogoFile(writtenLogoFilename, previousLogoPath)"), "a freshly written upload must be removed if the save failed"); assert.ok(handler.includes("if (!configSaved)"), "the catch-block cleanup must be gated on the config not being saved"); }); test("finding 5: appName-only update preserves previous logo configuration", () => { const start = indexSource.indexOf('app.post("/api/admin/branding/update"'); const end = endIndexOfFunction(indexSource.slice(start), "async (req, res) => {") + start; const handler = indexSource.slice(start, end); assert.ok(handler.includes("localLogoPath = previousLogoPath;"), "must preserve previousLogoPath when no new logo payload is sent"); assert.ok(handler.includes("finalLogoUrl = previousBranding.logoUrl"), "must preserve previous logoUrl when no new logo payload is sent"); assert.ok(handler.includes("isExplicitReset"), "must handle explicit logo reset"); }); function loadRemoveOldLoginBackgroundFile() { const fnSrc = extractFunction(indexSource, "function removeOldLoginBackgroundFile("); const files = new Map(); const fakeFs = { existsSync: (p) => files.has(String(p)), unlinkSync: (p) => { if (!files.delete(String(p))) { const err = new Error("ENOENT"); throw err; } }, }; const api = new Function( "fs", "path", "console", "__dirname", "GENERATED_LOGIN_BG_FILENAME_RE", `${fnSrc}\nreturn { removeOldLoginBackgroundFile };` )(fakeFs, path, console, ROOT, branding.GENERATED_LOGIN_BG_FILENAME_RE); return { ...api, files }; } test("finding 5: removeOldLoginBackgroundFile protects bgvid.webm and fixed assets", () => { const { removeOldLoginBackgroundFile, files } = loadRemoveOldLoginBackgroundFile(); for (const fixedAsset of [ "bgvid.webm", "adpanel-dark.webp", "logo.webp", "favicon.ico", "../bgvid.webm", "login-background-short.mp4", ]) { files.set(path.join(ROOT, "public", "images", fixedAsset), true); removeOldLoginBackgroundFile(fixedAsset, null); assert.ok(files.has(path.join(ROOT, "public", "images", fixedAsset)), `${fixedAsset} must never be unlinked`); } // Generated upload or remote mirror must be unlinked const uploadName = "login-background-0123456789abcdef.mp4"; const mirrorName = "login-background-remote-0123456789abcdef.avif"; files.set(path.join(ROOT, "public", "images", uploadName), true); files.set(path.join(ROOT, "public", "images", mirrorName), true); removeOldLoginBackgroundFile(uploadName, null); removeOldLoginBackgroundFile(mirrorName, null); assert.ok(!files.has(path.join(ROOT, "public", "images", uploadName)), "generated upload must be unlinked"); assert.ok(!files.has(path.join(ROOT, "public", "images", mirrorName)), "generated mirror must be unlinked"); }); test("finding 5: login-background route gates catch cleanup on configSaved", () => { const start = indexSource.indexOf('app.post("/api/admin/login-background"'); const end = endIndexOfFunction(indexSource.slice(start), "async (req, res) => {") + start; const handler = indexSource.slice(start, end); assert.ok(handler.includes("if (!configSaved)"), "login background cleanup in catch must be gated on configSaved"); }); // --------------------------------------------------------------------------- // Finding 6 — atomic write + no replacement-pattern expansion // --------------------------------------------------------------------------- // setBodyBackgroundInFile contains brace-carrying regex literals // (/:root\s*\{/), which breaks a naive brace-counting extractor — bound the // slice by the next top-level declaration instead. function loadSetBodyBackgroundInFile() { const start = indexSource.indexOf("function setBodyBackgroundInFile("); const end = indexSource.indexOf('app.get("/api/servers/:bot/versions"', start); assert.ok(start >= 0 && end > start, "setBodyBackgroundInFile slice must be bounded"); const fnSrc = indexSource.slice(start, end); return new Function("fs", "path", "console", "process", `${fnSrc}\nreturn setBodyBackgroundInFile;`)( fs, path, console, process ); } test("finding 6: $-replacement patterns inside a legal URL stay literal", () => { const setBodyBackgroundInFile = loadSetBodyBackgroundInFile(); const dir = fs.mkdtempSync(path.join(os.tmpdir(), "adpanel-bg-")); try { const file = path.join(dir, "theme.css"); fs.writeFileSync(file, ":root {\n --ui-bg: #111111;\n}\nbody{ background: var(--ui-bg); }\n"); const evilUrl = "https://example.com/x?a=$&b=$'c=$`d=$1e=${}f=$0.png"; const cssVal = makeCssBackground("image", evilUrl); assert.ok(cssVal, "precondition: the URL must pass makeCssBackground validation"); assert.equal(setBodyBackgroundInFile(file, cssVal), true); const css = fs.readFileSync(file, "utf8"); assert.ok(css.includes(`--ui-bg: ${cssVal};`), "the value must be written byte-for-byte, with no $&/$'/$` expansion"); assert.ok(!css.includes("$1$3"), "the old replacement-string concatenation must be gone"); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("finding 6: the write is temp+rename, preserves mode, and leaves no temp files", () => { const setBodyBackgroundInFile = loadSetBodyBackgroundInFile(); const dir = fs.mkdtempSync(path.join(os.tmpdir(), "adpanel-bg-")); try { const file = path.join(dir, "theme.css"); fs.writeFileSync(file, ":root {\n --ui-bg: #111111;\n}\n", { mode: 0o640 }); assert.equal(setBodyBackgroundInFile(file, 'url("https://ok.example/i.png?v=1")'), true); assert.match(fs.readFileSync(file, "utf8"), /--ui-bg:\s*url\("https:\/\/ok\.example\/i\.png\?v=1"\);/); assert.equal(fs.statSync(file).mode & 0o777, 0o640, "the original file mode must be preserved"); // No :root and no --ui-bg: both must be appended. const file2 = path.join(dir, "plain.css"); fs.writeFileSync(file2, "body{ color: blue; }\n"); assert.equal(setBodyBackgroundInFile(file2, "#ff0000"), true); const css2 = fs.readFileSync(file2, "utf8"); assert.ok(css2.includes(":root{ --ui-bg: #ff0000; }"), "a :root block must be appended"); assert.ok(css2.includes("background: var(--ui-bg)"), "the body fallback rule must be appended"); const leftovers = fs.readdirSync(dir).filter((f) => f.includes(".tmp")); assert.deepEqual(leftovers, [], "no temp files may be left behind"); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("finding 6: the source no longer interpolates cssVal into a replacement string", () => { const start = indexSource.indexOf("function setBodyBackgroundInFile("); const end = indexSource.indexOf('app.get("/api/servers/:bot/versions"', start); const fnSrc = indexSource.slice(start, end); assert.ok(!fnSrc.includes("`${cssVal}`") && !fnSrc.includes("`$1${cssVal}$3`"), "replacement-string interpolation must be gone"); assert.ok(fnSrc.includes("renameSync"), "the write must be temp+rename"); }); // --------------------------------------------------------------------------- // Finding 7 — local-first favicon and logo, explicit override only as last resort // --------------------------------------------------------------------------- test("finding 7: /auth-assets/favicon resolves local assets before an optional remote fetch", () => { const start = indexSource.indexOf('app.get("/auth-assets/favicon"'); const end = endIndexOfFunction(indexSource.slice(start), "async (req, res) => {") + start; const handler = indexSource.slice(start, end); const localLogoAt = handler.indexOf("branding.localLogoPath"); const remoteLogoAt = handler.indexOf("branding.logoUrl"); const builtInAt = handler.indexOf("getBuiltInFaviconPath()"); const overrideAt = handler.indexOf("FIXED_FAVICON_REMOTE_URL"); assert.ok(localLogoAt >= 0, "admin-uploaded logo must be consulted (keeps the ICO favicon upload alive)"); assert.ok(remoteLogoAt > localLogoAt, "configured remote logo URL comes second"); assert.ok(builtInAt > remoteLogoAt, "local built-ins come before any remote fetch"); assert.ok(overrideAt > builtInAt, "the explicit override must be the last resort"); }); test("finding 7: the last-resort favicon has no built-in remote URL", () => { assert.match(indexSource, /const FIXED_FAVICON_REMOTE_URL = sanitizeLogoUrl\(process\.env\.FAVICON_REMOTE_URL\);/); }); test("finding 7: DEFAULT_LOGO_URL points at the panel's own asset", () => { assert.equal(branding.DEFAULT_LOGO_URL, "/images/adpanel-dark.svg"); assert.ok(!/^https?:/i.test(branding.DEFAULT_LOGO_URL), "the default logo must not depend on a third-party origin"); assert.ok(fs.existsSync(path.join(ROOT, "public", "images", "adpanel-dark.svg")), "the referenced local asset must ship with the panel"); }); test("finding 7: the 404 page no longer hardcodes a CDN logo fallback", () => { assert.ok(!notFoundEjsSource.includes("cdn.jsdelivr.net/gh/antonndev/ADCDn/adpanel-dark"), "the hardcoded CDN logo fallback must be gone"); assert.ok(notFoundEjsSource.includes("'/images/adpanel-dark.svg'"), "the local fallback must be used instead"); }); // --------------------------------------------------------------------------- // Finding 8a — login-background mode reports "none" for the default state // --------------------------------------------------------------------------- test("finding 8a: both login-background handlers report mode 'none' when nothing is configured", () => { assert.ok(!indexSource.includes('"upload" : "upload")'), "the upload/upload fallback must be gone"); const occurrences = indexSource.split("localLoginBackgroundPath ? \"upload\" : \"none\"").length - 1; assert.ok(occurrences >= 2, `GET and POST must both report 'none' (found ${occurrences})`); }); test("finding 8a: the settings UI understands mode 'none'", () => { assert.ok(settingsJsSource.includes("data.mode === 'none'"), "the modal must show a distinct default-state hint"); }); // --------------------------------------------------------------------------- // Finding 8b — maintenance pre-alert restore cannot eat an identical admin alert // --------------------------------------------------------------------------- function loadRestoreAlertAfterMaintenance() { const fnSrc = extractFunction(indexSource, "function restoreAlertAfterMaintenance("); return (alerts, state, savedRef) => { let saved = false; const sandboxAlerts = alerts; const restore = new Function( "getGlobalAlerts", "saveGlobalAlerts", "sanitizeGlobalAlertMessage", "console", `${fnSrc}\nreturn restoreAlertAfterMaintenance;` )( () => sandboxAlerts, (next) => { saved = true; savedRef.next = next; return true; }, (value) => String(value ?? ""), console ); restore(state); return { saved }; }; } test("finding 8b: an admin alert with identical wording survives an id-based restore", () => { const adminAlert = { id: "admin-1", message: "Maintenance soon", date: "2026-09-01T00:00:00Z" }; const injected = { id: "injected-9", message: "Maintenance soon", date: "2026-09-06T00:00:00Z" }; const alerts = [adminAlert, injected]; const savedRef = {}; const state = { pre_alert: { _alert_injected: true, _injected_alert_message: "Maintenance soon", _injected_alert_id: "injected-9" }, previous_alert_backup: adminAlert, }; loadRestoreAlertAfterMaintenance()(alerts, state, savedRef); assert.ok(savedRef.next, "alerts must be persisted after removal"); assert.deepEqual(savedRef.next, [adminAlert], "only the injected alert may be removed"); }); test("finding 8b: legacy states (no recorded id) never remove the backed-up admin alert", () => { const adminAlert = { id: "admin-1", message: "Maintenance soon" }; const injected = { id: "injected-9", message: "Maintenance soon" }; const alerts = [adminAlert, injected]; const savedRef = {}; const state = { pre_alert: { _alert_injected: true, _injected_alert_message: "Maintenance soon" }, previous_alert_backup: adminAlert, }; loadRestoreAlertAfterMaintenance()(alerts, state, savedRef); assert.deepEqual(savedRef.next, [adminAlert], "the legacy fallback must skip the backup id and remove the injected copy"); }); test("finding 8b: legacy states without a backup still remove the injected message", () => { const injected = { id: "injected-9", message: "Maintenance soon" }; const alerts = [injected]; const savedRef = {}; const state = { pre_alert: { _alert_injected: true, _injected_alert_message: "Maintenance soon" }, previous_alert_backup: null, }; loadRestoreAlertAfterMaintenance()(alerts, state, savedRef); assert.deepEqual(savedRef.next, [], "the injected alert must be removed"); }); test("finding 8b: a state with nothing to restore leaves the alert list untouched", () => { const alerts = [{ id: "admin-1", message: "keep me" }]; const savedRef = {}; const state = { pre_alert: { _alert_injected: false, _injected_alert_message: null, _injected_alert_id: null } }; const { saved } = loadRestoreAlertAfterMaintenance()(alerts, state, savedRef); assert.equal(saved, false, "no save may happen when there is nothing to remove"); }); test("finding 8b: both injection sites persist the injected alert id", () => { const occurrences = indexSource.split("state.pre_alert._injected_alert_id = injectedAlert").length - 1; assert.equal(occurrences, 2, "the maintenance checker and the settings POST must both record the id"); assert.ok(indexSource.includes("_injected_alert_id: null"), "the fresh pre_alert shape must carry the field"); }); // --------------------------------------------------------------------------- // Finding 8c — scoped JSON body limits // --------------------------------------------------------------------------- test("finding 8c: the blanket JSON default is 1mb, heavy routes keep scoped parsers", () => { assert.ok(indexSource.includes('const JSON_BODY_LIMIT = process.env.JSON_BODY_LIMIT || "1mb"'), "default JSON limit must be 1mb"); assert.ok(indexSource.includes('const DASHBOARD_BACKGROUND_JSON_LIMIT = process.env.DASHBOARD_BACKGROUND_JSON_LIMIT || "26mb"'), "dashboard background needs its own budget (24M-char data URLs)"); assert.ok(indexSource.includes('if (req.method === "POST" && /^\\/api\\/settings\\/background$/.test(req.path || "")) {'), "the dashboard background parser must be dispatched"); assert.ok(indexSource.includes('jsonParserDashboardBackground = express.json({ limit: DASHBOARD_BACKGROUND_JSON_LIMIT })'), "the scoped parser must be constructed"); });