An open source, self-hosted, real-time port monitoring and discovery tool.
Remove network host dependency and improve port detection (#34)
Mostafa Wahiedde16120185f3
diff --git a/.gitignore b/.gitignoreindex 5c1ad33..af6d784 100644--- a/.gitignore+++ b/.gitignore@@ -5,6 +5,8 @@ node_modules/dist/build/+misc/+# Ignore specific backend filesbackend/data/*.dbbackend/data/*.jsondiff --git a/Dockerfile b/Dockerfileindex fef9e2d..9dcceb5 100644--- a/Dockerfile+++ b/Dockerfile@@ -51,6 +51,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \wget \sqlite3 \procps \+ util-linux \&& rm -rf /var/lib/apt/lists/*WORKDIR /app@@ -71,13 +72,13 @@ RUN mkdir -p /dataWORKDIR /app/backend# Environment variables+ENV NODE_ENV=productionENV PORT=4999ENV DATABASE_PATH=/data/portracker.db# Volume for data persistenceVOLUME /data-# Expose portEXPOSE 4999# Health checkdiff --git a/backend/collectors/base_collector.js b/backend/collectors/base_collector.jsindex 5b1bb96..c9f2337 100644--- a/backend/collectors/base_collector.js+++ b/backend/collectors/base_collector.js@@ -6,6 +6,8 @@* applications, ports, and virtual machines from a specific platform.*/+const { Logger } = require("../lib/logger");+class BaseCollector {/*** Create a new collector instance@@ -16,6 +18,9 @@ class BaseCollector {this.debug = config.debug || false;this.platform = "generic";this.platformName = "Generic Platform";++ // Initialize logger for this collector+ this.logger = new Logger(this.platformName, { debug: this.debug });}/**@@ -93,7 +98,7 @@ class BaseCollector {},};} catch (error) {- this.logError(`Error collecting all data: ${error.message}`);+ this.logger.error(`Error collecting all data: ${error.message}`);return {platform: this.platform,platformName: this.platformName,@@ -142,6 +147,7 @@ class BaseCollector {vm_id: entry.vm_id || null,app_id: entry.app_id || null,created: entry.created || null,+ internal: entry.internal || false,};}@@ -150,7 +156,7 @@ class BaseCollector {* @param {...any} args Arguments to log*/logInfo(...args) {- console.log(`[${this.platformName}] INFO:`, ...args);+ this.logger.info(...args);}/**@@ -158,9 +164,7 @@ class BaseCollector {* @param {...any} args Arguments to log*/log(...args) {- if (this.debug) {- console.log(`[${this.platformName}] DEBUG:`, ...args);- }+ this.logger.debug(...args);}/**@@ -168,7 +172,7 @@ class BaseCollector {* @param {...any} args Arguments to log*/logError(...args) {- console.error(`[${this.platformName}] ERROR:`, ...args);+ this.logger.error(...args);}/**@@ -176,7 +180,7 @@ class BaseCollector {* @param {...any} args Arguments to log*/logWarn(...args) {- console.warn(`[${this.platformName}] WARN:`, ...args);+ this.logger.warn(...args);}}diff --git a/backend/collectors/docker_collector.js b/backend/collectors/docker_collector.jsindex a0f0c55..2342525 100644--- a/backend/collectors/docker_collector.js+++ b/backend/collectors/docker_collector.js@@ -12,6 +12,7 @@ const util = require("util");const execAsync = util.promisify(exec);const fs = require("fs");const os = require("os");+const ProcParser = require("../lib/proc-parser");class DockerCollector extends BaseCollector {/**@@ -23,6 +24,7 @@ class DockerCollector extends BaseCollector {this.platform = "docker";this.platformName = "Docker";this.name = "Docker Collector";+ this.procParser = new ProcParser();}/**@@ -296,10 +298,9 @@ class DockerCollector extends BaseCollector {const allPorts = [];const dockerPortsMap = new Map();const dockerProcessMap = new Map();- const containerCreationTimeMap = new Map(); // Add this+ const containerCreationTimeMap = new Map();try {- // Get container creation timesconst dockerContainers = await this.getApplications();dockerContainers.forEach((container) => {if (container.created) {@@ -311,7 +312,6 @@ class DockerCollector extends BaseCollector {dockerPorts.forEach((port) => {const key = `${port.host_ip}:${port.host_port}`;if (!dockerPortsMap.has(key)) {- // Add created timestamp from containerif (port.container_id) {port.created = containerCreationTimeMap.get(port.container_id) || null;}@@ -327,6 +327,19 @@ class DockerCollector extends BaseCollector {dockerProcessMap.set(pid, container);});}++ if (container.internalPorts && container.internalPorts.length > 0) {+ container.internalPorts.forEach((internalPort) => {+ const publishedKey = `${internalPort.host_ip}:${internalPort.host_port}`;+ const internalKey = `${internalPort.host_ip}:${internalPort.host_port}:${container.id}:internal`;++ if (!dockerPortsMap.has(publishedKey) && !dockerPortsMap.has(internalKey)) {+ internalPort.created = containerCreationTimeMap.get(container.id) || null;+ dockerPortsMap.set(internalKey, internalPort);+ allPorts.push(this.normalizePortEntry(internalPort));+ }+ });+ }});} catch (dockerErr) {this.logWarn("Failed to collect Docker container-specific data:", dockerErr.message);@@ -352,7 +365,6 @@ class DockerCollector extends BaseCollector {containerId: container.id,target: `${container.id.substring(0, 12)}:internal(host-net)`,};- // Add created timestamp for host-networked containersport.created = containerCreationTimeMap.get(container.id) || null;break;}@@ -463,6 +475,27 @@ class DockerCollector extends BaseCollector {exposedPorts = null;}+ const internalPorts = [];+ if (exposedPorts && typeof exposedPorts === 'object') {+ Object.keys(exposedPorts).forEach(portDef => {+ const [port, protocol] = portDef.split('/');+ const portNum = parseInt(port, 10);+ if (!isNaN(portNum)) {+ internalPorts.push({+ source: "docker",+ owner: containerName,+ protocol: protocol || "tcp",+ host_ip: "0.0.0.0",+ host_port: portNum,+ target: `${containerId.substring(0, 12)}:${portNum}(internal)`,+ container_id: containerId,+ app_id: containerName,+ internal: true+ });+ }+ });+ }+return {id: containerId,name: containerName,@@ -470,6 +503,7 @@ class DockerCollector extends BaseCollector {networkMode: networkMode,exposedPorts: exposedPorts,pids: pids,+ internalPorts: internalPorts};} catch (inspectErr) {this.logWarn(@@ -681,24 +715,75 @@ class DockerCollector extends BaseCollector {*/async _getLinuxSystemPorts() {try {- this.logInfo('Attempting to get Linux ports with "ss -tulnp" command');- const { stdout } = await execAsync("ss -tulnp");- return this._parseLinuxSystemOutput(stdout);- } catch (err) {- this.logWarn(- `Linux "ss" command failed: ${err.message}. Trying "netstat" as fallback.`- );+ this.logInfo("Attempting nsenter method for comprehensive port collection with process names");+ const { stdout } = await execAsync("nsenter -t 1 -n ss -tulpn 2>/dev/null");+ const ports = this._parseLinuxSystemOutput(stdout);+ this.logInfo(`nsenter method successful: ${ports.length} ports found with process names`);+ return ports;+ } catch (nsenterErr) {+ this.logInfo(`nsenter method failed: ${nsenterErr.message}, trying alternative methods`);+try {- this.logInfo(- 'Attempting to get Linux ports with "netstat -tulnp" command (fallback)'- );- const { stdout } = await execAsync("netstat -tulnp");- return this._parseLinuxSystemOutput(stdout, true);- } catch (fallbackErr) {- this.logError(- `Linux "netstat" fallback also failed: ${fallbackErr.message}`- );- return [];+ const { stdout: netNsCheck } = await execAsync("readlink /proc/self/ns/net 2>/dev/null");+ const { stdout: hostNetNsCheck } = await execAsync("readlink /proc/1/ns/net 2>/dev/null");++ if (netNsCheck.trim() === hostNetNsCheck.trim()) {+ this.logInfo("Container has host network access, using direct ss");+ const { stdout } = await execAsync("ss -tulpn 2>/dev/null || ss -tuln");+ return this._parseLinuxSystemOutput(stdout);+ } else {+ this.logInfo("Limited network access, using container namespace ss");+ const { stdout } = await execAsync("ss -tulpn 2>/dev/null || ss -tuln");+ return this._parseLinuxSystemOutput(stdout);+ }+ } catch (nsCheckErr) {+ this.logInfo(`Network namespace check failed: ${nsCheckErr.message}, falling back to /proc method`);++ if (this.procParser) {+ try {+ this.logInfo("Falling back to /proc filesystem method");+ const procWorks = await this.procParser.testProcAccess();++ if (procWorks) {+ const tcpPorts = await this.procParser.getTcpPorts();+ const includeAllUdp = process.env.INCLUDE_UDP === 'true';+ const udpPorts = await this.procParser.getUdpPorts(includeAllUdp);+ const allPorts = [...tcpPorts, ...udpPorts];++ if (allPorts.length >= 2) {+ for (const port of allPorts) {+ if (port.pid) {+ const containerId = await this.procParser.getContainerByPid(port.pid);+ if (containerId) {+ port.container_id = containerId;+ port.source = 'docker';+ try {+ const { stdout } = await execAsync(`docker inspect --format '{{.Name}}' ${containerId}`);+ port.owner = stdout.trim().replace(/^\//, '');+ } catch (err) {+ // Container might have been removed+ }+ }+ }+ }++ this.logInfo(`Fallback /proc method: ${allPorts.length} ports found (TCP: ${tcpPorts.length}, UDP: ${udpPorts.length})`);+ return allPorts.map(port => this.normalizePortEntry(port));+ }+ }+ } catch (procErr) {+ this.logWarn("Proc fallback also failed:", procErr.message);+ }+ }++ try {+ this.logInfo("Final fallback: netstat command");+ const { stdout } = await execAsync("netstat -tulnp 2>/dev/null || netstat -tuln");+ return this._parseLinuxSystemOutput(stdout, true);+ } catch (fallbackErr) {+ this.logError(`All methods failed: ${fallbackErr.message}`);+ return [];+ }}}}@@ -741,7 +826,6 @@ class DockerCollector extends BaseCollector {_parseLinuxSystemOutput(output, isNetstat = false) {const entries = [];const lines = output.split("\n");-const startIndex = isNetstat ? 2 : 1;for (let i = startIndex; i < lines.length; i++) {@@ -791,19 +875,35 @@ class DockerCollector extends BaseCollector {}}- entries.push(- this.normalizePortEntry({- source: "system",- owner,- protocol: protocol.includes("tcp") ? "tcp" : "udp",- host_ip: host_ip === "*" ? "0.0.0.0" : host_ip,- host_port,- target: null,- container_id: null,- app_id: null,- pids: pid !== null ? [pid] : [],- })- );+ if (owner === "dockerd") {+ entries.push(+ this.normalizePortEntry({+ source: "docker",+ owner: "unknown",+ protocol: protocol.includes("tcp") ? "tcp" : "udp",+ host_ip: host_ip === "*" ? "0.0.0.0" : host_ip,+ host_port,+ target: null,+ container_id: null,+ app_id: null,+ pids: pid !== null ? [pid] : [],+ })+ );+ } else {+ entries.push(+ this.normalizePortEntry({+ source: "system",+ owner,+ protocol: protocol.includes("tcp") ? "tcp" : "udp",+ host_ip: host_ip === "*" ? "0.0.0.0" : host_ip,+ host_port,+ target: null,+ container_id: null,+ app_id: null,+ pids: pid !== null ? [pid] : [],+ })+ );+ }}return entries;diff --git a/backend/collectors/index.js b/backend/collectors/index.jsindex 270df6b..b4f3b1a 100644--- a/backend/collectors/index.js+++ b/backend/collectors/index.js@@ -5,6 +5,7 @@* a factory method to create the appropriate collector for a platform.*/+const { Logger } = require("../lib/logger");const BaseCollector = require("./base_collector");const TrueNASCollector = require("./truenas_collector");const DockerCollector = require("./docker_collector");@@ -29,28 +30,20 @@ function createCollector(platform = "base", config = {}) {}/**- * Auto-detect the best collector for the current system- * @param {Object} config Configuration options- * @returns {Promise<BaseCollector>} The best collector for this system+ * Asynchronously selects and returns the most compatible collector for the current system.+ *+ * Evaluates available collector types by their compatibility scores and returns the collector with the highest positive score. If no compatible collector is found, returns a system collector as a fallback.+ *+ * @param {Object} config - Optional configuration settings, such as debug mode.+ * @returns {Promise<BaseCollector>} A promise that resolves to the most suitable collector instance for the system.*/async function detectCollector(config = {}) {const debug = config.debug || false;-- function logInfo(message) {- console.log("[Collector] INFO:", message);- }- function logDebug(...args) {- if (debug) {- console.log("[Collector] DEBUG:", ...args);- }- }- function logWarn(...args) {- console.warn("[Collector] WARN:", ...args);- }+ const logger = new Logger("Collector", { debug });if (debug) {- logDebug("--- detectCollector START ---");- logDebug("Collector detection config:", config);+ logger.debug("--- detectCollector START ---");+ logger.debug("Collector detection config:", config);}const collectorTypes = ["truenas", "docker", "system"];@@ -62,45 +55,45 @@ async function detectCollector(config = {}) {if (!collectors[type]) continue;const collector = createCollector(type, { debug });- logDebug(`Attempting compatibility check for ${type}...`);+ logger.debug(`Attempting compatibility check for ${type}...`);try {const score = await collector.isCompatible();detectionDetails[type] = score;if (debug) {- logDebug(`Compatibility score for ${type}: ${score}`);+ logger.debug(`Compatibility score for ${type}: ${score}`);}if (score > highestScore) {highestScore = score;bestCollector = collector;- logDebug(+ logger.debug(`New best collector: ${type} (score: ${score}, previous best: ${highestScore})`);}} catch (err) {- logWarn(`Error checking compatibility for ${type}:`, err.message);+ logger.warn(`Error checking compatibility for ${type}:`, err.message);detectionDetails[type] = 0;}}if (debug) {- logDebug(`Final detection scores:`, detectionDetails);+ logger.debug(`Final detection scores:`, detectionDetails);}if (bestCollector && highestScore > 0) {const message = `Auto-detected ${bestCollector.platform} collector with score ${highestScore}`;- logInfo(message);- logDebug("--- detectCollector END (returning bestCollector) ---");+ logger.info(message);+ logger.debug("--- detectCollector END (returning bestCollector) ---");return bestCollector;}const systemCollector = createCollector("system", { debug });- logInfo(+ logger.info("No compatible collector detected with score > 0, using system collector");- logDebug("--- detectCollector END (returning system fallback) ---");+ logger.debug("--- detectCollector END (returning system fallback) ---");return systemCollector;}diff --git a/backend/collectors/system_collector.js b/backend/collectors/system_collector.jsindex d83d8c5..a2e66bf 100644--- a/backend/collectors/system_collector.js+++ b/backend/collectors/system_collector.js@@ -11,6 +11,7 @@ const { exec } = require("child_process");const util = require("util");const os = require("os");const execAsync = util.promisify(exec);+const ProcParser = require("../lib/proc-parser");class SystemCollector extends BaseCollector {/**@@ -23,6 +24,7 @@ class SystemCollector extends BaseCollector {this.platformName = "Local System";this.name = "System Collector";this.isWindows = os.platform() === "win32";+ this.procParser = new ProcParser();}/**@@ -146,6 +148,49 @@ class SystemCollector extends BaseCollector {async getPorts() {try {this.log("Collecting system ports");++ // First try to use /proc parsing if available with effectiveness test+ if (!this.isWindows && this.procParser) {+ try {+ this.log("Testing /proc filesystem access effectiveness...");+ const procWorks = await this.procParser.testProcAccess();++ if (procWorks) {+ this.log("Attempting to get ports via /proc filesystem");+ const tcpPorts = await this.procParser.getTcpPorts();++ // Use proper UDP filtering logic - include important UDP ports even when INCLUDE_UDP=false+ const includeAllUdp = process.env.INCLUDE_UDP === 'true';+ const udpPorts = await this.procParser.getUdpPorts(includeAllUdp);++ const allPorts = [...tcpPorts, ...udpPorts];++ if (allPorts.length >= 3) {+ this.log(`Successfully collected ${allPorts.length} ports via /proc (TCP: ${tcpPorts.length}, UDP: ${udpPorts.length})`);+ return allPorts.map(port => this.normalizePortEntry({+ source: "system",+ owner: port.owner,+ protocol: port.protocol,+ host_ip: port.host_ip,+ host_port: port.host_port,+ pid: port.pid,+ platform_data: {+ process: port.owner,+ pid: port.pid,+ },+ }));+ } else {+ this.logWarn(`/proc parsing returned only ${allPorts.length} ports, falling back to commands`);+ }+ } else {+ this.logWarn("/proc access test failed, falling back to commands");+ }+ } catch (procErr) {+ this.logWarn("Failed to get ports via /proc, falling back to commands:", procErr.message);+ }+ }++ // Fallback to existing command-based approachif (this.isWindows) {return await this.getWindowsPorts();} else {diff --git a/backend/collectors/truenas_collector.js b/backend/collectors/truenas_collector.jsindex c499ceb..d20f442 100644--- a/backend/collectors/truenas_collector.js+++ b/backend/collectors/truenas_collector.js@@ -20,6 +20,7 @@ const execAsync = util.promisify(exec);const fs = require("fs");const { TrueNASClient } = require("../lib/truenas-rpc");const PerformanceTracker = require("../utils/performance-tracker");+const ProcParser = require("../lib/proc-parser");class TrueNASCollector extends BaseCollector {/**@@ -32,6 +33,7 @@ class TrueNASCollector extends BaseCollector {this.platformName = "TrueNAS";this.name = "TrueNAS Collector";this.client = new TrueNASClient({ debug: this.debug });+ this.procParser = new ProcParser();// Initialize cache systemthis.cache = {@@ -416,46 +418,76 @@ class TrueNASCollector extends BaseCollector {);const lines = stdout.trim().split("\n");const ports = [];+for (const line of lines) {if (!line.trim()) continue;const [name, portsStr, containerId] = line.split("|");- if (!portsStr || portsStr === "") continue;++ if (!portsStr || portsStr === "") {+ continue;+ }+const portMappings = portsStr.split(", ");for (const mapping of portMappings) {- if (!mapping.includes("->")) continue;- const [external, internal] = mapping.split("->");- let hostIP = "*";- let hostPort;- if (external.includes(":")) {- const parts = external.split(":");- hostIP = this._resolveHostIP(parts[0]);- hostPort = parts[1];- } else {- hostPort = external;- hostIP = this._getServerIP();- }- const [containerPort, proto] = internal.split("/");++ if (mapping.includes("->")) {+ const [external, internal] = mapping.split("->");++ let hostIP = "*";+ let hostPort;+ if (external.includes(":")) {+ const parts = external.split(":");+ hostIP = this._resolveHostIP(parts[0]);+ hostPort = parts[1];+ } else {+ hostPort = external;+ hostIP = this._getServerIP();+ }+ const [containerPort, proto] = internal.split("/");- if (hostIP.endsWith(".255")) {- this.log(- `Skipping broadcast address port for ${name}: ${hostIP}:${hostPort}`- );- continue;- }+ if (hostIP.endsWith(".255")) {+ this.log(+ `Skipping broadcast address port for ${name}: ${hostIP}:${hostPort}`+ );+ continue;+ }- ports.push({- source: "docker",- owner: name,- protocol: proto || "tcp",- host_ip: hostIP,- host_port: parseInt(hostPort, 10),- target: containerPort,- container_id: containerId,- vm_id: null,- app_id: containerId,- });+ ports.push({+ source: "docker",+ owner: name,+ protocol: proto || "tcp",+ host_ip: hostIP,+ host_port: parseInt(hostPort, 10),+ target: containerPort,+ container_id: containerId,+ vm_id: null,+ app_id: containerId,+ });+ } else if (mapping.match(/^\d+\/(tcp|udp)$/)) {+ const [port, protocol] = mapping.split('/');+ const portNum = parseInt(port, 10);+ if (!isNaN(portNum)) {+ ports.push({+ source: "docker",+ owner: name,+ protocol: protocol || "tcp",+ host_ip: "0.0.0.0",+ host_port: portNum,+ target: `${containerId.substring(0, 12)}:${portNum}(internal)`,+ container_id: containerId,+ vm_id: null,+ app_id: containerId,+ internal: true+ });+ }+ } else {+ // Pattern didn't match - this is normal for some Docker port formats+ }}}++ this.log(`Total ports collected: ${ports.length}`);+return ports;} catch (err) {this.logError(@@ -546,70 +578,242 @@ class TrueNASCollector extends BaseCollector {}/**- * Get system ports using ss command+ * Get system ports using platform-adaptive approach* @returns {Promise<Array>} List of system ports*/async _getSystemPorts() {+ this.logInfo('=== TrueNAS System Ports Collection (Platform-Adaptive) ===');++ // METHOD 1: Try enhanced /proc parsing first (highest accuracy for containerized environments)+ if (this.procParser) {+ try {+ this.logInfo('Attempting primary method: Enhanced /proc filesystem parsing');+ const procWorks = await this.procParser.testProcAccess();++ if (procWorks) {+ const tcpPorts = await this.procParser.getTcpPorts();+ const includeUdp = process.env.INCLUDE_UDP === 'true';+ const udpPorts = await this.procParser.getUdpPorts(includeUdp);++ const allPorts = [...tcpPorts, ...udpPorts].map(port => ({+ source: 'system',+ owner: port.owner,+ protocol: port.protocol,+ host_ip: port.host_ip === '*' ? '0.0.0.0' : port.host_ip,+ host_port: port.host_port,+ target: null,+ container_id: null,+ app_id: null,+ pids: port.pid ? [port.pid] : []+ }));++ this.logInfo(`Enhanced /proc parsing successful: ${allPorts.length} ports found`);+ if (allPorts.length > 0) {+ return allPorts;+ }+ } else {+ this.logWarn('Enhanced /proc filesystem test failed, trying fallback methods');+ }+ } catch (procErr) {+ this.logWarn('Failed to get ports via enhanced /proc parsing:', procErr.message);+ }+ }++ // METHOD 2: Try ss command (fallback for non-containerized environments)try {- this.log('Getting system ports via "ss -tulpn"');- const { stdout } = await execAsync("ss -tulpn");- const lines = stdout.trim().split("\n");- const ports = [];- const includeUdp = process.env.INCLUDE_UDP === "true";+ this.logInfo('Attempting secondary method: ss command');+ const { stdout } = await execAsync('ss -tulpn 2>/dev/null');+ const ports = this._parseSSOutput(stdout);+ this.logInfo(`ss command successful: ${ports.length} ports found`);+ if (ports.length > 0) {+ return ports;+ }+ } catch (ssErr) {+ this.logWarn(`ss command failed: ${ssErr.message}, trying tertiary methods`);+ }++ // METHOD 3: Try netstat command+ try {+ this.logInfo('Attempting tertiary method: netstat command');+ const { stdout } = await execAsync('netstat -tulpn 2>/dev/null');+ const ports = this._parseNetstatOutput(stdout);+ this.logInfo(`netstat command successful: ${ports.length} ports found`);+ if (ports.length > 0) {+ return ports;+ }+ } catch (netstatErr) {+ this.logWarn(`netstat command failed: ${netstatErr.message}, trying final fallback`);+ }- for (let i = 1; i < lines.length; i++) {- const line = lines[i].trim();- if (!line) continue;- const columns = line.split(/\s+/);- if (columns.length < 5) continue;- const protocol = columns[0].toLowerCase();+ // METHOD 4: Try nsenter for host network access (last resort)+ try {+ this.logInfo('Attempting fallback method: nsenter for host network access');+ const { stdout } = await execAsync('nsenter -t 1 -n ss -tulpn 2>/dev/null');+ if (stdout.trim()) {+ const ports = this._parseSSOutput(stdout);+ this.logInfo(`nsenter method successful: ${ports.length} ports found`);+ return ports;+ }+ } catch (nsenterErr) {+ this.logWarn(`nsenter method failed: ${nsenterErr.message}`);+ }- if (!includeUdp && !protocol.startsWith("tcp")) {- continue; // Default behavior: skip non-TCP ports- }+ this.logError('All port collection methods failed');+ return [];+ }++ /**+ * Parse ss command output to extract port information+ * @param {string} output ss command output+ * @returns {Array} Parsed port entries+ */+ _parseSSOutput(output) {+ const entries = [];+ const lines = output.split('\n');++ for (let i = 1; i < lines.length; i++) {+ const line = lines[i].trim();+ if (!line) continue;++ const cols = line.split(/\s+/);+ if (cols.length < 5) continue;++ // ss output format: Netid State Recv-Q Send-Q Local-Address:Port Peer-Address:Port Process+ const protocol = cols[0].toLowerCase();+ if (!protocol.includes('tcp') && !protocol.includes('udp')) continue;++ const state = cols[1];+ // Only include listening ports+ if (protocol.includes('tcp') && state !== 'LISTEN') continue;+ if (protocol.includes('udp') && state !== 'UNCONN') continue;- const localAddress = columns[4];- const match = localAddress.match(/(.+):(\d+)$/);+ const localAddr = cols[4];+ if (!localAddr || !localAddr.includes(':')) continue;++ let host_ip, portStr;+ // Handle IPv6 addresses [::]:port and IPv4 addresses ip:port+ if (localAddr.includes('[') && localAddr.includes(']:')) {+ const match = localAddr.match(/\[(.+)\]:(\d+)$/);if (!match) continue;+ host_ip = match[1];+ portStr = match[2];+ } else {+ const lastColon = localAddr.lastIndexOf(':');+ if (lastColon === -1) continue;+ host_ip = localAddr.substring(0, lastColon);+ portStr = localAddr.substring(lastColon + 1);+ }- let [, address, port] = match;- if (address.includes("%")) {- address = address.split("%")[0];+ const host_port = parseInt(portStr, 10);+ if (isNaN(host_port) || host_port <= 0 || host_port > 65535) continue;++ // Extract process information if available+ let owner = 'unknown';+ let pid = null;+ if (cols.length > 6) {+ const processCol = cols[6];+ if (processCol && processCol !== '-') {+ // Format: users:(("process",pid=123,fd=5))+ const processMatch = processCol.match(/users:\(\("([^"]+)",pid=(\d+)/);+ if (processMatch) {+ owner = processMatch[1];+ pid = parseInt(processMatch[2], 10);+ }}+ }- const processMatch = line.match(/users:\(\("([^"]+)",pid=(\d+),/);- const process = processMatch ? processMatch[1] : null;- const pid = processMatch ? parseInt(processMatch[2], 10) : null;+ entries.push({+ source: 'system',+ owner,+ protocol: protocol.includes('tcp') ? 'tcp' : 'udp',+ host_ip: host_ip === '*' ? '0.0.0.0' : host_ip,+ host_port,+ target: null,+ container_id: null,+ app_id: null,+ pids: pid !== null ? [pid] : []+ });+ }- let resolvedHostIP;- if (address === "0.0.0.0" || address === "::") {- resolvedHostIP = "0.0.0.0";- } else {- resolvedHostIP = address;- }+ return entries;+ }- ports.push({- source: "system",- owner: process || "system",- protocol: protocol === "tcp" ? "tcp" : "udp",- host_ip: resolvedHostIP,- host_port: parseInt(port, 10),- target: null,- container_id: null,- vm_id: null,- app_id: null,- pid: pid,- });+ /**+ * Parse netstat command output to extract port information+ * @param {string} output netstat command output+ * @returns {Array} Parsed port entries+ */+ _parseNetstatOutput(output) {+ const entries = [];+ const lines = output.split('\n');++ for (let i = 2; i < lines.length; i++) {+ const line = lines[i].trim();+ if (!line) continue;++ const cols = line.split(/\s+/);+ if (cols.length < 4) continue;++ const protocol = cols[0].toLowerCase();+ if (!protocol.includes('tcp') && !protocol.includes('udp')) return;++ const localAddr = cols[3];+ if (!localAddr || !localAddr.includes(':')) continue;++ // Only include listening TCP ports or all UDP ports+ if (protocol.includes('tcp')) {+ const state = cols[5];+ if (state !== 'LISTEN') continue;}- return ports;- } catch (err) {- this.logError(- 'Error getting system ports via "ss":',- err.message,- err.stack- );- return [];++ let host_ip, portStr;+ // Handle IPv6 addresses [::]:port and IPv4 addresses ip:port+ if (localAddr.includes('[') && localAddr.includes(']:')) {+ const match = localAddr.match(/\[(.+)\]:(\d+)$/);+ if (!match) continue;+ host_ip = match[1];+ portStr = match[2];+ } else {+ const lastColon = localAddr.lastIndexOf(':');+ if (lastColon === -1) continue;+ host_ip = localAddr.substring(0, lastColon);+ portStr = localAddr.substring(lastColon + 1);+ }++ const host_port = parseInt(portStr, 10);+ if (isNaN(host_port) || host_port <= 0 || host_port > 65535) continue;++ // Extract process information if available (last column)+ let owner = 'unknown';+ let pid = null;+ if (cols.length > 6) {+ const processCol = cols[cols.length - 1];+ if (processCol && processCol !== '-') {+ const pidMatch = processCol.match(/^(\d+)\//);+ if (pidMatch) {+ pid = parseInt(pidMatch[1], 10);+ const nameMatch = processCol.match(/\/(.+)$/);+ if (nameMatch) {+ owner = nameMatch[1];+ }+ }+ }+ }++ entries.push({+ source: 'system',+ owner,+ protocol: protocol.includes('tcp') ? 'tcp' : 'udp',+ host_ip: host_ip === '*' ? '0.0.0.0' : host_ip,+ host_port,+ target: null,+ container_id: null,+ app_id: null,+ pids: pid !== null ? [pid] : []+ });}++ return entries;}/**@@ -700,11 +904,11 @@ class TrueNASCollector extends BaseCollector {size: "N/A",mounts: "N/A",networks: container.networks || "N/A",- ports: this._parseDockerPorts(container.ports),+ ports: [], // Will be populated below with both host-mapped and internal ports},})));- this.logInfo(`Collected ${dockerContainers.length} Docker containers`);+ this.log(`Collected ${dockerContainers.length} Docker containers`);} catch (err) {this.logWarn("Docker container collection failed:", err.message);}@@ -717,6 +921,30 @@ class TrueNASCollector extends BaseCollector {const dockerPorts = await this._getDockerPorts();perf.end("docker-ports-collection");+ // Group docker ports by container ID for attribution+ const portsByContainer = new Map();+ dockerPorts.forEach(port => {+ if (port.container_id) {+ if (!portsByContainer.has(port.container_id)) {+ portsByContainer.set(port.container_id, []);+ }+ portsByContainer.get(port.container_id).push({+ host_ip: port.host_ip,+ host_port: port.host_port,+ container_port: parseInt(port.target.toString().split(':')[1]?.split('(')[0] || port.host_port),+ protocol: port.protocol,+ internal: port.internal || false+ });+ }+ });++ // Populate platform_data.ports for each application+ results.applications.forEach(app => {+ if (app.platform === "docker" && portsByContainer.has(app.id)) {+ app.platform_data.ports = portsByContainer.get(app.id);+ }+ });+perf.start("system-ports-collection");const systemPorts = await this._getCachedOrFresh("systemPorts",@@ -792,7 +1020,10 @@ class TrueNASCollector extends BaseCollector {await this._buildHostProcToContainerMap();for (const port of dockerPorts) {- const key = `${port.host_ip}:${port.host_port}`;+ // Use different key pattern for internal vs external ports+ const key = port.internal+ ? `${port.container_id}:${port.host_port}:internal`+ : `${port.host_ip}:${port.host_port}`;port.created =containerCreationTimeMap.get(port.container_id) || null;uniquePorts.set(key, port);@@ -940,8 +1171,16 @@ class TrueNASCollector extends BaseCollector {const apiKey = process.env.TRUENAS_API_KEY;if (apiKey) {this.logInfo("API key detected - collecting enhanced TrueNAS features");++ const timeoutPromise = new Promise((_, reject) =>+ setTimeout(() => reject(new Error("TrueNAS connection timeout after 15 seconds")), 15000)+ );+try {- const enhancedData = await this._collectEnhancedFeatures();+ const enhancedData = await Promise.race([+ this._collectEnhancedFeatures(),+ timeoutPromise+ ]);if (enhancedData.systemInfo) {results.systemInfo = {...results.systemInfo,@@ -969,7 +1208,7 @@ class TrueNASCollector extends BaseCollector {},}));results.applications.push(...truenasApps);- this.logInfo(`Collected ${truenasApps.length} TrueNAS native apps`);+ this.log(`Collected ${truenasApps.length} TrueNAS native apps`);}if (enhancedData.vms && enhancedData.vms.length > 0) {results.vms = enhancedData.vms.map((vm) => ({@@ -990,17 +1229,19 @@ class TrueNASCollector extends BaseCollector {orig_data: vm,},}));- this.logInfo(`Collected ${results.vms.length} virtual machines`);+ this.log(`Collected ${results.vms.length} virtual machines`);}this.logInfo("Enhanced features collection completed successfully");} catch (err) {- this.logWarn(- `Enhanced features collection failed: ${err.message.substring(- 0,- 100- )}...`- );- this.logInfo("Continuing with core functionality only");+ this.logWarn("TrueNAS enhanced features collection failed:", err.message);+ this.logInfo("Continuing with Docker and system port data only");+ } finally {+ if (this.client) {+ try {+ this.client.close();+ } catch (closeErr) {+ }+ }}} else {this.logInfo(@@ -1014,13 +1255,13 @@ class TrueNASCollector extends BaseCollector {perf.end("total-collection");- // Log performance summary+ // Log performance summary at debug levelconst summary = perf.getSummary();- this.logInfo("=== Performance Summary ===");+ this.log("=== Performance Summary ===");summary.forEach(({ operation, duration }) => {- this.logInfo(` ${operation}: ${duration}ms`);+ this.log(` ${operation}: ${duration}ms`);});- this.logInfo("=== End Performance Summary ===");+ this.log("=== End Performance Summary ===");// Log cache status for monitoringconst cacheStatus = Object.keys(this.cache)@@ -1034,11 +1275,11 @@ class TrueNASCollector extends BaseCollector {}).join(", ");- this.logInfo(`Cache status: ${cacheStatus}`);+ this.log(`Cache status: ${cacheStatus}`);this.logInfo(`Collection complete: ${results.applications.length} apps, ${results.ports.length} ports, ${results.vms.length} VMs`);- this.logInfo(+ this.log(`Enhanced features: ${results.enhancedFeaturesEnabled ? "ENABLED" : "DISABLED"}`@@ -1513,7 +1754,7 @@ class TrueNASCollector extends BaseCollector {try {const systemInfo = await this.client.call("system.info");results.systemInfo = systemInfo;- this.logInfo("Enhanced system info retrieved");+ this.log("Enhanced system info retrieved");} catch (err) {this.logWarn("Enhanced system info API call failed:",@@ -1523,7 +1764,6 @@ class TrueNASCollector extends BaseCollector {try {const apps = await this.client.call("app.query");results.apps = apps || [];- this.logInfo(`Found ${results.apps.length} TrueNAS apps via API`);} catch (err) {this.logWarn("TrueNAS apps API query failed:",@@ -1533,7 +1773,6 @@ class TrueNASCollector extends BaseCollector {try {const vms = await this.client.call("virt.instance.query");results.vms = vms || [];- this.logInfo(`Found ${results.vms.length} VMs via API`);} catch (err) {this.logWarn("VM API query failed:", err.message.substring(0, 50));}diff --git a/backend/db.js b/backend/db.jsindex cb76f3a..7ed5ce6 100644--- a/backend/db.js+++ b/backend/db.js@@ -2,41 +2,10 @@const fs = require("fs");const path = require("path");const Database = require("better-sqlite3");+const { Logger } = require("./lib/logger");-/**- * Log database INFO message- * @param {...any} args Arguments to log- */-function dbLog(...args) {- console.log("[Database] INFO:", ...args);-}--/**- * Log database ERROR message- * @param {...any} args Arguments to log- */-function dbError(...args) {- console.error("[Database] ERROR:", ...args);-}--/**- * Log database WARN message- * @param {...any} args Arguments to log- */-function dbWarn(...args) {- console.warn("[Database] WARN:", ...args);-}--/**- * Log database DEBUG message (only if appDebugEnabled is true)- * @param {boolean} appDebugEnabled - Whether application-level debug is enabled.- * @param {...any} args Arguments to log- */-function dbDebug(appDebugEnabled, ...args) {- if (appDebugEnabled) {- console.log("[Database] DEBUG:", ...args);- }-}+// Initialize logger for database operations+const logger = new Logger("Database", { debug: process.env.DEBUG === 'true' });// Where to store DB: use env if present, else fallback to ./data/ports-tracker.dbconst defaultDataDir = path.resolve(process.cwd(), "data");@@ -47,7 +16,7 @@ const dbPath = process.env.DATABASE_PATH || defaultDbPath;if (!process.env.DATABASE_PATH) {fs.mkdirSync(defaultDataDir, { recursive: true });}-dbLog("Using database at", dbPath);+logger.info("Using database at", dbPath);const db = new Database(dbPath);// Check if servers table exists@@ -59,7 +28,7 @@ const tableExists = db// If not existing, create with all required columnsif (!tableExists) {- dbLog("Creating new database tables with updated schema");+ logger.info("Creating new database tables with updated schema");db.exec(`CREATE TABLE servers (id TEXT PRIMARY KEY,@@ -90,13 +59,13 @@ if (!tableExists) {try {const notesColumns = db.prepare("PRAGMA table_info(notes)").all();if (!notesColumns.some((col) => col.name === "updated_at")) {- dbLog('Schema migration: Adding "updated_at" column to "notes" table.');+ logger.info('Schema migration: Adding "updated_at" column to "notes" table.');db.prepare("ALTER TABLE notes ADD COLUMN updated_at DATETIME").run();}} catch (err) {// This can happen if the table doesn't exist yet on first run, which is fine.if (!err.message.includes("no such table: notes")) {- dbLog("Error during notes table schema check:", err.message);+ logger.info("Error during notes table schema check:", err.message);}}@@ -116,7 +85,7 @@ if (!tableExists) {// Add updated_at to notes table if it doesn't existconst notesColumns = db.prepare("PRAGMA table_info(notes)").all();if (!notesColumns.some((col) => col.name === "updated_at")) {- dbLog('Schema migration: Adding "updated_at" column to "notes" table.');+ logger.info('Schema migration: Adding "updated_at" column to "notes" table.');db.prepare("ALTER TABLE notes ADD COLUMN updated_at DATETIME").run();}@@ -124,7 +93,7 @@ if (!tableExists) {const columnNames = columns.map((col) => col.name);if (!columnNames.includes("type")) {- dbLog(+ logger.info("Migrating database: Table needs major restructuring (missing type column)");const tempTableExists = db@@ -133,7 +102,7 @@ if (!tableExists) {).get();if (tempTableExists) {- dbLog("Dropping existing temporary table servers_new");+ logger.debug("Dropping existing temporary table servers_new");db.exec(`DROP TABLE servers_new;`);}const existingServers = db.prepare("SELECT * FROM servers").all();@@ -184,24 +153,24 @@ if (!tableExists) {DROP TABLE servers;ALTER TABLE servers_new RENAME TO servers;`);- dbLog(+ logger.info('Database schema migration for "type" column completed successfully');} else {if (!columnNames.includes("platform")) {- dbLog("Migrating database: Adding platform column to servers table");+ logger.info("Migrating database: Adding platform column to servers table");db.prepare("ALTER TABLE servers ADD COLUMN platform TEXT DEFAULT 'standard'").run();}if (!columnNames.includes("platform_config")) {- dbLog(+ logger.info("Migrating database: Adding platform_config column to servers table");db.prepare("ALTER TABLE servers ADD COLUMN platform_config TEXT").run();}if (!columnNames.includes("platform_type")) {- dbLog(+ logger.info("Migrating database: Adding platform_type column to servers table");db.prepare(@@ -210,19 +179,23 @@ if (!tableExists) {}}} catch (migrationError) {- dbError(+ logger.error("FATAL: Database schema migration failed:",- migrationError.message,- migrationError.stack || ""+ migrationError.message);+ logger.debug("Stack trace:", migrationError.stack || "");// If migration fails, server may not be able to run.}}/**- * Ensures a local server entry exists in the database and its URL/platform_type are appropriate.- * @param {number} [port=3000] - The port to use in the local server URL.- * @param {boolean} [appDebugEnabled=false] - Whether application-level debug is enabled.+ * Ensures that a local server record with the correct URL, type, and platform_type exists in the database.+ *+ * If the local server entry does not exist, it is created with the specified port and default platform type. If it exists but its URL, type, or platform_type are incorrect, the entry is updated accordingly.+ *+ * @param {number} [port=3000] - The port to use for the local server's URL.+ * @param {boolean} [appDebugEnabled=false] - Enables debug logging if set to true.+ * @returns {boolean} True if the local server entry exists or was successfully created/updated; false if an error occurred or the schema is incomplete.*/function ensureLocalServer(port = 3000, appDebugEnabled = false) {try {@@ -233,7 +206,7 @@ function ensureLocalServer(port = 3000, appDebugEnabled = false) {!columnNames.includes("type") ||!columnNames.includes("platform_type")) {- dbWarn(+ logger.warn('Cannot ensure local server: "servers" table schema not fully migrated (missing "type" or "platform_type" column).');return false;@@ -246,7 +219,7 @@ function ensureLocalServer(port = 3000, appDebugEnabled = false) {const targetPlatformType = "auto";if (!localServer) {- dbLog(+ logger.info(`Adding local server to database. ID: local, URL: ${targetUrl}, Platform Type: ${targetPlatformType}`);db.prepare(@@ -264,13 +237,13 @@ function ensureLocalServer(port = 3000, appDebugEnabled = false) {updateClauses.push("url = ?");updateValues.push(targetUrl);needsUpdate = true;- dbLog(`Local server URL will be updated to ${targetUrl}.`);+ logger.info(`Local server URL will be updated to ${targetUrl}.`);}if (localServer.platform_type !== targetPlatformType) {updateClauses.push("platform_type = ?");updateValues.push(targetPlatformType);needsUpdate = true;- dbLog(+ logger.info(`Local server platform_type will be reset to '${targetPlatformType}' for auto-detection.`);}@@ -278,7 +251,7 @@ function ensureLocalServer(port = 3000, appDebugEnabled = false) {updateClauses.push("type = ?");updateValues.push("local");needsUpdate = true;- dbLog(`Local server type will be corrected to 'local'.`);+ logger.info(`Local server type will be corrected to 'local'.`);}if (needsUpdate) {@@ -286,27 +259,30 @@ function ensureLocalServer(port = 3000, appDebugEnabled = false) {db.prepare(`UPDATE servers SET ${updateClauses.join(", ")} WHERE id = ?`).run(...updateValues);- dbLog("Local server entry updated.");+ logger.info("Local server entry updated.");} else {- dbDebug(appDebugEnabled, "Local server entry already up-to-date.");+ if (appDebugEnabled) {+ logger.debug("Local server entry already up-to-date.");+ }}}return true;} catch (e) {- dbError("Error ensuring local server exists:", e.message, e.stack || "");+ logger.error("Error ensuring local server exists:", e.message);+ logger.debug("Stack trace:", e.stack || "");return false;}}/**- * Updates the platform_type for the local server.- * @param {string} platformType The new platform type (e.g., 'docker', 'truenas', 'system').- * @param {boolean} [appDebugEnabled=false] - Whether application-level debug is enabled.+ * Updates the `platform_type` field of the local server record in the database.+ * @param {string} platformType - The new platform type to set for the local server (e.g., 'docker', 'truenas', 'system').+ * @param {boolean} [appDebugEnabled=false] - Enables additional debug logging if true.*/function updateLocalServerPlatformType(platformType, appDebugEnabled = false) {try {if (!platformType || typeof platformType !== "string") {- dbWarn(+ logger.warn("Invalid platformType provided to updateLocalServerPlatformType. Received:",platformType);@@ -316,21 +292,22 @@ function updateLocalServerPlatformType(platformType, appDebugEnabled = false) {.prepare("UPDATE servers SET platform_type = ? WHERE id = 'local'").run(platformType);if (result.changes > 0) {- dbLog(+ logger.info(`Local server platform_type updated to '${platformType}' in database.`);} else {- dbDebug(- appDebugEnabled,- `updateLocalServerPlatformType called with '${platformType}', but no changes were made to the database (current value might be the same or 'local' server missing).`- );+ if (appDebugEnabled) {+ logger.debug(+ `updateLocalServerPlatformType called with '${platformType}', but no changes were made to the database (current value might be the same or 'local' server missing).`+ );+ }}} catch (e) {- dbError(+ logger.error("Failed to update local server platform_type:",- e.message,- e.stack || ""+ e.message);+ logger.debug("Stack trace:", e.stack || "");}}diff --git a/backend/index.js b/backend/index.jsindex f60e5fe..0cc3375 100644--- a/backend/index.js+++ b/backend/index.js@@ -1,7 +1,7 @@/*** PORTS TRACKER - BACKEND SERVER*- * Production-ready backend server for the Ports Tracker application.+ * Production-ready backend server for the portracker application.* Provides RESTful API endpoints for server management, port scanning,* and system monitoring across multiple deployment platforms.*/@@ -10,112 +10,526 @@ const express = require("express");const cors = require("cors");const db = require("./db");const { createCollector, detectCollector } = require("./collectors");+const { Logger } = require("./lib/logger");const path = require("path");const net = require("net");const http = require("http");const https = require("https");-// const fetch = require("node-fetch");+const fs = require("fs");+const os = require("os");++// Initialize logger for this component+const logger = new Logger("Server", { debug: process.env.DEBUG === 'true' });const PING_TIMEOUT = 2000;-async function testProtocol(scheme, host_ip, port, path = "/") {- const client = scheme === "https" ? https : http;- const options = {- hostname: host_ip,- port,- path,- timeout: PING_TIMEOUT,- family: 4,- };- if (scheme === "https") options.rejectUnauthorized = false;+// Rate limiting for ping debug logs to prevent spam+const pingDebugStats = {+ count: 0,+ startTime: Date.now(),+ lastSummaryTime: Date.now()+};++/**+ * Logs ping debug messages with rate limiting to reduce log spam, emitting summaries every 30 seconds or when forced.+ * @param {string} message - The debug message to log.+ * @param {boolean} [force=false] - If true, logs the message regardless of rate limits.+ */+function logPingDebug(message, force = false) {+ pingDebugStats.count++;+ const now = Date.now();++ // Log first few pings, then summary every 30 seconds+ if (pingDebugStats.count <= 5 || force || (now - pingDebugStats.lastSummaryTime) > 30000) {+ logger.debug(message);++ if ((now - pingDebugStats.lastSummaryTime) > 30000) {+ const elapsed = (now - pingDebugStats.startTime) / 1000;+ logger.debug(`[PING SUMMARY] ${pingDebugStats.count} pings processed in ${elapsed.toFixed(1)}s`);+ pingDebugStats.lastSummaryTime = now;+ }+ }+}++const WELL_KNOWN_PORTS = {+ 22: { name: 'SSH', type: 'system', description: 'Secure Shell (SSH)' },+ 23: { name: 'Telnet', type: 'system', description: 'Telnet protocol' },+ 25: { name: 'SMTP', type: 'system', description: 'Simple Mail Transfer Protocol (SMTP)' },+ 53: { name: 'DNS', type: 'system', description: 'Domain Name System (DNS)' },+ 80: { name: 'HTTP', type: 'web', description: 'Hypertext Transfer Protocol (HTTP)' },+ 110: { name: 'POP3', type: 'system', description: 'Post Office Protocol version 3 (POP3)' },+ 143: { name: 'IMAP', type: 'system', description: 'Internet Message Access Protocol (IMAP)' },+ 443: { name: 'HTTPS', type: 'web', description: 'HTTP Secure (HTTPS)' },+ 993: { name: 'IMAPS', type: 'system', description: 'IMAP over SSL' },+ 995: { name: 'POP3S', type: 'system', description: 'POP3 over SSL' },+ 1433: { name: 'SQL Server', type: 'database', description: 'Microsoft SQL Server database' },+ 3306: { name: 'MySQL', type: 'database', description: 'MySQL database' },+ 5432: { name: 'PostgreSQL', type: 'database', description: 'PostgreSQL database' },+ 6379: { name: 'Redis', type: 'database', description: 'Redis in-memory database' },+ 8080: { name: 'HTTP Alt', type: 'web', description: 'HTTP alternative port' },+ 8443: { name: 'HTTPS Alt', type: 'web', description: 'HTTPS alternative port' },+ 9000: { name: 'Management', type: 'web', description: 'Common management interface port' },+};++/**+ * Determines the service type and metadata for a given port and optional owner string.+ * @param {number|string} port - The port number to classify.+ * @param {string} [owner] - Optional process or service owner name for heuristic detection.+ * @return {Object} An object containing the service name, type, and description.+ */+function detectServiceType(port, owner) {+ const portNum = parseInt(port, 10);++ if (WELL_KNOWN_PORTS[portNum]) {+ return WELL_KNOWN_PORTS[portNum];+ }++ if (owner && typeof owner === 'string') {+ const ownerLower = owner.toLowerCase();++ if (ownerLower.includes('ssh') || ownerLower.includes('sshd')) {+ return { name: 'SSH', type: 'system', description: 'SSH service' };+ }+ if (ownerLower.includes('nginx') || ownerLower.includes('apache') || ownerLower.includes('httpd')) {+ return { name: 'Web Server', type: 'web', description: 'Web server' };+ }+ if (ownerLower.includes('mysql') || ownerLower.includes('postgres') || ownerLower.includes('redis')) {+ return { name: 'Database', type: 'database', description: 'Database service' };+ }+ }++ // Enhanced port range detection for web services+ if (portNum === 80 || portNum === 443 || portNum === 8080 || portNum === 8443 ||+ (portNum >= 3000 && portNum <= 3999) || // Common dev ports+ (portNum >= 4000 && portNum <= 4999) || // Common app ports+ (portNum >= 8000 && portNum <= 8999) || // Common web alt ports+ (portNum >= 9000 && portNum <= 9999)) { // Management/admin ports+ return { name: 'Web Service', type: 'web', description: 'Web service' };+ }++ if (portNum < 1024) {+ return { name: 'System Service', type: 'system', description: 'System service' };+ }++ return { name: 'Service', type: 'service', description: 'Application service' };+}+/**+ * Determines the Docker host IP address for the current environment.+ *+ * Returns the appropriate host IP for Docker containers, handling Docker Desktop, macOS, Windows, and Linux environments. Attempts to extract the gateway IP from `/proc/net/route` on Linux systems; falls back to `172.17.0.1` if detection fails.+ * @return {string} The Docker host IP address.+ */+function getDockerHostIP() {+ const platform = os.platform();++ if (platform === 'darwin' || platform === 'win32') {+ return "host.docker.internal";+ }++ if (isDockerDesktopEnvironment()) {+ return "host.docker.internal";+ }+try {- const headRes = await new Promise((resolve, reject) => {- const req = client.request({ ...options, method: "HEAD" }, (res) => {- res.resume();- resolve(res);- });- req.on("timeout", () => {- req.destroy();- reject(new Error("timeout"));+ if (fs.existsSync('/proc/net/route')) {+ const routes = fs.readFileSync('/proc/net/route', 'utf8');+ const lines = routes.split('\n');+ for (const line of lines) {+ const fields = line.split('\t');+ if (fields[1] === '00000000' && fields[7] === '00000000') {+ const gatewayHex = fields[2];+ const gateway = [+ parseInt(gatewayHex.substr(6, 2), 16),+ parseInt(gatewayHex.substr(4, 2), 16),+ parseInt(gatewayHex.substr(2, 2), 16),+ parseInt(gatewayHex.substr(0, 2), 16)+ ].join('.');+ return gateway;+ }+ }+ }+ } catch (err) {+ logger.warn('Failed to detect Docker host IP from /proc/net/route:', err.message);+ }++ return "172.17.0.1";+}++/**+ * Determines if the current environment is Docker Desktop.+ * @return {boolean} True if running inside Docker Desktop, otherwise false.+ */+function isDockerDesktopEnvironment() {+ try {+ if (process.env.DOCKER_DESKTOP === 'true') {+ return true;+ }++ if (fs.existsSync('/proc/version')) {+ const version = fs.readFileSync('/proc/version', 'utf8');+ if (version.includes('linuxkit') || version.includes('docker-desktop')) {+ return true;+ }+ }++ if (fs.existsSync('/proc/net/route')) {+ const routes = fs.readFileSync('/proc/net/route', 'utf8');+ const gatewayLines = routes.split('\n').filter(line => {+ const fields = line.split('\t');+ return fields[1] === '00000000';});- req.on("error", reject);- req.end();- });- if (headRes.statusCode >= 200 && headRes.statusCode < 300)- return { success: true, statusCode: headRes.statusCode };- if (- headRes.statusCode >= 300 &&- headRes.statusCode < 400 &&- headRes.headers.location- )- return {- success: true,- statusCode: headRes.statusCode,- redirected: true,- };- } catch (headError) {- if (debug || (headError && headError.message !== "timeout")) {- console.log(- `[Server] DEBUG: testProtocol HEAD ${scheme}://${host_ip}:${port}${path} failed: ${headError.message}`- );++ for (const line of gatewayLines) {+ const fields = line.split('\t');+ const gatewayHex = fields[2];+ const gateway = [+ parseInt(gatewayHex.substr(6, 2), 16),+ parseInt(gatewayHex.substr(4, 2), 16),+ parseInt(gatewayHex.substr(2, 2), 16),+ parseInt(gatewayHex.substr(0, 2), 16)+ ].join('.');++ if (gateway.startsWith('192.168.65.') || gateway.startsWith('172.19.') || gateway.startsWith('172.20.')) {+ return true;+ }+ }}++ return false;+ } catch (err) {+ return false;}+}+/**+ * Tests the reachability of a service over HTTP or HTTPS by sending HEAD and GET requests.+ *+ * Attempts a HEAD request first; if unsuccessful, falls back to a GET request. Measures response time, captures status codes, and detects single-page application (SPA) patterns in 404 HTML responses. Returns detailed information about reachability, protocol, method, response time, and SPA detection.+ *+ * @param {string} scheme - The protocol to use ("http" or "https").+ * @param {string} host_ip - The target host IP address.+ * @param {number} port - The target port number.+ * @param {string} [path="/"] - The request path.+ * @param {boolean} [isDebugEnabled=false] - Enables debug logging if true.+ * @return {Promise<Object>} An object indicating reachability, status code, protocol, method, response time, and SPA detection if applicable.+ */+async function testProtocol(scheme, host_ip, port, path = "/", isDebugEnabled = false) {+ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), PING_TIMEOUT);++ const url = `${scheme}://${host_ip}:${port}${path}`;+try {- const getRes = await new Promise((resolve, reject) => {- const req = client.request({ ...options, method: "GET" }, (res) => {- res.resume();- resolve(res);+ const startTime = Date.now();++ try {+ const headResponse = await fetch(url, {+ method: 'HEAD',+ signal: controller.signal,+ headers: {+ 'User-Agent': 'PortTracker/1.0',+ },});- req.on("timeout", () => {- req.destroy();- reject(new Error("timeout"));++ const duration = Date.now() - startTime;++ if (isDebugEnabled) {+ logPingDebug(+ `testProtocol HEAD ${url} -> ${headResponse.status} (${duration}ms)`+ );+ }++ if (headResponse.status < 500 && headResponse.status !== 404) {+ clearTimeout(timeout);+ return {+ reachable: true,+ statusCode: headResponse.status,+ protocol: scheme,+ method: 'HEAD',+ responseTime: duration,+ };+ }+ } catch (headError) {+ if (isDebugEnabled) {+ logPingDebug(+ `testProtocol HEAD ${url} failed: ${headError.message}`+ );+ }+ }++ try {+ const getStartTime = Date.now();+ const getResponse = await fetch(url, {+ method: 'GET',+ signal: controller.signal,+ headers: {+ 'User-Agent': 'PortTracker/1.0',+ },+ redirect: 'manual'});- req.on("error", reject);- req.end();- });- if (getRes.statusCode >= 200 && getRes.statusCode < 300)- return { success: true, statusCode: getRes.statusCode };- if (- getRes.statusCode >= 300 &&- getRes.statusCode < 400 &&- getRes.headers.location- )- return { success: true, statusCode: getRes.statusCode, redirected: true };- return { success: false, statusCode: getRes.statusCode };- } catch (getError) {- if (debug || (getError && getError.message !== "timeout")) {- console.log(- `[Server] DEBUG: testProtocol GET ${scheme}://${host_ip}:${port}${path} failed: ${getError.message}`- );++ const getDuration = Date.now() - getStartTime;++ if (isDebugEnabled) {+ logPingDebug(+ `testProtocol GET ${url} -> ${getResponse.status} (${getDuration}ms)`+ );+ }++ if (getResponse.status < 500) {+ let isSPA = false;++ if (getResponse.status === 404) {+ try {+ const body = await getResponse.text();+ const contentType = getResponse.headers.get('content-type') || '';++ if (contentType.includes('text/html') && body.length > 100) {+ const hasDoctype = body.toLowerCase().includes('<!doctype html>') || body.toLowerCase().includes('<html');+ const hasScriptTags = body.toLowerCase().includes('<script');+ const hasMetaTags = body.toLowerCase().includes('<meta');+ const hasAppRoot = body.includes('id="root"') || body.includes('id="app"') || body.includes('id=\'root\'') || body.includes('id=\'app\'');++ isSPA = hasDoctype && hasScriptTags && (hasAppRoot || hasMetaTags);++ if (isDebugEnabled && isSPA) {+ logPingDebug(+ `testProtocol detected SPA pattern in 404 response for ${url}`+ );+ }+ }+ } catch (bodyError) {+ if (isDebugEnabled) {+ logPingDebug(+ `testProtocol failed to read body for SPA detection: ${bodyError.message}`+ );+ }+ }+ }++ clearTimeout(timeout);+ return {+ reachable: true,+ statusCode: getResponse.status,+ protocol: scheme,+ method: 'GET',+ responseTime: getDuration,+ isSPA: isSPA+ };+ }+ } catch (getError) {+ if (isDebugEnabled) {+ logPingDebug(+ `testProtocol GET ${url} failed: ${getError.message}`+ );+ }}- return { success: false, reason: getError.message };++ clearTimeout(timeout);+ return { reachable: false, error: 'No successful response' };++ } catch (error) {+ clearTimeout(timeout);+ return { reachable: false, error: error.message };}}+/**+ * Determines the status and accessibility of a service based on its type and HTTP(S) response data.+ *+ * Evaluates the service type and the results of HTTP and HTTPS protocol checks to classify the service as accessible, listening, unreachable, or in error. Returns a status object with color coding, descriptive title, and protocol information when applicable.+ *+ * @param {Object} serviceInfo - Metadata about the service, including type, name, and description.+ * @param {Object} httpsResponse - Result of the HTTPS protocol check, including reachability and status code.+ * @param {Object} httpResponse - Result of the HTTP protocol check, including reachability and status code.+ * @return {Object} An object describing the service's status, color, title, description, and protocol if relevant.+ */+function determineServiceStatus(serviceInfo, httpsResponse, httpResponse) {+ const serviceType = serviceInfo.type;++ if (serviceType === 'system') {+ return {+ status: 'system',+ color: 'gray',+ title: `${serviceInfo.name} - System service`,+ description: serviceInfo.description+ };+ }++ let workingResponse = null;++ if (httpsResponse.reachable && httpsResponse.statusCode >= 200 && httpsResponse.statusCode < 300) {+ workingResponse = httpsResponse;+ } else if (httpResponse.reachable && httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {+ workingResponse = httpResponse;+ } else if (httpsResponse.reachable) {+ workingResponse = httpsResponse;+ } else if (httpResponse.reachable) {+ workingResponse = httpResponse;+ }++ if (!workingResponse) {+ return {+ status: 'unreachable',+ color: 'red',+ title: `${serviceInfo.name} - Service not reachable`,+ description: serviceInfo.description+ };+ }++ if (serviceType === 'web') {+ const statusCode = workingResponse.statusCode;++ if (statusCode >= 200 && statusCode < 400) {+ return {+ status: 'accessible',+ color: 'green',+ title: `${serviceInfo.name} - Web service accessible`,+ description: serviceInfo.description,+ protocol: workingResponse.protocol+ };+ }++ if (statusCode === 401) {+ return {+ status: 'accessible',+ color: 'green',+ title: `${serviceInfo.name} - Web accessible (auth)`,+ description: serviceInfo.description,+ protocol: workingResponse.protocol+ };+ }++ if (statusCode === 403) {+ return {+ status: 'listening',+ color: 'yellow',+ title: `${serviceInfo.name} - Listening (Forbidden)`,+ description: serviceInfo.description,+ protocol: workingResponse.protocol+ };+ }++ if (statusCode === 405 && workingResponse.method === 'HEAD') {+ return {+ status: 'accessible',+ color: 'green',+ title: `${serviceInfo.name} - Web accessible (GET)`,+ description: serviceInfo.description,+ protocol: workingResponse.protocol+ };+ }++ if (statusCode === 404) {+ if (workingResponse.isSPA) {+ return {+ status: 'accessible',+ color: 'green',+ title: `${serviceInfo.name} - Web accessible`,+ description: serviceInfo.description,+ protocol: workingResponse.protocol+ };+ } else {+ return {+ status: 'listening',+ color: 'yellow',+ title: `${serviceInfo.name} - Listening (no web UI)`,+ description: serviceInfo.description,+ protocol: workingResponse.protocol+ };+ }+ }++ if (statusCode >= 400 && statusCode < 500) {+ return {+ status: 'accessible',+ color: 'green',+ title: `${serviceInfo.name} - Web accessible (HTTP ${statusCode})`,+ description: serviceInfo.description,+ protocol: workingResponse.protocol+ };+ }++ if (statusCode >= 500) {+ return {+ status: 'error',+ color: 'red',+ title: `${serviceInfo.name} - HTTP ${statusCode} error`,+ description: serviceInfo.description,+ protocol: workingResponse.protocol+ };+ }+ }++ if (serviceType === 'database' || serviceType === 'service') {+ const statusCode = workingResponse.statusCode;++ if (statusCode === 401) {+ return {+ status: 'accessible',+ color: 'green',+ title: `${serviceInfo.name} - HTTP accessible (auth)`,+ description: serviceInfo.description,+ protocol: workingResponse.protocol+ };+ }++ if (statusCode === 403) {+ return {+ status: 'listening',+ color: 'yellow',+ title: `${serviceInfo.name} - Listening (Forbidden)`,+ description: serviceInfo.description,+ protocol: workingResponse.protocol+ };+ }++ if (statusCode < 500) {+ return {+ status: 'accessible',+ color: 'green',+ title: `${serviceInfo.name} - HTTP accessible`,+ description: serviceInfo.description,+ protocol: workingResponse.protocol+ };+ } else {+ return {+ status: 'listening',+ color: 'yellow',+ title: `${serviceInfo.name} - Service listening (not HTTP)`,+ description: serviceInfo.description+ };+ }+ }++ return {+ status: 'listening',+ color: 'yellow',+ title: `${serviceInfo.name} - Service listening`,+ description: serviceInfo.description+ };+}+// Verify database schema before starting the servertry {const columns = db.prepare("PRAGMA table_info(servers)").all();const columnNames = columns.map((col) => col.name);if (!columnNames.includes("type")) {- console.warn(- '[Server] WARN: Database schema migration may be needed. The "servers" table "type" column is missing.'+ logger.warn(+ 'Database schema migration may be needed. The "servers" table "type" column is missing.');- console.warn(- "[Server] WARN: This might affect functionality. Consider checking database setup or migrations."+ logger.warn(+ "This might affect functionality. Consider checking database setup or migrations.");} else {- console.log("[Server] INFO: Database schema verification successful.");+ logger.info("Database schema verification successful.");}db.ensureLocalServer(process.env.PORT || 3000);} catch (error) {- console.error(- "[Server] FATAL: Database verification failed:",- error.message,- error.stack || ""- );+ logger.fatal("Database verification failed:", error.message);+ logger.debug("Stack trace:", error.stack || "");}const app = express();@@ -128,10 +542,12 @@ let debug = false;* Get all ports from local system using collector framework.*/app.get("/api/ports", async (req, res) => {- debug = req.query.debug === "true";- if (debug) {- console.log(`[Server] DEBUG: GET /api/ports called with debug=${debug}`);- }+ const debug = req.query.debug === "true";+ // Enable debug for this request if specified+ if (debug) logger.setDebugEnabled(true);++ logger.debug(`GET /api/ports called with debug=${debug}`);+try {const entries = [];const dockerCollector = createCollector("docker", { debug });@@ -169,14 +585,14 @@ app.get("/api/ports", async (req, res) => {})));} catch (error) {- console.error(- "[Server] ERROR: Error in GET /api/ports:",- error.message,- error.stack || ""- );+ logger.error("Error in GET /api/ports:", error.message);+ logger.debug("Stack trace:", error.stack || "");res.status(500).json({ error: "Failed to scan ports", details: error.message });+ } finally {++ if (debug) logger.setDebugEnabled(process.env.DEBUG === 'true');}});@@ -184,12 +600,12 @@ app.get("/api/ports", async (req, res) => {* New peer-based endpoint to replace remote API connectivity*/app.get("/api/all-ports", async (req, res) => {- debug = req.query.debug === "true";- if (debug) {- console.log(- `[Server] DEBUG: GET /api/all-ports called with debug=${debug}`- );- }+ const debug = req.query.debug === "true";+ // Enable debug for this request if specified+ if (debug) logger.setDebugEnabled(true);++ logger.debug(`GET /api/all-ports called with debug=${debug}`);+try {const servers = db.prepare("SELECT * FROM servers").all();@@ -210,10 +626,7 @@ app.get("/api/all-ports", async (req, res) => {localServerResult.data = localPorts;localServerResult.ok = true;} catch (localError) {- console.error(- "[Server] ERROR: Failed to get local ports for /api/all-ports:",- localError.message- );+ logger.error("Failed to get local ports for /api/all-ports:", localError.message);localServerResult.ok = false;localServerResult.error = `Failed to collect local ports: ${localError.message}`;}@@ -221,52 +634,39 @@ app.get("/api/all-ports", async (req, res) => {res.json(results);} catch (error) {- console.error(- "[Server] ERROR: Error in GET /api/all-ports:",- error.message,- error.stack || ""- );+ logger.error("Error in GET /api/all-ports:", error.message);+ logger.debug("Stack trace:", error.stack || "");res.status(500).json({ error: "Failed to process all ports", details: error.message });+ } finally {++ if (debug) logger.setDebugEnabled(process.env.DEBUG === 'true');}});/**- * Get local ports using the best available collector+ * Collects and returns the list of open ports on the local system using the most suitable platform-specific collector.+ * @param {Object} [options] - Optional settings for port collection.+ * @param {boolean} [options.debug] - Enables debug logging if true.+ * @return {Promise<Array>} Resolves with an array of port information objects.*/async function getLocalPortsUsingCollectors(options = {}) {- const currentDebug = options.debug || debug;+ const currentDebug = options.debug || false;try {- if (currentDebug) {- console.log(- "[Server] DEBUG: [getLocalPortsUsingCollectors] Starting port collection..."- );- }+ logger.debug("[getLocalPortsUsingCollectors] Starting port collection...");const collector = await detectCollector({ debug: currentDebug });- if (currentDebug) {- console.log(- `[Server] DEBUG: [getLocalPortsUsingCollectors] Detected collector: ${collector?.platform}`- );- }+ logger.debug(`[getLocalPortsUsingCollectors] Detected collector: ${collector?.platform}`);const ports = await collector.getPorts();- if (currentDebug) {- console.log(- `[Server] DEBUG: [getLocalPortsUsingCollectors] Collected ${- ports?.length || 0- } ports.`- );- }+ logger.debug(`[getLocalPortsUsingCollectors] Collected ${ports?.length || 0} ports.`);+return ports;} catch (error) {- console.error(- "[Server] ERROR: [getLocalPortsUsingCollectors] Primary collection attempt failed:",- error.message,- error.stack || ""- );+ logger.error("[getLocalPortsUsingCollectors] Primary collection attempt failed:", error.message);+ logger.debug("Stack trace:", error.stack || "");throw error;}}@@ -276,12 +676,12 @@ async function getLocalPortsUsingCollectors(options = {}) {*/app.get("/api/servers/:id/scan", async (req, res) => {const serverId = req.params.id;- const currentDebug = req.query.debug === "true" || debug;- if (currentDebug) {- console.log(- `[Server] DEBUG: GET /api/servers/${serverId}/scan called with debug=${currentDebug}`- );- }+ const currentDebug = req.query.debug === "true";++ // Enable debug for this request if specified+ if (currentDebug) logger.setDebugEnabled(true);++ logger.debug(`GET /api/servers/${serverId}/scan called with debug=${currentDebug}`);try {const server = db@@ -289,9 +689,7 @@ app.get("/api/servers/:id/scan", async (req, res) => {.get(serverId);if (!server) {- console.warn(- `[Server] WARN: [GET /api/servers/${serverId}/scan] Server not found.`- );+ logger.warn(`[GET /api/servers/${serverId}/scan] Server not found.`);return res.status(404).json({ error: "Server not found" });}@@ -299,11 +697,7 @@ app.get("/api/servers/:id/scan", async (req, res) => {const platformType = server.platform_type || "auto";let collector;- if (currentDebug) {- console.log(- `[Server] DEBUG: [GET /api/servers/local/scan] Local server platform_type: ${platformType}`- );- }+ logger.debug(`[GET /api/servers/local/scan] Local server platform_type: ${platformType}`);if (platformType === "auto") {collector = await detectCollector({ debug: currentDebug });@@ -341,8 +735,8 @@ app.get("/api/servers/:id/scan", async (req, res) => {) {db.updateLocalServerPlatformType(collectData.platform);}- console.log(- `[Server] INFO: [GET /api/servers/local/scan] Successfully scanned. Collector: ${+ logger.debug(+ `Local scan complete. Collector: ${collector?.platform}, Apps: ${collectData.apps?.length || 0}, Ports: ${collectData.ports?.length || 0@@ -352,18 +746,11 @@ app.get("/api/servers/:id/scan", async (req, res) => {}if (server.type === "peer" && server.url) {- if (currentDebug) {- console.log(- `[Server] DEBUG: [GET /api/servers/${serverId}/scan] Attempting to scan remote peer at URL: ${server.url}`- );- }+ logger.debug(`[GET /api/servers/${serverId}/scan] Attempting to scan remote peer at URL: ${server.url}`);+try {const peerScanUrl = new URL("/api/servers/local/scan", server.url).href;- if (currentDebug) {- console.log(- `[Server] DEBUG: [GET /api/servers/${serverId}/scan] Fetching from peer URL: ${peerScanUrl}`- );- }+ logger.debug(`[GET /api/servers/${serverId}/scan] Fetching from peer URL: ${peerScanUrl}`);const controller = new AbortController();const timeoutId = setTimeout(() => controller.abort(), 15000);@@ -381,8 +768,8 @@ app.get("/api/servers/:id/scan", async (req, res) => {} catch (e) {/* ignore */}- console.warn(- `[Server] WARN: [GET /api/servers/${serverId}/scan] Peer server at ${server.url} responded with status ${peerResponse.status}. Body: ${errorBody}`+ logger.warn(+ `[GET /api/servers/${serverId}/scan] Peer server at ${server.url} responded with status ${peerResponse.status}. Body: ${errorBody}`);return res.status(peerResponse.status).json({error: `Peer server scan failed with status ${peerResponse.status}`,@@ -393,20 +780,13 @@ app.get("/api/servers/:id/scan", async (req, res) => {}const peerScanData = await peerResponse.json();- if (currentDebug) {- console.log(- `[Server] DEBUG: [GET /api/servers/${serverId}/scan] Successfully received scan data from peer ${serverId}`- );- }- console.log(- `[Server] INFO: [GET /api/servers/${serverId}/scan] Successfully scanned remote peer. Peer: ${server.label} (${serverId})`- );+ logger.debug(`Peer scan complete: ${server.label} (${serverId})`);return res.json(peerScanData);} catch (fetchError) {clearTimeout(timeoutId);if (fetchError.name === 'AbortError') {- console.error(- `[Server] ERROR: [GET /api/servers/${serverId}/scan] Timeout after 15s communicating with peer ${server.label} at ${server.url}`+ logger.error(+ `[GET /api/servers/${serverId}/scan] Timeout after 15s communicating with peer ${server.label} at ${server.url}`);return res.status(408).json({error: "Request timeout - peer server took too long to respond",@@ -418,9 +798,8 @@ app.get("/api/servers/:id/scan", async (req, res) => {throw fetchError;}} catch (fetchError) {- console.error(- `[Server] ERROR: [GET /api/servers/${serverId}/scan] Failed to fetch scan data from peer ${server.label} at ${server.url}:`,- fetchError.message+ logger.error(+ `[GET /api/servers/${serverId}/scan] Failed to fetch scan data from peer ${server.label} at ${server.url}: ${fetchError.message}`);return res.status(502).json({error: "Failed to communicate with peer server",@@ -430,8 +809,8 @@ app.get("/api/servers/:id/scan", async (req, res) => {});}} else {- console.warn(- `[Server] WARN: [GET /api/servers/${serverId}/scan] Cannot scan server: Not 'local' and not a valid 'peer' with a URL.`+ logger.warn(+ `[GET /api/servers/${serverId}/scan] Cannot scan server: Not 'local' and not a valid 'peer' with a URL.`);return res.status(501).json({error:@@ -440,14 +819,14 @@ app.get("/api/servers/:id/scan", async (req, res) => {});}} catch (error) {- console.error(- `[Server] ERROR: Error in GET /api/servers/${serverId}/scan:`,- error.message,- error.stack || ""- );+ logger.error(`Error in GET /api/servers/${serverId}/scan: ${error.message}`);+ logger.debug("Stack trace:", error.stack || "");res.status(500).json({ error: "Failed to scan server", details: error.message });+ } finally {++ if (currentDebug) logger.setDebugEnabled(process.env.DEBUG === 'true');}});@@ -544,6 +923,10 @@ function validateNoteInput(req, res, next) {next();}+/**+ * Middleware that validates the presence and format of the server ID parameter in the request.+ * Responds with a 400 error if the ID is missing or not a non-empty string.+ */function validateServerIdParam(req, res, next) {const serverId = req.params.id;if (@@ -564,22 +947,17 @@ function validateServerIdParam(req, res, next) {}app.get("/api/servers", (req, res) => {- console.log("[Server] INFO: Received GET /api/servers request");+ logger.debug("GET /api/servers");try {const stmt = db.prepare("SELECT id, label, url, parentId, type, unreachable, platform_type FROM servers");const servers = stmt.all();- console.log(- `[Server] INFO: Sending ${servers.length} servers in /api/servers response`- );+ logger.debug(`Returning ${servers.length} servers`);res.json(servers);} catch (error) {- console.error(- "[Server] ERROR: Failed to get servers:",- error.message,- error.stack || ""- );+ logger.error("Failed to get servers:", error.message);+ logger.debug("Stack trace:", error.stack || "");res.status(500).json({ error: "Failed to retrieve servers", details: error.message });@@ -620,9 +998,7 @@ app.post("/api/servers", validateServerInput, (req, res) => {platform_type,id);- console.log(- `[Server] INFO: Server updated successfully. ID: ${id}, Label: "${label}"`- );+ logger.info(`Server updated successfully. ID: ${id}, Label: "${label}"`);res.status(200).json({ message: "Server updated successfully", id });} else {db.prepare(@@ -636,17 +1012,12 @@ app.post("/api/servers", validateServerInput, (req, res) => {dbUnreachable,platform_type);- console.log(- `[Server] INFO: Server added successfully. ID: ${id}, Label: "${label}"`- );+ logger.info(`Server added successfully. ID: ${id}, Label: "${label}"`);res.status(201).json({ message: "Server added successfully", id });}} catch (error) {- console.error(- `[Server] ERROR: Database error in POST /api/servers (ID: ${id}):`,- error.message,- error.stack || ""- );+ logger.error(`Database error in POST /api/servers (ID: ${id}): ${error.message}`);+ logger.debug("Stack trace:", error.stack || "");if (error.message.includes("UNIQUE constraint failed")) {return res.status(409)@@ -656,10 +1027,8 @@ app.post("/api/servers", validateServerInput, (req, res) => {error.message.toLowerCase().includes("can only bind") ||error.message.toLowerCase().includes("datatype mismatch")) {- console.error(- `[Server] ERROR DETAIL: Possible data binding/type issue for server ID ${id}. Payload received: ${JSON.stringify(- req.body- )}`+ logger.error(+ `Possible data binding/type issue for server ID ${id}. Payload received: ${JSON.stringify(req.body)}`);return res.status(500)@@ -676,31 +1045,26 @@ app.post("/api/servers", validateServerInput, (req, res) => {app.delete("/api/servers/:id", validateServerIdParam, (req, res) => {const serverId = req.params.id;- const currentDebug = req.query.debug === "true" || debug;+ const currentDebug = req.query.debug === "true";++ // Enable debug for this request if specified+ if (currentDebug) logger.setDebugEnabled(true);- if (currentDebug) {- console.log(- `[Server] DEBUG: [DELETE /api/servers/${serverId}] Request received.`- );- }+ logger.debug(`[DELETE /api/servers/${serverId}] Request received.`);try {const server = db.prepare("SELECT id, label FROM servers WHERE id = ?").get(serverId);if (!server) {- console.warn(- `[Server] WARN: [DELETE /api/servers/${serverId}] Attempt to delete non-existent server.`- );+ logger.warn(`[DELETE /api/servers/${serverId}] Attempt to delete non-existent server.`);return res.status(404).json({ error: "Server not found", server_id: serverId });}if (serverId === "local") {- console.warn(- `[Server] WARN: [DELETE /api/servers/${serverId}] Attempt to delete 'local' server.`- );+ logger.warn(`[DELETE /api/servers/${serverId}] Attempt to delete 'local' server.`);return res.status(400).json({ error: "Cannot delete local server", server_id: serverId });@@ -716,20 +1080,15 @@ app.delete("/api/servers/:id", validateServerIdParam, (req, res) => {});deleteTransaction();- console.log(- `[Server] INFO: Server deleted successfully. ID: ${serverId}, Label: "${server.label}"`- );+ logger.info(`Server deleted successfully. ID: ${serverId}, Label: "${server.label}"`);res.json({success: true,message: `Server '${server.label}' (ID: ${serverId}) deleted successfully`,});} catch (err) {if (err.message.includes("FOREIGN KEY constraint failed")) {- console.error(- `[Server] ERROR: FOREIGN KEY constraint failed during DELETE /api/servers/${serverId}:`,- err.message,- err.stack || ""- );+ logger.error(`FOREIGN KEY constraint failed during DELETE /api/servers/${serverId}: ${err.message}`);+ logger.debug("Stack trace:", err.stack || "");return res.status(409).json({error: "Conflict deleting server",details:@@ -737,11 +1096,8 @@ app.delete("/api/servers/:id", validateServerIdParam, (req, res) => {rawError: err.message,});}- console.error(- `[Server] ERROR: Database error in DELETE /api/servers/${serverId}:`,- err.message,- err.stack || ""- );+ logger.error(`Database error in DELETE /api/servers/${serverId}: ${err.message}`);+ logger.debug("Stack trace:", err.stack || "");res.status(500).json({@@ -749,19 +1105,21 @@ app.delete("/api/servers/:id", validateServerIdParam, (req, res) => {details: "Unable to delete server",rawError: err.message,});+ } finally {++ if (currentDebug) logger.setDebugEnabled(process.env.DEBUG === 'true');}});app.post("/api/notes", validateNoteInput, (req, res) => {const { server_id, host_ip, host_port, note } = req.body;- const currentDebug = req.query.debug === "true" || debug;+ const currentDebug = req.query.debug === "true";const noteTrimmed = note ? note.trim() : "";- if (currentDebug) {- console.log(- `[Server] DEBUG: POST /api/notes for ${server_id} ${host_ip}:${host_port}. Note: "${noteTrimmed}"`- );- }+ // Enable debug for this request if specified+ if (currentDebug) logger.setDebugEnabled(true);++ logger.debug(`POST /api/notes for ${server_id} ${host_ip}:${host_port}. Note: "${noteTrimmed}"`);try {const existing = db@@ -774,48 +1132,43 @@ app.post("/api/notes", validateNoteInput, (req, res) => {db.prepare("DELETE FROM notes WHERE server_id = ? AND host_ip = ? AND host_port = ?").run(server_id, host_ip, host_port);- console.log(- `[Server] INFO: Note deleted for ${server_id} ${host_ip}:${host_port}`- );+ logger.info(`Note deleted for ${server_id} ${host_ip}:${host_port}`);} else {db.prepare("UPDATE notes SET note = ?, updated_at = datetime('now') WHERE server_id = ? AND host_ip = ? AND host_port = ?").run(noteTrimmed, server_id, host_ip, host_port);- console.log(- `[Server] INFO: Note updated for ${server_id} ${host_ip}:${host_port}`- );+ logger.info(`Note updated for ${server_id} ${host_ip}:${host_port}`);}} else if (noteTrimmed !== "") {db.prepare("INSERT INTO notes (server_id, host_ip, host_port, note) VALUES (?, ?, ?, ?)").run(server_id, host_ip, host_port, noteTrimmed);- console.log(- `[Server] INFO: Note created for ${server_id} ${host_ip}:${host_port}`- );+ logger.info(`Note created for ${server_id} ${host_ip}:${host_port}`);}res.status(200).json({ success: true, message: "Note saved successfully" });} catch (err) {- console.error(- `[Server] ERROR: Database error in POST /api/notes:`,- err.message,- err.stack || ""- );+ logger.error(`Database error in POST /api/notes: ${err.message}`);+ logger.debug("Stack trace:", err.stack || "");res.status(500).json({error: "Database operation failed",details: "Unable to save note",});+ } finally {++ if (currentDebug) logger.setDebugEnabled(process.env.DEBUG === 'true');}});app.get("/api/notes", (req, res) => {const { server_id } = req.query;- const currentDebug = req.query.debug === "true" || debug;+ const currentDebug = req.query.debug === "true";- if (currentDebug) {- console.log(`[Server] DEBUG: GET /api/notes for server_id: ${server_id}`);- }+ // Enable debug for this request if specified+ if (currentDebug) logger.setDebugEnabled(true);++ logger.debug(`GET /api/notes for server_id: ${server_id}`);if (!server_id) {return res@@ -829,29 +1182,28 @@ app.get("/api/notes", (req, res) => {.all(server_id);res.json(notes);} catch (err) {- console.error(- `[Server] ERROR: Database error in GET /api/notes:`,- err.message,- err.stack || ""- );+ logger.error(`Database error in GET /api/notes: ${err.message}`);+ logger.debug("Stack trace:", err.stack || "");res.status(500).json({error: "Database operation failed",details: "Unable to retrieve notes",});+ } finally {++ if (currentDebug) logger.setDebugEnabled(process.env.DEBUG === 'true');}});app.post("/api/ignores", (req, res) => {const { server_id, host_ip, host_port, ignored } = req.body;- const currentDebug = req.query.debug === "true" || debug;+ const currentDebug = req.query.debug === "true";- if (currentDebug) {- console.log(- `[Server] DEBUG: POST /api/ignores for ${server_id} ${host_ip}:${host_port}. Ignored: ${ignored}`- );- }+ // Enable debug for this request if specified+ if (currentDebug) logger.setDebugEnabled(true);++ logger.debug(`POST /api/ignores for ${server_id} ${host_ip}:${host_port}. Ignored: ${ignored}`);if (!server_id ||@@ -878,53 +1230,44 @@ app.post("/api/ignores", (req, res) => {db.prepare("INSERT INTO ignores (server_id, host_ip, host_port) VALUES (?, ?, ?)").run(server_id, host_ip, host_port);- console.log(- `[Server] INFO: Port ignored for ${server_id} ${host_ip}:${host_port}`- );+ logger.info(`Port ignored for ${server_id} ${host_ip}:${host_port}`);} else {- if (currentDebug)- console.log(- `[Server] DEBUG: Port already ignored for ${server_id} ${host_ip}:${host_port}, no change.`- );+ logger.debug(`Port already ignored for ${server_id} ${host_ip}:${host_port}, no change.`);}} else {if (existing) {db.prepare("DELETE FROM ignores WHERE server_id = ? AND host_ip = ? AND host_port = ?").run(server_id, host_ip, host_port);- console.log(- `[Server] INFO: Port un-ignored for ${server_id} ${host_ip}:${host_port}`- );+ logger.info(`Port un-ignored for ${server_id} ${host_ip}:${host_port}`);} else {- if (currentDebug)- console.log(- `[Server] DEBUG: Port already not ignored for ${server_id} ${host_ip}:${host_port}, no change.`- );+ logger.debug(`Port already not ignored for ${server_id} ${host_ip}:${host_port}, no change.`);}}res.status(200).json({ success: true, message: "Ignore status updated" });} catch (err) {- console.error(- `[Server] ERROR: Database error in POST /api/ignores:`,- err.message,- err.stack || ""- );+ logger.error(`Database error in POST /api/ignores: ${err.message}`);+ logger.debug("Stack trace:", err.stack || "");res.status(500).json({error: "Database operation failed",details: "Unable to update ignore status",});+ } finally {++ if (currentDebug) logger.setDebugEnabled(process.env.DEBUG === 'true');}});app.get("/api/ignores", (req, res) => {const { server_id } = req.query;- const currentDebug = req.query.debug === "true" || debug;+ const currentDebug = req.query.debug === "true";- if (currentDebug) {- console.log(`[Server] DEBUG: GET /api/ignores for server_id: ${server_id}`);- }+ // Enable debug for this request if specified+ if (currentDebug) logger.setDebugEnabled(true);++ logger.debug(`GET /api/ignores for server_id: ${server_id}`);if (!server_id) {return res@@ -938,24 +1281,27 @@ app.get("/api/ignores", (req, res) => {.all(server_id);res.json(ignores.map((item) => ({ ...item, ignored: true })));} catch (err) {- console.error(- `[Server] ERROR: Database error in GET /api/ignores:`,- err.message,- err.stack || ""- );+ logger.error(`Database error in GET /api/ignores: ${err.message}`);+ logger.debug("Stack trace:", err.stack || "");res.status(500).json({error: "Database operation failed",details: "Unable to retrieve ignores",});+ } finally {++ if (currentDebug) logger.setDebugEnabled(process.env.DEBUG === 'true');}});app.get("/api/ping", async (req, res) => {- const { host_ip, host_port, target_server_url } = req.query;- const currentDebug = req.query.debug === "true" || debug;-+ const { host_ip, host_port, target_server_url, owner } = req.query;+ const currentDebug = req.query.debug === "true";++ // Enable debug for this request if specified+ if (currentDebug) logger.setDebugEnabled(true);+if (!host_ip || !host_port) {return res.status(400)@@ -965,10 +1311,26 @@ app.get("/api/ping", async (req, res) => {if (isNaN(portNum) || portNum <= 0 || portNum > 65535) {return res.status(400).json({ error: "Invalid host_port" });}++ const serviceInfo = detectServiceType(host_port, owner);++ if (serviceInfo.type === 'system') {+ return res.json({+ reachable: true,+ status: 'system',+ color: 'gray',+ title: serviceInfo.description,+ serviceType: serviceInfo.type,+ serviceName: serviceInfo.name+ });+ }let pingable_host_ip = host_ip;- const isBackendInDocker = process.env.RUNNING_IN_DOCKER === "true";-++ const isInDocker = process.env.RUNNING_IN_DOCKER === "true" ||+ fs.existsSync("/.dockerenv") ||+ fs.existsSync("/proc/self/cgroup") &&+ fs.readFileSync("/proc/self/cgroup", "utf8").includes("docker");if (target_server_url &&(host_ip === "0.0.0.0" ||@@ -979,99 +1341,72 @@ app.get("/api/ping", async (req, res) => {try {const peerUrlObj = new URL(target_server_url);pingable_host_ip = peerUrlObj.hostname;- if (currentDebug) {- console.log(- `[Server] DEBUG: [GET /api/ping] Remapping generic host_ip '${host_ip}' to peer host '${pingable_host_ip}' from target_server_url for port ${host_port}.`- );- }- } catch (e) {- console.error(- `[Server] ERROR: [GET /api/ping] Invalid target_server_url: ${target_server_url}`,- e.message+ logPingDebug(+ `Using peer server hostname '${pingable_host_ip}' for generic host_ip '${host_ip}' on port ${host_port}`);+ } catch (e) {+ logger.error(`[GET /api/ping] Invalid target_server_url: ${target_server_url} - ${e.message}`);}} else if (- isBackendInDocker &&(host_ip === "0.0.0.0" ||host_ip === "127.0.0.1" ||host_ip === "[::]" ||host_ip === "[::1]")) {- pingable_host_ip = "host.docker.internal";- if (currentDebug) {- console.log(- `[Server] DEBUG: [GET /api/ping] Remapping generic host_ip '${host_ip}' to 'host.docker.internal' for local Docker ping to port ${host_port}.`+ if (isInDocker) {+ const dockerHostIP = getDockerHostIP();+ pingable_host_ip = dockerHostIP;+ logPingDebug(+ `Detected Docker environment, using host IP '${dockerHostIP}' for port ${host_port}`);- }- } else if (currentDebug) {- console.log(- `[Server] DEBUG: [GET /api/ping] Pinging ${pingable_host_ip}:${portNum} (isBackendInDocker: ${isBackendInDocker}, target_server_url: ${- target_server_url || "N/A"- }).`- );- }-- let finalReachable = false;- let finalProtocol = "http";-- if (currentDebug) {- console.log(- `[Server] DEBUG: [GET /api/ping] Attempting HTTPS for ${pingable_host_ip}:${portNum}`- );- }- const httpsResponse = await testProtocol("https", pingable_host_ip, portNum);-- if (httpsResponse.success) {- finalReachable = true;- finalProtocol = "https";- if (currentDebug) {- console.log(- `[Server] DEBUG: [GET /api/ping] HTTPS success for ${pingable_host_ip}:${portNum}`+ } else {+ pingable_host_ip = "localhost";+ logPingDebug();}} else {- if (currentDebug) {- console.log(- `[Server] DEBUG: [GET /api/ping] HTTPS failed for ${pingable_host_ip}:${portNum}. Reason: ${- httpsResponse.reason || `Status: ${httpsResponse.statusCode}`- }. Attempting HTTP.`- );- }- const httpResponse = await testProtocol("http", pingable_host_ip, portNum);- if (httpResponse.success) {- finalReachable = true;- finalProtocol = "http";- if (currentDebug) {- console.log(- `[Server] DEBUG: [GET /api/ping] HTTP success for ${pingable_host_ip}:${portNum}`- );- }- } else {- if (currentDebug) {- console.log(- `[Server] DEBUG: [GET /api/ping] HTTP also failed for ${pingable_host_ip}:${portNum}. Reason: ${- httpResponse.reason || `Status: ${httpResponse.statusCode}`- }`- );- }- }+ logPingDebug(`Using provided host_ip '${host_ip}' for port ${host_port}`);}- if (currentDebug) {- console.log(- `[Server] DEBUG: [GET /api/ping] Ping result for ${pingable_host_ip}:${portNum} -> reachable: ${finalReachable}, protocol: ${finalProtocol}`- );++ // Only log service testing for first few pings or important services+ const isImportantService = serviceInfo.type !== 'service' || portNum <= 1024;+ if (currentDebug && (pingDebugStats.count <= 3 || isImportantService)) {+ logger.debug(`Testing ${serviceInfo.name} (${serviceInfo.type}) on ${pingable_host_ip}:${portNum}`);+ }++ const httpsResponse = await testProtocol("https", pingable_host_ip, portNum, "/", currentDebug);+ const httpResponse = await testProtocol("http", pingable_host_ip, portNum, "/", currentDebug);++ const result = determineServiceStatus(serviceInfo, httpsResponse, httpResponse);++ // Only log results for first few pings or failures+ if (currentDebug && (pingDebugStats.count <= 3 || result.status === 'unreachable')) {+ logger.debug(`Service status for ${pingable_host_ip}:${portNum} -> ${result.status} (${result.color})`);}- res.json({ reachable: finalReachable, protocol: finalProtocol });++ res.json({+ reachable: result.status !== 'unreachable',+ status: result.status,+ color: result.color,+ title: result.title,+ protocol: result.protocol || null,+ serviceType: serviceInfo.type,+ serviceName: serviceInfo.name,+ description: result.description+ });+++ if (currentDebug) logger.setDebugEnabled(process.env.DEBUG === 'true');});app.get("/api/health", (req, res) => {- console.log("[Server] INFO: Received GET /api/health request");+ logger.debug("Health check requested");try {const dbCheck = db.prepare("SELECT 1").get();const memoryUsage = process.memoryUsage();const uptime = process.uptime();- console.log("[Server] INFO: Sending /api/health response");+ logger.debug("Health check successful");res.json({status: "healthy",timestamp: new Date().toISOString(),@@ -1080,11 +1415,8 @@ app.get("/api/health", (req, res) => {database: "connected",});} catch (error) {- console.error(- "[Server] ERROR: Health check failed:",- error.message,- error.stack || ""- );+ logger.error("Health check failed:", error.message);+ logger.debug("Stack trace:", error.stack || "");res.status(503).json({status: "unhealthy",error: error.message,@@ -1094,22 +1426,15 @@ app.get("/api/health", (req, res) => {});const staticPath = path.join(__dirname, "public");-console.log(- `[Server] INFO: Attempting to serve static files from: ${staticPath}`-);+logger.info(`Attempting to serve static files from: ${staticPath}`);app.use(express.static(staticPath, { fallthrough: true, index: false }));app.get("*", (req, res, next) => {const indexPath = path.join(__dirname, "public", "index.html");- console.log(- `[Server] INFO: Catch-all GET '*' received for path: ${req.path}. Attempting to serve: ${indexPath}`- );+ logger.debug(`Serving frontend for path: ${req.path}`);res.sendFile(indexPath, (err) => {if (err) {- console.error(- `[Server] ERROR: Failed to send ${indexPath} for ${req.path}:`,- err.message- );+ logger.error(`Failed to send ${indexPath} for ${req.path}: ${err.message}`);if (!res.headersSent) {res.status(404).json({error: "Frontend entry point not found",@@ -1117,18 +1442,13 @@ app.get("*", (req, res, next) => {});}} else {- console.log(- `[Server] INFO: Successfully sent ${indexPath} for ${req.path}`- );+ logger.debug(`Successfully served frontend for ${req.path}`);}});});app.use((err, req, res, next) => {- console.error(- "[Server] FATAL: Unhandled error in Express middleware:",- err.stack || err.message- );+ logger.fatal("Unhandled error in Express middleware:", err.stack || err.message);if (!res.headersSent) {res.status(500)@@ -1138,36 +1458,23 @@ app.use((err, req, res, next) => {}});-console.log(`[Server] INFO: About to call app.listen on port ${PORT}`);+logger.info(`About to call app.listen on port ${PORT}`);try {app.listen(PORT, "0.0.0.0", () => {- console.log(- `[Server] INFO: Server is now listening on http://0.0.0.0:${PORT}`- );- console.log(`[Server] INFO: Full startup message complete.`);+ logger.info(`Server is now listening on http://0.0.0.0:${PORT}`);+ logger.info("Full startup message complete.");});} catch (listenError) {- console.error(- "[Server] FATAL: app.listen failed to start:",- listenError.message,- listenError.stack || ""- );+ logger.fatal("app.listen failed to start:", listenError.message);+ logger.debug("Stack trace:", listenError.stack || "");process.exit(1);}process.on("unhandledRejection", (reason, promise) => {- console.error(- "[Server] FATAL: Unhandled Rejection at:",- promise,- "reason:",- reason- );+ logger.fatal("Unhandled Rejection at:", promise, "reason:", reason);});process.on("uncaughtException", (error) => {- console.error(- "[Server] FATAL: Uncaught Exception:",- error.stack || error.message- );+ logger.fatal("Uncaught Exception:", error.stack || error.message);process.exit(1);});diff --git a/backend/lib/logger.js b/backend/lib/logger.jsnew file mode 100644index 0000000..b2c5b92--- /dev/null+++ b/backend/lib/logger.js@@ -0,0 +1,127 @@+/**+ * Centralized logging system for Portracker+ * Provides consistent logging across all components+ */++class Logger {+ constructor(component, options = {}) {+ this.component = component;+ this.debugEnabled = options.debug !== undefined ? options.debug : process.env.DEBUG === 'true';+ }++ /**+ * Internal logging method with consistent formatting+ */+ _log(level, ...args) {+ const timestamp = new Date().toISOString();+ const prefix = `[${timestamp}] [${this.component}] ${level}:`;++ switch (level) {+ case 'DEBUG':+ if (this.debugEnabled) {+ console.log(prefix, ...args);+ }+ break;+ case 'INFO':+ console.log(prefix, ...args);+ break;+ case 'WARN':+ console.warn(prefix, ...args);+ break;+ case 'ERROR':+ console.error(prefix, ...args);+ break;+ case 'FATAL':+ console.error(prefix, ...args);+ break;+ }+ }++ /**+ * Log debug messages (only shown when debug is enabled)+ */+ debug(...args) {+ this._log('DEBUG', ...args);+ }++ /**+ * Log informational messages+ */+ info(...args) {+ this._log('INFO', ...args);+ }++ /**+ * Log warning messages+ */+ warn(...args) {+ this._log('WARN', ...args);+ }++ /**+ * Log error messages+ */+ error(...args) {+ this._log('ERROR', ...args);+ }++ /**+ * Log fatal error messages+ */+ fatal(...args) {+ this._log('FATAL', ...args);+ }++ /**+ * Enable or disable debug logging+ */+ setDebugEnabled(enabled) {+ this.debugEnabled = enabled;+ }++ /**+ * Check if debug logging is enabled+ */+ isDebugEnabled() {+ return this.debugEnabled;+ }+}++/**+ * Static logger factory for quick access+ */+class LoggerFactory {+ static create(component, options = {}) {+ return new Logger(component, options);+ }++ /**+ * Quick static logging methods for simple use cases+ */+ static info(component, ...args) {+ const logger = new Logger(component);+ logger.info(...args);+ }++ static debug(component, enabled, ...args) {+ const logger = new Logger(component, { debug: enabled });+ logger.debug(...args);+ }++ static warn(component, ...args) {+ const logger = new Logger(component);+ logger.warn(...args);+ }++ static error(component, ...args) {+ const logger = new Logger(component);+ logger.error(...args);+ }++ static fatal(component, ...args) {+ const logger = new Logger(component);+ logger.fatal(...args);+ }+}++module.exports = { Logger, LoggerFactory };diff --git a/backend/lib/proc-parser.js b/backend/lib/proc-parser.jsnew file mode 100644index 0000000..743d7c2--- /dev/null+++ b/backend/lib/proc-parser.js@@ -0,0 +1,346 @@+/**+ * /proc filesystem parser for secure port detection+ */++const fs = require('fs').promises;+const path = require('path');+const { Logger } = require('./logger');++class ProcParser {+ constructor(procPath = '/proc') {+ this.logger = new Logger("ProcParser", { debug: process.env.DEBUG === 'true' });++ // Check environment variable for host proc path+ const hostProcPath = process.env.HOST_PROC;++ // PLATFORM-ADAPTIVE PRIORITY ORDER+ // TrueNAS: /proc/net/tcp exists, /host/proc/net/tcp does NOT exist+ // macOS Docker Desktop: /host/proc/net/tcp exists, /proc/net/tcp might not+ const procPaths = [+ procPath, // Default /proc (works on TrueNAS)+ '/proc', // Direct /proc (TrueNAS primary)+ hostProcPath, // Environment variable override+ '/host/proc', // Docker mount point (macOS primary)+ '/hostproc', // Alternative mount point+ ].filter(Boolean); // Remove null/undefined values++ // Find the first accessible /proc path+ this.procPath = procPath;+ for (const testPath of procPaths) {+ try {+ const stats = require('fs').statSync(path.join(testPath, 'net', 'tcp'));+ this.procPath = testPath;+ this.logger.debug(`Using /proc path: ${this.procPath}`);+ break;+ } catch (err) {+ // Continue to next path+ }+ }++ this.logger.info(`Final /proc path: ${this.procPath}`);++ // Important UDP ports that should always be included regardless of INCLUDE_UDP setting+ this.importantUdpPorts = [+ 53, // DNS+ 67, // DHCP Server+ 68, // DHCP Client+ 123, // NTP+ 137, // NetBIOS Name Service+ 138, // NetBIOS Datagram Service+ 161, // SNMP+ 162, // SNMP Trap+ 514, // Syslog+ 500, // IPsec IKE+ 4500, // IPsec NAT-T+ 1194, // OpenVPN+ 1198, // OpenVPN+ 51820, // WireGuard+ 51821, // WireGuard-UI+ 51822, // WireGuard+ ];++ // Add containerized environment detection+ this.isContainerized = this._detectContainerizedEnvironment();+ if (this.isContainerized) {+ this.logger.debug(`Detected containerized environment, using host network namespace`);+ }+ }++ /**+ * Detect if running in containerized environment with host PID access+ */+ _detectContainerizedEnvironment() {+ try {+ // Check if we're in a container with host PID access+ const fs = require('fs');++ // If we can see massive number of processes, we have host PID access+ const procDirs = fs.readdirSync(this.procPath);+ const pidCount = procDirs.filter(dir => /^\d+$/.test(dir)).length;++ // If we see >100 processes and have /.dockerenv, we're containerized with host PID+ const hasDockerEnv = fs.existsSync('/.dockerenv');+ const hasHostPidAccess = pidCount > 100;++ return hasDockerEnv && hasHostPidAccess;+ } catch (err) {+ return false;+ }+ }++ /**+ * Get network file path - use host process network namespace if containerized+ */+ _getNetworkFilePath(protocol) {+ if (this.isContainerized) {+ // Use init process (PID 1) network namespace to access host network+ return path.join(this.procPath, '1', 'net', protocol);+ }+ return path.join(this.procPath, 'net', protocol);+ }++ /**+ * Parse /proc/net/tcp and /proc/net/tcp6+ */+ async getTcpPorts() {+ const ports = [];++ for (const file of ['tcp', 'tcp6']) {+ try {+ const filePath = this._getNetworkFilePath(file);+ const content = await fs.readFile(filePath, 'utf8');+ const lines = content.trim().split('\n').slice(1); // Skip header++ for (const line of lines) {+ const parts = line.trim().split(/\s+/);+ if (parts.length < 10) continue;++ const [, localAddress, remoteAddress, state, , , , , , inode] = parts;++ // State 0A = LISTEN+ if (state !== '0A') continue;++ const [addrHex, portHex] = localAddress.split(':');+ const port = parseInt(portHex, 16);++ if (port === 0 || port > 65535) continue;++ const ip = this._parseHexAddress(addrHex);+ const processInfo = await this._findProcessByInode(parseInt(inode, 10));++ ports.push({+ protocol: 'tcp',+ host_ip: ip,+ host_port: port,+ inode: parseInt(inode, 10),+ pid: processInfo?.pid,+ owner: processInfo?.name || 'unknown'+ });+ }+ } catch (err) {+ this.logger.warn(`Warning reading network file ${file}:`, err.message);+ }+ }++ return ports;+ }++ /**+ * Parse /proc/net/udp and /proc/net/udp6 with proper filtering+ * @param {boolean} includeAll - If true, include all UDP ports. If false, only important ones+ */+ async getUdpPorts(includeAll = false) {+ const ports = [];++ for (const file of ['udp', 'udp6']) {+ try {+ const filePath = this._getNetworkFilePath(file);+ const content = await fs.readFile(filePath, 'utf8');+ const lines = content.trim().split('\n').slice(1); // Skip header++ for (const line of lines) {+ const parts = line.trim().split(/\s+/);+ if (parts.length < 10) continue;++ const [, localAddress, , , , , , , , inode] = parts;++ const [addrHex, portHex] = localAddress.split(':');+ const port = parseInt(portHex, 16);++ if (port === 0 || port > 65535) continue;++ // Filter UDP ports based on includeAll setting+ if (!includeAll && !this.importantUdpPorts.includes(port)) {+ continue;+ }++ const ip = this._parseHexAddress(addrHex);+ const processInfo = await this._findProcessByInode(parseInt(inode, 10));++ ports.push({+ protocol: 'udp',+ host_ip: ip,+ host_port: port,+ inode: parseInt(inode, 10),+ pid: processInfo?.pid,+ owner: processInfo?.name || 'unknown'+ });+ }+ } catch (err) {+ this.logger.warn(`Warning reading network file ${file}:`, err.message);+ }+ }++ return ports;+ }++ /**+ * Test if /proc parsing is working effectively+ * Returns true if we can find a reasonable number of ports+ */+ async testProcAccess() {+ try {+ // First check if we can read the TCP file at all+ const tcpPath = path.join(this.procPath, 'net', 'tcp');+ await fs.access(tcpPath, fs.constants.R_OK);++ // Then check if we get meaningful content+ const content = await fs.readFile(tcpPath, 'utf8');+ const lines = content.trim().split('\n');++ // Should have header + at least some entries+ if (lines.length < 2) {+ this.logger.warn(`/proc/net/tcp has no entries`);+ return false;+ }++ // Count listening ports+ let listeningPorts = 0;+ for (let i = 1; i < lines.length; i++) {+ const parts = lines[i].trim().split(/\s+/);+ if (parts.length >= 4 && parts[3] === '0A') { // State 0A = LISTEN+ listeningPorts++;+ }+ }++ this.logger.debug(`Found ${listeningPorts} listening TCP ports in ${this.procPath}/net/tcp`);++ // Also check if we can read process information+ let canReadProcesses = false;+ try {+ const testPids = await fs.readdir(this.procPath);+ const numericPids = testPids.filter(p => /^\d+$/.test(p));+ if (numericPids.length > 0) {+ // Try to read at least one process cmdline+ const testPid = numericPids[0];+ await fs.readFile(path.join(this.procPath, testPid, 'cmdline'), 'utf8');+ canReadProcesses = true;+ }+ } catch (err) {+ this.logger.warn(`Cannot read process information: ${err.message}`);+ }++ // In Docker environments without host network, we typically see fewer ports+ // and might not be able to read all process information+ // Return true if we can at least read the network files+ return listeningPorts >= 1 || canReadProcesses;+ } catch (err) {+ this.logger.warn(`/proc access test failed:`, err.message);+ return false;+ }+ }++ /**+ * Parse hex IP address+ */+ _parseHexAddress(hex) {+ if (hex === '00000000') return '0.0.0.0';++ if (hex.length === 8) {+ // IPv4 - little endian+ const bytes = [];+ for (let i = 6; i >= 0; i -= 2) {+ bytes.push(parseInt(hex.substr(i, 2), 16));+ }+ return bytes.join('.');+ } else if (hex.length === 32) {+ // IPv6 - for now just return ::+ return '::';+ }++ return '0.0.0.0';+ }++ /**+ * Find process by socket inode+ */+ async _findProcessByInode(inode) {+ if (this.isContainerized) {+ // In containerized environment, we can't reliably map inodes to processes+ // Return null to fall back to "unknown" attribution+ return null;+ }++ try {+ const dirs = await fs.readdir(this.procPath);++ for (const dir of dirs) {+ if (!/^\d+$/.test(dir)) continue;++ const pid = parseInt(dir, 10);+ const fdPath = path.join(this.procPath, dir, 'fd');++ try {+ const fds = await fs.readdir(fdPath);++ for (const fd of fds) {+ try {+ const link = await fs.readlink(path.join(fdPath, fd));+ if (link === `socket:[${inode}]`) {+ // Found the process+ const cmdline = await fs.readFile(+ path.join(this.procPath, dir, 'cmdline'),+ 'utf8'+ );+ const name = cmdline.split('\0')[0].split('/').pop() || 'unknown';++ return { pid, name };+ }+ } catch (err) {+ // Permission denied or broken link+ }+ }+ } catch (err) {+ // Process might have exited or permission denied+ }+ }+ } catch (err) {+ // Permission denied on /proc+ this.logger.warn(`Error reading process info: ${err.message}`);+ }++ return null;+ }++ /**+ * Check if a process belongs to a Docker container+ */+ async getContainerByPid(pid) {+ try {+ const cgroupPath = path.join(this.procPath, pid.toString(), 'cgroup');+ const content = await fs.readFile(cgroupPath, 'utf8');++ // Look for Docker container ID in cgroup+ const match = content.match(/docker[/-]([a-f0-9]{64})/);+ if (match) {+ return match[1].substring(0, 12); // Short container ID+ }+ } catch (err) {+ // Not accessible or not a container+ }++ return null;+ }+}++module.exports = ProcParser;\ No newline at end of filediff --git a/backend/lib/tn-ws.js b/backend/lib/tn-ws.jsindex 9b79fad..426fcb0 100644--- a/backend/lib/tn-ws.js+++ b/backend/lib/tn-ws.js@@ -4,12 +4,24 @@*/const WebSocket = require("ws");-const debugWS = require("debug")("ports-tracker:truenas:ws");+const { Logger } = require('./logger');const {discoverUIConfig,generateWebSocketURLs,} = require("./truenas-auto-discover");+// Initialize centralized logger+const logger = new Logger("TrueNAS-WS", { debug: process.env.DEBUG === 'true' });++/**+ * Logs a debug message for the TrueNAS WebSocket client using the centralized logger.+ * @param {string} message - The debug message to log.+ * @param {...any} args - Additional arguments to include in the log message.+ */+function debugWS(message, ...args) {+ logger.debug(message, ...args);+}+/*** Get TrueNAS WebSocket URLs to try* @param {object} options - Options objectdiff --git a/backend/lib/truenas-auto-discover.js b/backend/lib/truenas-auto-discover.jsindex 7bc2691..d7c5657 100644--- a/backend/lib/truenas-auto-discover.js+++ b/backend/lib/truenas-auto-discover.js@@ -4,7 +4,19 @@*/const fs = require("fs");-const debugDiscovery = require("debug")("ports-tracker:truenas:discovery");+const { Logger } = require('./logger');++// Initialize logger for auto-discovery+const logger = new Logger("TrueNAS-Discovery", { debug: process.env.DEBUG === 'true' });++/**+ * Logs a debug message using the TrueNAS-Discovery logger.+ * @param {string} message - The debug message to log.+ * @param {...any} args - Additional arguments to include in the log message.+ */+function debugDiscovery(message, ...args) {+ logger.debug(message, ...args);+}/*** Discover TrueNAS UI configuration via Unix socket@@ -178,10 +190,10 @@ function callSocketMethod(socketPath, method, options = {}) {}/**- * Detect network environment and get appropriate host addresses- * @param {object} [options={}] - Options object- * @param {boolean} [options.appDebugEnabled=false] - Whether application-level debug is enabled- * @returns {Array<string>} Host addresses to try+ * Returns a list of host addresses suitable for connecting to the TrueNAS UI, adapting to local or containerized environments.+ *+ * If running inside a container, attempts to detect the default gateway IP and includes additional container-specific addresses.+ * @returns {Array<string>} Array of host addresses to attempt for network connections.*/function detectHostAddresses(options = {}) {const hostAddresses = [];@@ -192,9 +204,37 @@ function detectHostAddresses(options = {}) {process.env.DOCKER_HOST || fs.existsSync("/.dockerenv");if (isContainerEnvironment) {+ try {+ const fs = require("fs");+ if (fs.existsSync("/proc/net/route")) {+ const routes = fs.readFileSync("/proc/net/route", "utf8");+ const lines = routes.split("\n");+ for (const line of lines) {+ const fields = line.split("\t");+ if (fields[1] === "00000000" && fields[7] === "00000000") {+ const gatewayHex = fields[2];+ const gateway = [+ parseInt(gatewayHex.substr(6, 2), 16),+ parseInt(gatewayHex.substr(4, 2), 16),+ parseInt(gatewayHex.substr(2, 2), 16),+ parseInt(gatewayHex.substr(0, 2), 16)+ ].join(".");++ if (!hostAddresses.includes(gateway)) {+ hostAddresses.unshift(gateway);+ }+ break;+ }+ }+ }+ } catch (err) {+ // Fallback silently+ }+hostAddresses.push("host.docker.internal");hostAddresses.push("172.17.0.1");}+return hostAddresses;}diff --git a/backend/lib/truenas-rpc.js b/backend/lib/truenas-rpc.jsindex 4087a51..1179b45 100644--- a/backend/lib/truenas-rpc.js+++ b/backend/lib/truenas-rpc.js@@ -8,13 +8,14 @@*/const { connectWs } = require("./tn-ws");-const debugRPC = require("debug")("ports-tracker:truenas:rpc");+const { Logger } = require('./logger');/*** TrueNAS middleware client using Unix socket first, WebSocket fallback*/class TrueNASClient {constructor(options = {}) {+ this.logger = new Logger("TrueNAS-RPC", { debug: options.debug || false });this.appDebugEnabled = options.debug || false;this.client = null;@@ -30,7 +31,7 @@ class TrueNASClient {* @param {...any} args Arguments to log*/logError(...args) {- console.error("[TrueNAS-RPC]", ...args);+ this.logger.error(...args);}async connect() {@@ -39,7 +40,7 @@ class TrueNASClient {}if (this.appDebugEnabled) {- debugRPC("Attempting to connect...");+ this.logger.debug("Attempting to connect...");}await this._doConnect();}@@ -47,12 +48,12 @@ class TrueNASClient {async _doConnect() {try {if (this.appDebugEnabled) {- debugRPC("Attempting WebSocket connection...");+ this.logger.debug("Attempting WebSocket connection...");}if (!this.apiKey) {if (this.appDebugEnabled) {- debugRPC(+ this.logger.info("ℹ️ No API key provided - TrueNAS enhanced features will be disabled. Setting up graceful degradation.");}@@ -61,7 +62,7 @@ class TrueNASClient {}if (this.appDebugEnabled) {- debugRPC(+ this.logger.debug("API key found - attempting authenticated WebSocket connection");}@@ -76,11 +77,11 @@ class TrueNASClient {this.clientType = "websocket";this.connected = true;if (this.appDebugEnabled) {- debugRPC("Connected via WebSocket with authentication");+ this.logger.info("Connected via WebSocket with authentication");}} catch (wsError) {if (this.appDebugEnabled) {- debugRPC(`WebSocket connection failed: ${wsError.message}`);+ this.logger.warn(`WebSocket connection failed: ${wsError.message}`);}this.logError("WebSocket connection error:",@@ -93,12 +94,12 @@ class TrueNASClient {_setupGracefulDegradation() {if (this.appDebugEnabled) {- debugRPC("Setting up graceful degradation mode for TrueNASClient");+ this.logger.debug("Setting up graceful degradation mode for TrueNASClient");}this.client = async (method) => {if (this.appDebugEnabled) {- debugRPC(+ this.logger.debug(`TrueNAS method ${method} called in graceful degradation mode. No API call made.`);}@@ -111,7 +112,7 @@ class TrueNASClient {this.clientType = "graceful-degradation";this.connected = true;if (this.appDebugEnabled) {- debugRPC("TrueNASClient graceful degradation active.");+ this.logger.info("TrueNASClient graceful degradation active.");}}@@ -122,16 +123,16 @@ class TrueNASClient {try {if (this.appDebugEnabled) {- debugRPC(`Calling TrueNAS API method: ${method} with params:`, params);+ this.logger.debug(`Calling TrueNAS API method: ${method} with params:`, params);}const result = await this.client(method, params);if (this.appDebugEnabled) {- debugRPC(`Received response for ${method}`);+ this.logger.debug(`Received response for ${method}`);}return result;} catch (err) {if (this.appDebugEnabled) {- debugRPC(`Error calling TrueNAS API method ${method}:`, err.message);+ this.logger.warn(`Error calling TrueNAS API method ${method}:`, err.message);}this.logError(`TrueNAS RPC Error for method '${method}':`,@@ -145,7 +146,7 @@ class TrueNASClient {close() {if (this.wsCloseFn) {if (this.appDebugEnabled) {- debugRPC("Closing TrueNASClient WebSocket connection via wsCloseFn");+ this.logger.debug("Closing TrueNASClient WebSocket connection via wsCloseFn");}this.wsCloseFn();this.wsCloseFn = null;@@ -153,7 +154,7 @@ class TrueNASClient {this.client = null;this.connected = false;if (this.appDebugEnabled) {- debugRPC("TrueNASClient connection closed and reset.");+ this.logger.info("TrueNASClient connection closed and reset.");}}}diff --git a/backend/utils/performance-tracker.js b/backend/utils/performance-tracker.jsindex 54be6f1..cddb191 100644--- a/backend/utils/performance-tracker.js+++ b/backend/utils/performance-tracker.js@@ -1,9 +1,12 @@/*** Simple performance tracking utility for measuring operation durations*/+const { Logger } = require('../lib/logger');+class PerformanceTracker {constructor() {this.operations = new Map();+ this.logger = new Logger("Performance", { debug: process.env.DEBUG === 'true' });}/**@@ -22,15 +25,15 @@ class PerformanceTracker {end(operation) {const op = this.operations.get(operation);if (!op) {- console.warn(- `[Performance] Warning: No start time found for operation '${operation}'`+ this.logger.warn(+ `Warning: No start time found for operation '${operation}'`);return 0;}const duration = Date.now() - op.startTime;op.duration = duration;- console.log(`[Performance] ${operation}: ${duration}ms`);+ this.logger.debug(`${operation}: ${duration}ms`);return duration;}diff --git a/docker-compose.yml b/docker-compose.ymlindex dc42582..a279475 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -2,31 +2,44 @@ version: '3.8'services:portracker:+ build: .image: portracker:latestcontainer_name: portrackerrestart: unless-stopped- network_mode: "host"+ # network_mode: "host"+ pid: "host" # Access host PID namespace++ cap_add:+ - SYS_PTRACE # For process inspection+ - SYS_ADMIN # For nsenter if neededvolumes:- /var/run/docker.sock:/var/run/docker.sock:ro- - /run/middleware/middlewared.sock:/var/run/middlewared.sock:ro # For TrueNAS- ./portracker-data:/data+ - /proc:/host/proc:ro # Mount host /proc+ - /sys:/host/sys:ro # Mount host /sys filesystem (optional but helpful)++ ports:+ - "${HOST_PORT:-4999}:4999"environment:# CORE CONFIGURATION- DATABASE_PATH=/data/portracker.db- PORT=4999+ - NODE_ENV=production+ - DATA_DIR=/data+ - HOST_PROC=/host/proc # Tell the app where to find host /proc# TRUENAS INTEGRATION (Optional)- - TRUENAS_API_KEY=your-api-key-here+ # - TRUENAS_API_KEY=your-api-key-here# PERFORMANCE SETTINGS- CACHE_TIMEOUT_MS=60000 # Cache duration (60 seconds)- DISABLE_CACHE=false # Set to 'true' to disable caching- - INCLUDE_UDP=false # Set to 'true' to include UDP ports+ - INCLUDE_UDP=true # Set to 'true' to include UDP ports# DEBUGGING- - DEBUG=false # Set to 'true' for verbose logging+ - DEBUG=true # Set to 'true' for verbose logginghealthcheck:diff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex a4b70f7..37f9427 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -17,9 +17,20 @@ import { Label } from "@/components/ui/label";import { DashboardLayout } from "./components/layout/DashboardLayout";import { MultipleServerSkeleton } from "./components/server/MultipleServerSkeleton";import { BarChart3 } from "lucide-react";+import Logger from "./lib/logger";const keyOf = (srvId, p) => `${srvId}-${p.host_ip}-${p.host_port}`;+// Initialize logger for App component+const logger = new Logger('App');++/**+ * Main React component for the server and port monitoring dashboard.+ *+ * Manages state, data fetching, transformation, and user interactions for displaying and managing servers and their network ports. Handles UI preferences, filtering, searching, note editing, port ignoring, server addition and deletion, and clipboard actions. Synchronizes relevant state with localStorage and supports auto-refresh and error fallback mechanisms.+ *+ * @return {JSX.Element} The rendered dashboard application.+ */export default function App() {const [groups, setGroups] = useState([]);const [loading, setLoading] = useState(true);@@ -131,7 +142,7 @@ export default function App() {try {localStorage.setItem("portFilters", JSON.stringify(filters));} catch (error) {- console.warn("Failed to save filter settings:", error);+ logger.warn("Failed to save filter settings:", error);}}, [filters]);@@ -139,7 +150,7 @@ export default function App() {try {localStorage.setItem("expandedServers", JSON.stringify(expandedServers));} catch (error) {- console.warn("Failed to save expanded servers state:", error);+ logger.warn("Failed to save expanded servers state:", error);}}, [expandedServers]);@@ -147,7 +158,7 @@ export default function App() {try {localStorage.setItem("openAccordions", JSON.stringify(openAccordions));} catch (error) {- console.warn("Failed to save open accordions state:", error);+ logger.warn("Failed to save open accordions state:", error);}}, [openAccordions]);@@ -155,7 +166,7 @@ export default function App() {try {localStorage.setItem("infoCardLayout", infoCardLayout);} catch (error) {- console.warn("Failed to save info card layout setting:", error);+ logger.warn("Failed to save info card layout setting:", error);}}, [infoCardLayout]);@@ -163,7 +174,7 @@ export default function App() {try {localStorage.setItem("portLayout", portLayout);} catch (error) {- console.warn("Failed to save port layout setting:", error);+ logger.warn("Failed to save port layout setting:", error);}}, [portLayout]);@@ -182,7 +193,7 @@ export default function App() {JSON.stringify(searchHighlighting));} catch (error) {- console.warn("Failed to save search highlighting setting:", error);+ logger.warn("Failed to save search highlighting setting:", error);}}, [searchHighlighting]);@@ -210,8 +221,8 @@ export default function App() {const transformCollectorData = useCallback(async (collectorData, serverId) => {if (!collectorData.ports || !Array.isArray(collectorData.ports)) {- console.warn(- `[App] transformCollectorData: No ports array in collectorData for serverId ${serverId}`,+ logger.warn(+ `transformCollectorData: No ports array in collectorData for serverId ${serverId}`,collectorData);return [];@@ -241,18 +252,21 @@ export default function App() {note: port.note || null,ignored: !!port.ignored,created: port.created || null,+ internal: port.internal || false,}));const uniquePorts = [];const seenKeys = new Set();transformedPorts.forEach((port) => {- const key = `${port.host_ip}:${port.host_port}:${port.owner}`;+ const key = port.internal+ ? `${port.container_id || port.app_id}:${port.host_port}:internal`+ : `${port.host_ip}:${port.host_port}:${port.owner}`;if (!seenKeys.has(key)) {seenKeys.add(key);uniquePorts.push(port);} else {- console.warn("Filtering out duplicate port:", port);+ logger.debug(`DUPLICATE DETECTED - Filtering out port with key: ${key}`, port);}});@@ -296,8 +310,8 @@ export default function App() {});});- console.log(- `Transformed ${collectorData.ports.length} raw ports into ${portsWithGroupInfo.length} unique valid ports with grouping`+ logger.debug(+ `Final result: Transformed ${collectorData.ports.length} raw ports into ${portsWithGroupInfo.length} unique valid ports with grouping`);return portsWithGroupInfo;},@@ -348,7 +362,7 @@ export default function App() {.catch(() => ({error: `Local scan failed with status ${scanResponse.status}`,}));- console.warn(+ logger.warn(`Local scan API for ${server.id} failed:`,errorData.error);@@ -363,7 +377,7 @@ export default function App() {};}} catch (error) {- console.error("Error scanning local server:", error);+ logger.error("Error scanning local server:", error);return {id: server.id,server: server.label,@@ -406,7 +420,7 @@ export default function App() {const errorData = await scanResponse.json().catch(() => ({error: `Failed to scan peer '${server.label}' via backend. Status: ${scanResponse.status}`,}));- console.warn(+ logger.warn(`Failed to scan peer ${server.id} (${server.label}):`,errorData.details || errorData.error);@@ -424,7 +438,7 @@ export default function App() {};}} catch (error) {- console.error(+ logger.error(`Error fetching scan for peer ${server.id} (${server.label}):`,error);@@ -455,10 +469,10 @@ export default function App() {setGroups(enrichedServers);setTimeout(() => setLoading(false), 300);} catch (error) {- console.error("Error in fetchAll:", error);+ logger.error("Error in fetchAll:", error);try {- console.warn(+ logger.warn("Primary fetch failed, attempting complete fallback to legacy API");const fallbackResponse = await fetch("/api/all-ports");@@ -469,7 +483,7 @@ export default function App() {return;}} catch (fallbackError) {- console.error("Even fallback API failed:", fallbackError);+ logger.error("Even fallback API failed:", fallbackError);}setError(error.toString());@@ -554,7 +568,7 @@ export default function App() {throw new Error("Failed to update ignore status on backend.");}).catch((error) => {- console.error("Error toggling ignore:", error);+ logger.error("Error toggling ignore:", error);setGroups((currentGroups) =>currentGroups.map((group) => {if (group.id === srvId) {@@ -633,7 +647,7 @@ export default function App() {if (!response.ok) throw new Error("Failed to save note on backend.");}).catch((error) => {- console.error("Error saving note:", error);+ logger.error("Error saving note:", error);setGroups((currentGroups) =>currentGroups.map((group) => {if (group.id === modalSrvId) {@@ -658,7 +672,7 @@ export default function App() {fetch("/api/servers").then((r) => r.json()).then(setServers)- .catch(console.error);+ .catch(logger.error);}, []);const addServer = useCallback(@@ -701,7 +715,7 @@ export default function App() {}} catch (error) {setGroups(originalGroups);- console.error("Failed to save server:", error);+ logger.error("Failed to save server:", error);throw error;}} else {@@ -790,7 +804,7 @@ export default function App() {);}} catch (error) {- console.error("Failed to add server:", error);+ logger.error("Failed to add server:", error);setGroups((currentGroups) =>currentGroups.filter((g) => g.id !== serverData.id));@@ -826,7 +840,7 @@ export default function App() {} catch (error) {setServers(originalServers);setGroups(originalGroups);- console.error("Failed to delete server:", error);+ logger.error("Failed to delete server:", error);}},[servers, groups, selectedServer, fetchServers]@@ -927,7 +941,7 @@ export default function App() {);}).catch((err) => {- console.warn("Clipboard write failed, using fallback:", err);+ logger.warn("Clipboard write failed, using fallback:", err);copyToClipboardFallback(urlToCopy, server.id, p);});} else {@@ -1087,7 +1101,7 @@ export default function App() {prompt("Copy this URL:", text);}} catch (err) {- console.warn("Copy failed:", err);+ logger.warn("Copy failed:", err);prompt("Copy this URL:", text);} finally {document.body.removeChild(textArea);diff --git a/frontend/src/components/server/PortGridItem.jsx b/frontend/src/components/server/PortGridItem.jsxindex 72fd071..ae698ce 100644--- a/frontend/src/components/server/PortGridItem.jsx+++ b/frontend/src/components/server/PortGridItem.jsx@@ -33,6 +33,11 @@ const renderHighlightedText = (content) => {);};+/**+ * Displays detailed information and interactive actions for a network port, with optional search term highlighting.+ *+ * Renders a styled UI card showing port status, clickable port number, internal port details, owner, notes, source, creation date, and host information. Provides actions for copying, editing notes, and toggling ignore state, with dynamic highlighting of search matches.+ */export function PortGridItem({port,serverId,@@ -120,12 +125,15 @@ export function PortGridItem({<div className="flex items-center space-x-0.5 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 transition-opacity ml-2"><PortActionsport={port}- itemKey={`${serverId}-${port.host_ip}-${port.host_port}`}+ itemKey={+ port.internal+ ? `${serverId}-${port.container_id || port.app_id}-${port.host_port}-internal`+ : `${serverId}-${port.host_ip}-${port.host_port}`+ }actionFeedback={actionFeedback}onCopy={() => onCopy(port, protocol)}onEdit={() => onNote(serverId, port)}onHide={() => onToggleIgnore(serverId, port)}- size="sm"/></div></div>diff --git a/frontend/src/components/server/PortStatusIndicator.jsx b/frontend/src/components/server/PortStatusIndicator.jsxindex 467fd6c..dfa8558 100644--- a/frontend/src/components/server/PortStatusIndicator.jsx+++ b/frontend/src/components/server/PortStatusIndicator.jsx@@ -6,13 +6,18 @@ import {TooltipTrigger,} from "@/components/ui/tooltip";+/**+ * Displays a colored status indicator with tooltip for a network port's reachability and status.+ *+ * Fetches the port's status from an API and visually represents it as a colored dot, with a tooltip describing the current state (e.g., reachable, unreachable, checking). Calls the optional `onProtocolChange` callback if the protocol is detected.+ */export function PortStatusIndicator({serverId,serverUrl,port,onProtocolChange,}) {- const [reachable, setReachable] = useState(null);+ const [statusData, setStatusData] = useState(null);const [checking, setChecking] = useState(true);useEffect(() => {@@ -22,6 +27,10 @@ export function PortStatusIndicator({let pingApiUrl = `/api/ping?host_ip=${encodeURIComponent(port.host_ip)}&host_port=${port.host_port}`;++ if (port.owner) {+ pingApiUrl += `&owner=${encodeURIComponent(port.owner)}`;+ }if (serverId &&@@ -37,12 +46,17 @@ export function PortStatusIndicator({res.ok ? res.json() : Promise.reject(`API ping failed: ${res.status}`)).then((data) => {- setReachable(data.reachable);+ setStatusData(data);if (onProtocolChange && data.protocol) {onProtocolChange(data.protocol);}})- .catch(() => setReachable(false))+ .catch(() => setStatusData({+ reachable: false,+ status: 'unreachable',+ color: 'red',+ title: 'Connection failed'+ })).finally(() => {clearTimeout(timeoutId);setChecking(false);@@ -52,24 +66,33 @@ export function PortStatusIndicator({clearTimeout(timeoutId);controller.abort();};- }, [port.host_ip, port.host_port, serverId, serverUrl, onProtocolChange]);+ }, [port.host_ip, port.host_port, port.owner, serverId, serverUrl, onProtocolChange]);const getDotState = () => {if (checking) {return {color: "bg-blue-400 animate-pulse",- title: "Checking port status...",+ title: "Checking service status...",};}- if (reachable === null) {++ if (!statusData) {return {color: "bg-gray-400",title: "Status unknown",};}++ const colorMap = {+ green: "bg-green-500",+ yellow: "bg-yellow-500",+ red: "bg-red-500",+ gray: "bg-gray-400"+ };+return {- color: reachable ? "bg-green-500" : "bg-red-500",- title: reachable ? "Port is reachable" : "Port is unreachable",+ color: colorMap[statusData.color] || "bg-gray-400",+ title: statusData.title || "Status unknown",};};@@ -82,7 +105,7 @@ export function PortStatusIndicator({<div className={`w-2.5 h-2.5 rounded-full ${dotState.color}`} /></TooltipTrigger><TooltipContent>- <p>{dotState.title}</p>+ <p className="font-medium">{dotState.title}</p></TooltipContent></Tooltip></TooltipProvider>diff --git a/frontend/src/components/server/PortTable.jsx b/frontend/src/components/server/PortTable.jsxindex 23d708c..982cd5b 100644--- a/frontend/src/components/server/PortTable.jsx+++ b/frontend/src/components/server/PortTable.jsx@@ -1,6 +1,11 @@import { ArrowUpDown, ArrowUp, ArrowDown } from "lucide-react";import { PortTableRow } from "./PortTableRow";+/**+ * Renders a sortable table displaying a list of ports with associated details and actions.+ *+ * Displays columns for status, port, service, source, host, creation time, and available actions. Allows sorting by port, service, or creation time. Each row represents a port and provides controls for copying, adding notes, or toggling ignore status.+ */export function PortTable({ports,serverId,@@ -98,7 +103,11 @@ export function PortTable({<tbody className="divide-y divide-slate-100 dark:divide-slate-800 bg-white dark:bg-slate-900">{ports.map((port) => (<PortTableRow- key={`${serverId}-${port.host_ip}-${port.host_port}`}+ key={+ port.internal+ ? `${serverId}-${port.container_id || port.app_id}-${port.host_port}-internal`+ : `${serverId}-${port.host_ip}-${port.host_port}`+ }port={port}serverId={serverId}serverUrl={serverUrl}diff --git a/frontend/src/components/server/ServerSection.jsx b/frontend/src/components/server/ServerSection.jsxindex e113ea3..5a8618e 100644--- a/frontend/src/components/server/ServerSection.jsx+++ b/frontend/src/components/server/ServerSection.jsx@@ -19,6 +19,7 @@ import { PortGridItem } from "./PortGridItem";import { PortTable } from "./PortTable";import { HiddenPortsDrawer } from "./HiddenPortsDrawer";import { SystemInfoCard } from "./SystemInfoCard";+import Logger from "../../lib/logger";import { VMsCard } from "./VMsCard";import {Accordion,@@ -33,6 +34,11 @@ import {DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";+/**+ * Renders a comprehensive server overview section, including system information, virtual machines, and port management with sorting, filtering, and multiple layout options.+ *+ * Displays server status, host details, and provides interactive controls for sorting and viewing ports in list, grid, card, or table formats. Allows toggling between expanded and collapsed views, managing hidden ports, and switching layouts for system info and VMs. Handles user actions such as copying, editing notes, and toggling port visibility.+ */function ServerSectionComponent({server,ok,@@ -56,6 +62,9 @@ function ServerSectionComponent({infoCardLayout,onInfoCardLayoutChange,}) {+ // Initialize logger for ServerSection component+ const logger = new Logger('ServerSection');+const [sortConfig, setSortConfig] = useState(() => {try {const saved = localStorage.getItem("portSortConfig");@@ -112,7 +121,7 @@ function ServerSectionComponent({try {localStorage.setItem("portSortConfig", JSON.stringify(sortConfig));} catch (error) {- console.warn("Failed to save sort config:", error);+ logger.warn("Failed to save sort config:", error);}}, [sortConfig]);@@ -469,9 +478,44 @@ function ServerSectionComponent({<ul className="space-y-2">{portsToDisplay.map((port) => (<PortCard- key={`${id}-${port.host_ip}-${port.host_port}`}+ key={+ port.internal+ ? `${id}-${port.container_id || port.app_id}-${port.host_port}-internal`+ : `${id}-${port.host_ip}-${port.host_port}`+ }+ port={port}+ itemKey={+ port.internal+ ? `${id}-${port.container_id || port.app_id}-${port.host_port}-internal`+ : `${id}-${port.host_ip}-${port.host_port}`+ }+ searchTerm={searchTerm}+ actionFeedback={actionFeedback}+ onCopy={onCopy}+ onEdit={onNote}+ onToggleIgnore={onToggleIgnore}+ serverId={id}+ serverUrl={serverUrl}+ />+ ))}+ </ul>+ )}++ {portLayout === "card" && (+ <ul className="space-y-2">+ {portsToDisplay.map((port) => (+ <PortCard+ key={+ port.internal+ ? `${id}-${port.container_id || port.app_id}-${port.host_port}-internal`+ : `${id}-${port.host_ip}-${port.host_port}`+ }port={port}- itemKey={`${id}-${port.host_ip}-${port.host_port}`}+ itemKey={+ port.internal+ ? `${id}-${port.container_id || port.app_id}-${port.host_port}-internal`+ : `${id}-${port.host_ip}-${port.host_port}`+ }searchTerm={searchTerm}actionFeedback={actionFeedback}onCopy={onCopy}@@ -483,11 +527,16 @@ function ServerSectionComponent({))}</ul>)}+{portLayout === "grid" && (<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">{portsToDisplay.map((port) => (<PortGridItem- key={`${id}-${port.host_ip}-${port.host_port}`}+ key={+ port.internal+ ? `${id}-${port.container_id || port.app_id}-${port.host_port}-internal`+ : `${id}-${port.host_ip}-${port.host_port}`+ }port={port}searchTerm={searchTerm}actionFeedback={actionFeedback}diff --git a/frontend/src/lib/logger.js b/frontend/src/lib/logger.jsnew file mode 100644index 0000000..e856c13--- /dev/null+++ b/frontend/src/lib/logger.js@@ -0,0 +1,101 @@+/**+ * Frontend Logger System for Portracker+ * Provides centralized logging with component identification and timestamp formatting+ * Consistent with backend logging patterns+ */++class Logger {+ constructor(componentName = 'Unknown', options = {}) {+ this.componentName = componentName;++ // Check debug flag from localStorage, URL params, or options+ this.debugEnabled = this._getDebugSetting(options);+ }++ _getDebugSetting(options) {+ // Priority: options.debug > URL param > localStorage > default false+ if (options.debug !== undefined) {+ return options.debug;+ }++ // Check URL parameters+ const urlParams = new URLSearchParams(window.location.search);+ if (urlParams.get('debug') === 'true') {+ return true;+ }++ // Check localStorage+ try {+ const stored = localStorage.getItem('portracker_debug');+ if (stored === 'true') return true;+ if (stored === 'false') return false;+ } catch {+ // localStorage might not be available+ }++ return false; // Default to false for production+ }++ formatTimestamp() {+ const now = new Date();+ return now.toISOString().slice(0, 19).replace('T', ' ');+ }++ getPrefix() {+ return `[${this.formatTimestamp()}] [${this.componentName}]`;+ }++ log(...args) {+ console.log(this.getPrefix(), ...args);+ }++ info(...args) {+ console.info(this.getPrefix(), '[INFO]', ...args);+ }++ warn(...args) {+ console.warn(this.getPrefix(), '[WARN]', ...args);+ }++ error(...args) {+ console.error(this.getPrefix(), '[ERROR]', ...args);+ }++ debug(...args) {+ if (this.debugEnabled) {+ console.debug(this.getPrefix(), '[DEBUG]', ...args);+ }+ }++ // Method to enable/disable debug logging+ setDebug(enabled) {+ this.debugEnabled = enabled;+ }++ // Convenience method for errors with context+ errorWithContext(message, error, context = {}) {+ console.error(this.getPrefix(), '[ERROR]', message, {+ error: error?.message || error,+ stack: error?.stack,+ ...context+ });+ }++ // Method for performance logging (frontend specific)+ performance(label, duration) {+ console.log(this.getPrefix(), '[PERF]', `${label}: ${duration}ms`);+ }+}++/**+ * Creates and returns a new Logger instance for the specified component.+ * @param {string} componentName - The name of the component associated with the logger.+ * @param {Object} [options={}] - Optional configuration for the logger, such as debug settings.+ * @return {Logger} A Logger instance configured for the given component.+ */+function LoggerFactory(componentName, options = {}) {+ return new Logger(componentName, options);+}++export { Logger, LoggerFactory };+export default Logger;