const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
const { validateSvgBuffer, sanitizeSvg } = require("./svg-sanitizer");
const BRANDING_CONFIG_PATH = path.join(__dirname, "..", "data", "branding.json");
let brandingCache = null;
let brandingCacheTime = 0;
const CACHE_TTL = 60000;
const DEFAULT_BRANDING = {
appName: "ADPanel",
logoUrl: null,
localLogoPath: null,
loginBackgroundType: "video",
loginBackgroundExternalUrl: null,
localLoginBackgroundPath: null,
loginBackgroundMimeType: "video/webm"
};
// Allowed extensions for login background (raster/video only; SVG rejected for backgrounds).
const ALLOWED_EXTENSIONS = ["png", "jpg", "jpeg", "webp", "ico", "avif", "gif"];
// Allowed extensions for brand logo (SVG is supported with strict security sanitization & CSP sandboxing).
const ALLOWED_LOGO_EXTENSIONS = ["png", "jpg", "jpeg", "webp", "ico", "avif", "gif", "svg"];
const ALLOWED_VIDEO_EXTENSIONS = ["webm", "mp4", "ogg", "ogv"];
const GENERATED_LOGO_FILENAME_RE = /^logo-[0-9a-f]{16}\.[a-z0-9]+$/;
const GENERATED_LOGIN_BG_FILENAME_RE = /^login-background-(remote-)?[0-9a-f]{16}\.[a-z0-9]+$/;
const DEFAULT_LOGIN_BACKGROUND_URL = "/images/bgvid.webm";
// Default brand logo shown everywhere until an admin uploads/sets a custom
// one. Served from the panel's own public/ assets: the historical value was a
// pinned cdn.jsdelivr.net URL, which made every login page an availability
// dependent on — and a trust decision in — a third-party CDN repo. The local
// file is the same asset that URL mirrored.
const DEFAULT_LOGO_URL = "/images/adpanel-dark.svg";
const PUBLIC_IMAGES_DIR = path.join(__dirname, "..", "public", "images");
const BUNDLED_MEDIA_ALIASES = new Map([
["https://logos-world.net/wp-content/uploads/2021/03/FiveM-Symbol.png", "fivem.avif"],
["https://cdn.cloudflare.steamstatic.com/steam/apps/730/header.jpg", "cs2.avif"],
]);
function resolveBundledMediaFilename(value) {
if (typeof value !== "string") return null;
const url = value.trim();
const filename = BUNDLED_MEDIA_ALIASES.get(url)
|| /^(?:\/images\/|https?:\/\/cdn\.jsdelivr\.net\/gh\/antonndev\/adcdn(?:@[\w.-]+)?\/)([\w.-]{1,255})(?:[?#][^\r\n]*)?$/i.exec(url)?.[1];
if (!filename || filename.startsWith(".") || !(getValidatedLogoExtension(filename) || getValidatedVideoExtension(filename))) {
return null;
}
try {
return fs.lstatSync(path.join(PUBLIC_IMAGES_DIR, filename), { throwIfNoEntry: false })?.isFile() ? filename : null;
} catch {
return null;
}
}
function preferBundledMediaUrl(value) {
if (typeof value !== "string" || value.trimStart().startsWith("/")) return value;
const filename = resolveBundledMediaFilename(value);
return filename ? `/images/${filename}` : value;
}
const IMAGE_MAGIC_BYTES = {
png: [0x89, 0x50, 0x4E, 0x47],
jpg: [0xFF, 0xD8, 0xFF],
jpeg: [0xFF, 0xD8, 0xFF],
webp: [0x52, 0x49, 0x46, 0x46],
ico: [0x00, 0x00, 0x01, 0x00],
gif: [0x47, 0x49, 0x46, 0x38], // "GIF8"
avif: null // detected separately (ISO-BMFF "ftyp" box, brand "avif"/"avis")
};
const VIDEO_MIME_TYPES = {
webm: "video/webm",
mp4: "video/mp4",
ogg: "video/ogg",
ogv: "video/ogg"
};
// Prevent path traversal in local asset filenames
function safeBasename(p) {
if (!p || typeof p !== 'string') return null;
const b = path.basename(p);
return (b && b !== '.' && b !== '..') ? b : null;
}
function getBrandingAssetVersionSuffix(branding) {
const updatedAt = typeof branding?.updatedAt === "string" ? branding.updatedAt.trim() : "";
return updatedAt ? `?v=${encodeURIComponent(updatedAt)}` : "";
}
function resolveLocalBrandingAssetUrl(filename, branding) {
const safe = safeBasename(filename);
if (!safe) return null;
const assetPath = path.join(PUBLIC_IMAGES_DIR, safe);
if (!fs.existsSync(assetPath)) return null;
return `/images/${safe}${getBrandingAssetVersionSuffix(branding)}`;
}
function resolveLoginBackgroundAssetUrl(branding) {
const config = branding && typeof branding === "object" ? branding : loadBrandingConfig();
const localUrl = resolveLocalBrandingAssetUrl(config.localLoginBackgroundPath, config);
if (localUrl) return localUrl;
if (config.loginBackgroundExternalUrl) {
return `/branding-media/login-background${getBrandingAssetVersionSuffix(config)}`;
}
return DEFAULT_LOGIN_BACKGROUND_URL;
}
function resolveFaviconAssetUrl(branding) {
const config = branding && typeof branding === "object" ? branding : loadBrandingConfig();
const safeLogo = safeBasename(config.localLogoPath);
if (safeLogo && fs.existsSync(path.join(PUBLIC_IMAGES_DIR, safeLogo))) {
return `/images/${safeLogo}${getBrandingAssetVersionSuffix(config)}`;
}
const remoteLogoUrl = String(config.logoUrl || "").trim();
if (remoteLogoUrl) {
return remoteLogoUrl;
}
return DEFAULT_LOGO_URL;
}
// Resolve the favicon MIME type so the attribute
// matches the actual asset extension. This mirrors the resolution order used by
// the /auth-assets/favicon route (local logo -> remote logo URL -> built-in default).
function resolveFaviconMimeType(branding) {
const config = branding && typeof branding === "object" ? branding : loadBrandingConfig();
// 1. Custom uploaded logo (stored locally) — derive type from its extension.
const localLogo = safeBasename(config.localLogoPath);
if (localLogo) {
const ext = getValidatedLogoExtension(localLogo);
if (ext) return getMimeTypeForExtension(ext) || "image/webp";
}
// 2. Custom remote logo URL — derive type from its extension.
const remoteLogoUrl = String(config.logoUrl || "").trim();
if (remoteLogoUrl) {
const ext = getLogoExtensionFromUrl(remoteLogoUrl);
if (ext) return getMimeTypeForExtension(ext) || "image/webp";
}
// 3. Built-in favicon referenced by the page (adpanel-dark.svg).
return "image/svg+xml";
}
function loadBrandingConfig() {
const now = Date.now();
if (brandingCache && (now - brandingCacheTime) < CACHE_TTL) {
return brandingCache;
}
try {
if (fs.existsSync(BRANDING_CONFIG_PATH)) {
const data = fs.readFileSync(BRANDING_CONFIG_PATH, "utf8");
const config = JSON.parse(data);
// The login watermark feature was removed; never resurrect legacy keys
// from an old config (they would otherwise be re-persisted on save).
delete config.loginWatermarkUrl;
delete config.localLoginWatermarkPath;
// adpanel:branding-load-sanitization — the save route sanitizes, but
// data/branding.json is operator-editable at rest (hand-edited or
// co-opted): load must not trust what save validated once. Re-run the
// module's OWN sanitizers (the exact ones the save route applies — no
// fork, no second copy of the rules) so a hand-edited javascript:,
// protocol-relative or private-host URL cannot reach the auth pages —
// whose CSP derives img-src from the branding logo origin — and an
// oversized/control-char appName is cut down to the save path's
// alphabet. Anything a sanitizer rejects falls back exactly as a
// rejected save would (middleware defaults, not a crash).
brandingCache = sanitizeLoadedBrandingConfig({
...DEFAULT_BRANDING,
...config
});
brandingCacheTime = now;
return brandingCache;
}
} catch (err) {
console.error("[branding] Error loading config:", err.message);
}
brandingCache = { ...DEFAULT_BRANDING };
brandingCacheTime = now;
return brandingCache;
}
function saveBrandingConfig(config) {
try {
const dataDir = path.dirname(BRANDING_CONFIG_PATH);
if (!fs.existsSync(dataDir)) {
fs.mkdirSync(dataDir, { recursive: true });
}
const existing = loadBrandingConfig();
const newConfig = {
...existing,
...config,
updatedAt: new Date().toISOString()
};
const tempPath = BRANDING_CONFIG_PATH + ".tmp";
fs.writeFileSync(tempPath, JSON.stringify(newConfig, null, 2), { mode: 0o600 });
fs.renameSync(tempPath, BRANDING_CONFIG_PATH);
brandingCache = null;
brandingCacheTime = 0;
return true;
} catch (err) {
console.error("[branding] Error saving config:", err.message);
return false;
}
}
function generateSafeLogoFilename(extension) {
const randomId = crypto.randomBytes(8).toString("hex");
return `logo-${randomId}.${extension}`;
}
function validateImageBuffer(buffer, options = {}) {
const allowSvg = Boolean(options && options.allowSvg);
if (!Buffer.isBuffer(buffer)) {
return { valid: false, error: "Invalid image data" };
}
if (buffer.length < 8) {
return { valid: false, error: "Image data too small" };
}
if (buffer.length > 5 * 1024 * 1024) {
return { valid: false, error: "Image too large (max 5MB)" };
}
// SVG support for logo source with enterprise-grade sanitization
if (allowSvg) {
const head = buffer.slice(0, Math.min(512, buffer.length)).toString("utf8").trim().toLowerCase();
if (head.startsWith("