Files
2026-11-30 16:32:37 +00:00

704 lines
21 KiB
JavaScript

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 <link rel="icon" type="..."> 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("<svg") || head.startsWith("<?xml") || head.includes("<svg")) {
const svgResult = validateSvgBuffer(buffer);
if (svgResult.valid) {
return { valid: true, data: svgResult.data, ext: "svg" };
} else {
return { valid: false, error: svgResult.error || "Invalid or malicious SVG file" };
}
}
}
let validType = false;
for (const magic of Object.values(IMAGE_MAGIC_BYTES)) {
if (magic === null) continue;
let matches = true;
for (let i = 0; i < magic.length; i++) {
if (buffer[i] !== magic[i]) {
matches = false;
break;
}
}
if (matches) {
validType = true;
break;
}
}
if (!validType && buffer.length >= 12) {
// AVIF (and other ISO-BMFF based images) start with a "ftyp" box at
// offset 4 followed by a brand. Accept AVIF still images.
const isFtyp = buffer[4] === 0x66 && buffer[5] === 0x74 && buffer[6] === 0x79 && buffer[7] === 0x70;
if (isFtyp) {
const brand = buffer.toString("ascii", 8, 12).toLowerCase();
const compat = buffer.toString("ascii", 8, Math.min(64, buffer.length)).toLowerCase();
if (brand === "avif" || brand === "avis" || compat.includes("avif") || compat.includes("avis")) {
validType = true;
}
}
}
if (!validType) {
return { valid: false, error: "Unrecognized image format. SVG is only allowed for logo source." };
}
return { valid: true, data: buffer };
}
function validateBase64Image(base64Data, options = {}) {
try {
if (typeof base64Data !== "string") {
return { valid: false, error: "Failed to decode image data" };
}
let cleanBase64 = base64Data;
if (base64Data.includes(",")) {
cleanBase64 = base64Data.split(",")[1];
}
return validateImageBuffer(Buffer.from(cleanBase64, "base64"), options);
} catch (err) {
return { valid: false, error: "Failed to decode image data" };
}
}
function getValidatedExtension(filename, options = {}) {
if (!filename || typeof filename !== "string") {
return null;
}
const parts = filename.toLowerCase().split(".");
if (parts.length < 2) {
return null;
}
const ext = parts[parts.length - 1].replace(/[^a-z0-9]/g, "");
const allowSvg = Boolean(options && options.allowSvg);
const allowed = allowSvg ? ALLOWED_LOGO_EXTENSIONS : ALLOWED_EXTENSIONS;
if (allowed.includes(ext)) {
return ext;
}
return null;
}
function getValidatedLogoExtension(filename) {
return getValidatedExtension(filename, { allowSvg: true });
}
function getValidatedVideoExtension(filename) {
if (!filename || typeof filename !== "string") {
return null;
}
const parts = filename.toLowerCase().split(".");
if (parts.length < 2) {
return null;
}
const ext = parts[parts.length - 1].replace(/[^a-z0-9]/g, "");
if (ALLOWED_VIDEO_EXTENSIONS.includes(ext)) {
return ext;
}
return null;
}
function getMimeTypeForExtension(extension) {
if (!extension || typeof extension !== "string") {
return null;
}
const normalized = extension.toLowerCase().replace(/[^a-z0-9]/g, "");
if (normalized === "png") return "image/png";
if (normalized === "jpg" || normalized === "jpeg") return "image/jpeg";
if (normalized === "webp") return "image/webp";
if (normalized === "avif") return "image/avif";
if (normalized === "gif") return "image/gif";
if (normalized === "ico") return "image/x-icon";
if (normalized === "svg") return "image/svg+xml";
return VIDEO_MIME_TYPES[normalized] || null;
}
function getMediaTypeFromFilename(filename) {
if (getValidatedExtension(filename)) return "image";
if (getValidatedVideoExtension(filename)) return "video";
return null;
}
function getMediaTypeFromUrl(url) {
if (!url || typeof url !== "string") {
return null;
}
try {
const parsed = new URL(url);
const pathname = (parsed.pathname || "").toLowerCase();
const ext = pathname.includes(".") ? pathname.slice(pathname.lastIndexOf(".") + 1) : "";
if (!ext) return null;
if (ALLOWED_EXTENSIONS.includes(ext)) return "image";
if (ALLOWED_VIDEO_EXTENSIONS.includes(ext)) return "video";
} catch (err) {
return null;
}
return null;
}
function getExtensionFromUrl(url, options = {}) {
if (!url || typeof url !== "string") {
return null;
}
try {
const parsed = new URL(url);
const pathname = (parsed.pathname || "").toLowerCase();
if (!pathname.includes(".")) return null;
const ext = pathname.slice(pathname.lastIndexOf(".") + 1).replace(/[^a-z0-9]/g, "");
const allowSvg = Boolean(options && options.allowSvg);
const allowed = allowSvg ? ALLOWED_LOGO_EXTENSIONS : ALLOWED_EXTENSIONS;
if (allowed.includes(ext) || ALLOWED_VIDEO_EXTENSIONS.includes(ext)) {
return ext;
}
} catch (err) {
return null;
}
return null;
}
function getLogoExtensionFromUrl(url) {
return getExtensionFromUrl(url, { allowSvg: true });
}
function validateVideoBuffer(buffer, expectedExt, declaredMime = "") {
if (!Buffer.isBuffer(buffer)) {
return { valid: false, error: "Invalid video data" };
}
if (buffer.length < 32) {
return { valid: false, error: "Video data too small" };
}
if (buffer.length > 40 * 1024 * 1024) {
return { valid: false, error: "Video too large (max 40MB)" };
}
const ext = String(expectedExt || "").toLowerCase();
let valid = false;
if (ext === "webm") {
valid = buffer[0] === 0x1a && buffer[1] === 0x45 && buffer[2] === 0xdf && buffer[3] === 0xa3;
} else if (ext === "mp4") {
valid = buffer.slice(4, 8).toString("ascii") === "ftyp";
} else if (ext === "ogg" || ext === "ogv") {
valid = buffer.slice(0, 4).toString("ascii") === "OggS";
}
if (!valid) {
return { valid: false, error: "Unrecognized video format" };
}
if (declaredMime && !declaredMime.startsWith("video/")) {
return { valid: false, error: "Invalid video MIME type" };
}
return { valid: true, data: buffer };
}
function validateBase64Video(base64Data, expectedExt) {
try {
if (typeof base64Data !== "string") {
return { valid: false, error: "Failed to decode video data" };
}
let cleanBase64 = base64Data;
let declaredMime = "";
if (base64Data.startsWith("data:")) {
const match = base64Data.match(/^data:([^;,]+)[;,]/i);
declaredMime = match ? String(match[1] || "").toLowerCase() : "";
}
if (base64Data.includes(",")) {
cleanBase64 = base64Data.split(",")[1];
}
return validateVideoBuffer(Buffer.from(cleanBase64, "base64"), expectedExt, declaredMime);
} catch (err) {
return { valid: false, error: "Failed to decode video data" };
}
}
function invalidateBrandingCache() {
brandingCache = null;
brandingCacheTime = 0;
}
function sanitizeAppName(appName) {
if (!appName || typeof appName !== "string") {
return null;
}
const trimmed = appName.trim().slice(0, 50);
const sanitized = trimmed.replace(/[^a-zA-Z0-9\s\-_.!]/g, "");
if (sanitized.length < 1) {
return null;
}
return sanitized;
}
function isPrivateOrReservedHost(hostname) {
if (!hostname) return true;
const h = hostname.toLowerCase();
if (h === "localhost" || h.endsWith(".localhost")) return true;
const ipv4 = h.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
if (ipv4) {
const [a, b] = [parseInt(ipv4[1], 10), parseInt(ipv4[2], 10)];
if (a === 0) return true; // 0.0.0.0/8
if (a === 10) return true; // 10.0.0.0/8
if (a === 127) return true; // 127.0.0.0/8
if (a === 169 && b === 254) return true; // 169.254.0.0/16 (link-local / cloud metadata)
if (a === 172 && b >= 16 && b <= 31) return true; // 172.16.0.0/12
if (a === 192 && b === 168) return true; // 192.168.0.0/16
return false;
}
// IPv6 (Node.js URL parser may keep brackets)
const ipv6 = h.startsWith("[") && h.endsWith("]") ? h.slice(1, -1) : h;
if (ipv6 === "::1" || ipv6 === "::" || ipv6.startsWith("fe80:") || ipv6.startsWith("fc") || ipv6.startsWith("fd")) return true;
if (ipv6.startsWith("::ffff:")) {
const mapped = ipv6.slice(7);
// Dotted-decimal form (::ffff:127.0.0.1)
if (mapped.includes(".")) return isPrivateOrReservedHost(mapped);
// Hex form (::ffff:7f00:1) — convert to IPv4
const hex = mapped.replace(":", "").padStart(8, "0");
const a = parseInt(hex.slice(0, 2), 16), b = parseInt(hex.slice(2, 4), 16);
const c = parseInt(hex.slice(4, 6), 16), d = parseInt(hex.slice(6, 8), 16);
return isPrivateOrReservedHost(`${a}.${b}.${c}.${d}`);
}
return false;
}
function sanitizeLogoUrl(url) {
if (!url || typeof url !== "string") {
return null;
}
const trimmed = url.trim();
if (!trimmed.startsWith("http://") && !trimmed.startsWith("https://")) {
return null;
}
try {
const parsed = new URL(trimmed);
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
return null;
}
// Block requests to internal/private network addresses (SSRF protection)
if (isPrivateOrReservedHost(parsed.hostname)) {
return null;
}
return parsed.href;
} catch (e) {
return null;
}
}
// adpanel:branding-load-sanitization — load-time twin of the save route's
// sanitize set: appName/logoUrl/loginBackgroundExternalUrl are exactly the
// fields the save route runs through sanitizeAppName/sanitizeLogoUrl (a
// hand-edited config must not get wider acceptance than the admin API), and
// existing local paths stay basename-guarded at every resolve site. Legacy
// URLs for bundled media resolve to their local files without a network fetch.
function sanitizeLoadedBrandingConfig(config) {
const logoFilename = resolveBundledMediaFilename(config.logoUrl);
const backgroundFilename = resolveBundledMediaFilename(config.loginBackgroundExternalUrl);
const bundledLogo = getValidatedLogoExtension(logoFilename);
const backgroundType = getMediaTypeFromFilename(backgroundFilename);
return {
...config,
appName: sanitizeAppName(config.appName) || DEFAULT_BRANDING.appName,
logoUrl: bundledLogo ? null : sanitizeLogoUrl(config.logoUrl),
...(bundledLogo && !resolveLocalBrandingAssetUrl(config.localLogoPath, config) ? { localLogoPath: logoFilename } : {}),
loginBackgroundExternalUrl: backgroundType ? null : sanitizeLogoUrl(config.loginBackgroundExternalUrl),
...(backgroundType ? {
localLoginBackgroundPath: backgroundFilename,
loginBackgroundType: backgroundType,
loginBackgroundMimeType: getMimeTypeForExtension(getValidatedExtension(backgroundFilename) || getValidatedVideoExtension(backgroundFilename))
} : {})
};
}
function brandingMiddleware(req, res, next) {
const branding = loadBrandingConfig();
const safeLogo = safeBasename(branding.localLogoPath);
const localLogoExists = Boolean(safeLogo && fs.existsSync(path.join(PUBLIC_IMAGES_DIR, safeLogo)));
res.locals.branding = {
appName: branding.appName || DEFAULT_BRANDING.appName,
faviconUrl: resolveFaviconAssetUrl(branding),
faviconMimeType: resolveFaviconMimeType(branding),
logoUrl: localLogoExists
? `/images/${safeLogo}${getBrandingAssetVersionSuffix(branding)}`
: (branding.logoUrl || DEFAULT_LOGO_URL),
loginBackgroundType: branding.loginBackgroundType || DEFAULT_BRANDING.loginBackgroundType,
loginBackgroundUrl: resolveLoginBackgroundAssetUrl(branding),
loginBackgroundMimeType: branding.loginBackgroundMimeType || DEFAULT_BRANDING.loginBackgroundMimeType
};
next();
}
module.exports = {
brandingMiddleware,
loadBrandingConfig,
saveBrandingConfig,
sanitizeAppName,
sanitizeLogoUrl,
sanitizeLoadedBrandingConfig,
resolveBundledMediaFilename,
preferBundledMediaUrl,
generateSafeLogoFilename,
GENERATED_LOGO_FILENAME_RE,
GENERATED_LOGIN_BG_FILENAME_RE,
validateImageBuffer,
validateBase64Image,
validateVideoBuffer,
validateBase64Video,
validateSvgBuffer,
sanitizeSvg,
getValidatedExtension,
getValidatedLogoExtension,
getValidatedVideoExtension,
getMimeTypeForExtension,
getMediaTypeFromFilename,
getMediaTypeFromUrl,
getExtensionFromUrl,
getLogoExtensionFromUrl,
getBrandingAssetVersionSuffix,
resolveFaviconAssetUrl,
resolveFaviconMimeType,
resolveLoginBackgroundAssetUrl,
invalidateBrandingCache,
ALLOWED_EXTENSIONS,
ALLOWED_LOGO_EXTENSIONS,
DEFAULT_BRANDING,
DEFAULT_LOGIN_BACKGROUND_URL,
DEFAULT_LOGO_URL
};