An open source, self-hosted, real-time port monitoring and discovery tool.
Feature/add auth (#65)
Mostafa Wahied6a51659b88f1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8e12856..cbf369c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,88 +2,114 @@All notable changes to portracker will be documented in this file.+## [Unreleased]++### Security++- **Authentication**: Optional authentication to secure dashboard access using `ENABLE_AUTH=true`+ - **[sub]** Disabled by default for backward compatibility+ - **[sub]** Recovery mode accessible via `RECOVERY_MODE=true` if you lose your password+ - **[sub]** When recovery mode is enabled, a time-limited recovery code (valid 15 minutes) appears in the logs to use on the login page with any username++### Dashboard++- **Auto-Refresh**: Added a toggle to auto-refresh ports and services every 30 seconds+## [1.1.1] - 2025-01-17-### Features+### Server Integrations+- **TrueNAS Enhanced Features**: Add your TrueNAS API key directly from the UI to unlock VM and LXC container monitoring with step-by-step setup instructions### Fixes+- **TrueNAS API Key Revocation**: Fixed automatic key revocation issue by prioritizing secure WebSocket connections- **Virtual Machines & Containers**: VMs and LXC containers now display correctly with icons and badges to distinguish between them- **Debug Logging**: DEBUG environment variable now properly enables debug output## [1.1.0] - 2025-08-23-### Frontend & Backend+### Dashboard+- **System Port Name Fix**: Fixed the issue where system ports were incorrectly displayed as "unknown".- **Consistent Status Indicators**: Improved status indicators for system ports to ensure consistency.## [1.0.8] - 2025-08-20-### Frontend-- **Batch rename migration fix**: Fix migration issue affecting batch rename operations so renamed services persist correctly.+### Dashboard-### Dev+- **Batch rename migration fix**: Fix migration issue affecting batch rename operations so renamed services persist correctly.- **Misc.**: minor migration-related fix for batch rename flow.## [1.0.7] - 2025-08-19-### Frontend+### Dashboard+- **Service renaming**: Allow renaming services from the UI.- **Batch actions**: Add selection and batch operations for services and ports (ignore, add note, etc.).- **Internal / Port display fixes**: Fix display issues so internal and published ports are shown correctly; fix select-box overlap.### Backend+- **Port protocol reporting**: Ensure ports include protocol information so reported mappings are accurate.## [1.0.6] - 2025-08-15-### Frontend+### Dashboard+- **Container Details Drawer**: New slide-out panel to show detailed information for Docker containers including stats, labels, mounts, and environment variables- **Internal Port Display**: UI now correctly shows and differentiates internal-only ports from published ports with health status monitoring- **Global Search**: Search bar now includes an option to search across all servers simultaneously- **What's New**: Automatic notification system to stay updated with new features when releasing new versions-### Backend+### Data+- **Collector Caching**: Added caching mechanism to all data collectors to reduce duplicate requests and improve data refresh speed## [1.0.5] - 2025-08-09-### Backend+### Server Integrations+- **Dockerode Integration**: Switched to use the dockerode library for more reliable Docker API interactions instead of shell commands- **Centralized Logging**: All collectors now use a single Logger class for consistent and structured logging throughout the application## [1.0.4] - 2025-08-09-### Frontend+### Dashboard+- **Enhanced Service Detection**: Improved identification and categorization of running services with Single Page Application (SPA) detection support- **Port Status Indicators**: Added clear visual distinction between different types of ports (published vs internal) with detailed status information-### Backend+### Server Integrations+- **Removed network_mode: host Requirement**: Eliminated the need for Docker host networking mode by implementing direct /proc filesystem parsing for better security- **Advanced Port Detection**: Enhanced system for more accurate container and system port identification using multiple detection methods- **Improved Container Introspection**: Better error handling and fallback strategies across different platforms for reliable port collection## [1.0.3] - 2025-08-07-### Infrastructure+### Data+- **Simplified Docker Dependencies**: Streamlined system requirements - no longer requires mounting additional system sockets for container information and support for docker proxy.- **Enhanced Data Accuracy**: Improved container information display with more accurate timestamps and metadata parsing## [1.0.2] - 2025-07-11-### Security & Improvements+### Security+- **Security Hardening**: Key security aspects addressed- **Data Collection**: Improved data collection accuracy## [1.0.1] - 2025-07-10### Initial Improvements+- Various fixes and improvements after initial release## [1.0.0] - 2025-07-07-### Initial Release+### Dashboard+- **Multi-platform Port Tracking**: Initial release of portracker with support for monitoring ports across multiple servers- **Docker Integration**: Native Docker container port monitoring- **Web Interface**: Clean, responsive web interface for port managementdiff --git a/README.md b/README.mdindex 19e4d69..c13e3c0 100644--- a/README.md+++ b/README.md@@ -174,6 +174,8 @@ Configure `portracker` using environment variables.| `PORT`\* | The port the web application will run on. | `4999` || `DATABASE_PATH`\* | Path inside the container to the SQLite database file. | `/data/portracker.db` || `TRUENAS_API_KEY` | Optional API key for enhanced TrueNAS data collection. | ` ` |+| `ENABLE_AUTH` | Set to `true` to enable authentication (v1.2.0+). | `false` |+| `SESSION_SECRET` | Secret key for session encryption (recommended when auth enabled). | _random_ || `CACHE_TIMEOUT_MS` | Duration in milliseconds to cache scan results. | `60000` || `DISABLE_CACHE` | Set to `true` to disable all caching. | `false` || `INCLUDE_UDP` | Set to `true` to include UDP ports in scans. | `false` |@@ -181,6 +183,31 @@ Configure `portracker` using environment variables.<sub>\*_Required_</sub>+### Authentication Setup (v1.2.0+)++Portracker includes optional authentication to secure dashboard access:++1. **Enable Authentication**: Set `ENABLE_AUTH=true` in your environment variables+2. **First-Time Setup**: On first access, you'll see a setup wizard to create the admin account+3. **Login**: Use your admin credentials to access the dashboard+4. **Production Recommendation**: Set a custom `SESSION_SECRET` for secure session management++**Example with Authentication:**++```yaml+services:+ portracker:+ image: mostafawahied/portracker:latest+ environment:+ - ENABLE_AUTH=true+ - SESSION_SECRET=your-random-secret-here-change-this+```++**Important Notes:**+- Authentication is **disabled by default** for backward compatibility+- When enabled, the dashboard requires login but API endpoints for peer communication remain accessible+- API key authentication for peer-to-peer communication is planned for v1.3.0+## Technical Stack- **Backend**: Node.js, Express, WebSocket, better-sqlite3@@ -191,9 +218,10 @@ Configure `portracker` using environment variables.Future development is focused on improving the application based on community feedback. Key areas include:-- Adding user authentication.-- Expanding the library of platform-specific collectors for other host systems.-- Addressing bugs and incorporating requested changes from the community.+- ~~Adding user authentication~~ ✅ **Added in v1.2.0** (optional authentication with setup wizard)+- Adding API key authentication for peer-to-peer communication (planned for v1.3.0)+- Expanding the library of platform-specific collectors for other host systems+- Addressing bugs and incorporating requested changes from the community## Star Historydiff --git a/backend/db.js b/backend/db.jsindex b5ec50a..84f391b 100644--- a/backend/db.js+++ b/backend/db.js@@ -97,6 +97,17 @@ if (!tableExists) {);`);createCustomServiceNamesTable.run();++ const createUsersTable = db.prepare(`+ CREATE TABLE IF NOT EXISTS users (+ id TEXT PRIMARY KEY,+ username TEXT UNIQUE NOT NULL,+ password_hash TEXT NOT NULL,+ created_at INTEGER NOT NULL,+ last_login INTEGER+ );+`);+ createUsersTable.run();} else {try {const notesColumns = db.prepare("PRAGMA table_info(notes)").all();@@ -484,6 +495,26 @@ if (!tableExists) {logger.info('Schema migration: custom_service_names table updated with protocol support');}+ const usersTableExists = db+ .prepare(+ "SELECT name FROM sqlite_master WHERE type='table' AND name='users'"+ )+ .get();++ if (!usersTableExists) {+ logger.info('Schema migration: Creating "users" table for authentication');+ db.exec(`+ CREATE TABLE users (+ id TEXT PRIMARY KEY,+ username TEXT UNIQUE NOT NULL,+ password_hash TEXT NOT NULL,+ created_at INTEGER NOT NULL,+ last_login INTEGER+ );+ `);+ logger.info('Schema migration: users table created successfully');+ }+} catch (migrationError) {logger.error("FATAL: Database schema migration failed:",diff --git a/backend/index.js b/backend/index.jsindex 5707e2f..f290eb1 100644--- a/backend/index.js+++ b/backend/index.js@@ -6,8 +6,12 @@* and system monitoring across multiple deployment platforms.*/+require('dotenv').config({ path: __dirname + '/.env' });+const express = require('express');const cors = require('cors');+const session = require('express-session');+const cookieParser = require('cookie-parser');const path = require('path');const fs = require('fs');const fetch = (...args) => (globalThis.fetch ? globalThis.fetch(...args) : import('node-fetch').then(m => m.default(...args)));@@ -17,6 +21,9 @@ const { createCollector, detectCollector } = require('./collectors');const db = require('./db');const https = require("https");const os = require("os");+const { requireAuth, checkAuthEnabled, isAuthEnabled } = require('./middleware/auth');+const authRoutes = require('./routes/auth');+const recoveryManager = require('./lib/recovery-manager');const logger = new Logger("Server", { debug: process.env.DEBUG === 'true' });const BASE_DEBUG = process.env.DEBUG === 'true';@@ -25,6 +32,12 @@ const { SimpleTTLCache } = require('./utils/cache');const responseCache = new SimpleTTLCache();const RESP_TTL_PORTS = parseInt(process.env.ENDPOINT_CACHE_PORTS_TTL_MS || '3000', 10);+if (isAuthEnabled()) {+ logger.info('Authentication is ENABLED - Login required for dashboard access');+} else {+ logger.info('Authentication is DISABLED - Dashboard is publicly accessible');+}+const PING_TIMEOUT = 2000;const pingDebugStats = {@@ -550,8 +563,45 @@ try {}const app = express();-app.use(cors());++app.use(cors({+ origin: true,+ credentials: true+}));app.use(express.json());+app.use(cookieParser());++const sessionSecret = process.env.SESSION_SECRET || require('crypto').randomBytes(32).toString('hex');++if (!process.env.SESSION_SECRET) {+ logger.warn('No SESSION_SECRET set - using random secret (sessions will not persist across restarts)');+}++app.use(session({+ secret: sessionSecret,+ resave: false,+ saveUninitialized: false,+ name: 'portracker.sid',+ cookie: {+ secure: false,+ httpOnly: true,+ maxAge: 24 * 60 * 60 * 1000,+ sameSite: 'lax'+ }+}));++logger.info('Session middleware configured');++if (isAuthEnabled()) {+ logger.info('Authentication is ENABLED - Login required for dashboard access');+} else {+ logger.info('Authentication is DISABLED - Dashboard is publicly accessible');+}++app.use(checkAuthEnabled);++app.use('/api/auth', authRoutes);+const PORT = process.env.PORT || 3000;/**@@ -1228,7 +1278,7 @@ function validateCustomServiceNameDeleteInput(req, res, next) {next();}-app.get("/api/servers", (req, res) => {+app.get("/api/servers", requireAuth, (req, res) => {logger.debug("GET /api/servers");try {const stmt = db.prepare(@@ -1246,7 +1296,7 @@ app.get("/api/servers", (req, res) => {}});-app.post("/api/servers", validateServerInput, (req, res) => {+app.post("/api/servers", requireAuth, validateServerInput, (req, res) => {const { id, label, url, parentId, type, unreachable, platform_type } =req.body;@@ -1325,7 +1375,7 @@ app.post("/api/servers", validateServerInput, (req, res) => {}});-app.delete("/api/servers/:id", validateServerIdParam, (req, res) => {+app.delete("/api/servers/:id", requireAuth, validateServerIdParam, (req, res) => {const serverId = req.params.id;const currentDebug = req.query.debug === "true";@@ -1391,7 +1441,7 @@ app.delete("/api/servers/:id", validateServerIdParam, (req, res) => {}});-app.post("/api/notes", validateNoteInput, (req, res) => {+app.post("/api/notes", requireAuth, validateNoteInput, (req, res) => {const { server_id, host_ip, host_port, protocol, note, container_id, internal } = req.body;const currentDebug = req.query.debug === "true";const noteTrimmed = note ? note.trim() : "";@@ -1440,7 +1490,7 @@ app.post("/api/notes", validateNoteInput, (req, res) => {}});-app.get("/api/notes", (req, res) => {+app.get("/api/notes", requireAuth, (req, res) => {const { server_id } = req.query;const currentDebug = req.query.debug === "true";@@ -1473,7 +1523,7 @@ app.get("/api/notes", (req, res) => {}});-app.post("/api/ignores", validateIgnoreInput, (req, res) => {+app.post("/api/ignores", requireAuth, validateIgnoreInput, (req, res) => {const { server_id, host_ip, host_port, protocol, ignored, container_id, internal } = req.body;const currentDebug = req.query.debug === "true";@@ -1523,7 +1573,7 @@ app.post("/api/ignores", validateIgnoreInput, (req, res) => {}});-app.get("/api/ignores", (req, res) => {+app.get("/api/ignores", requireAuth, (req, res) => {const { server_id } = req.query;const currentDebug = req.query.debug === "true";@@ -1557,7 +1607,7 @@ app.get("/api/ignores", (req, res) => {}});-app.post("/api/custom-service-names", validateCustomServiceNameInput, (req, res) => {+app.post("/api/custom-service-names", requireAuth, validateCustomServiceNameInput, (req, res) => {const { server_id, host_ip, host_port, protocol, custom_name, original_name, container_id, internal } = req.body;const currentDebug = req.query.debug === "true";@@ -1648,7 +1698,7 @@ app.post("/api/custom-service-names", validateCustomServiceNameInput, (req, res)}});-app.get("/api/custom-service-names", (req, res) => {+app.get("/api/custom-service-names", requireAuth, (req, res) => {const { server_id } = req.query;const currentDebug = req.query.debug === "true";@@ -1681,7 +1731,7 @@ app.get("/api/custom-service-names", (req, res) => {}});-app.delete("/api/custom-service-names", validateCustomServiceNameDeleteInput, (req, res) => {+app.delete("/api/custom-service-names", requireAuth, validateCustomServiceNameDeleteInput, (req, res) => {const { server_id, host_ip, host_port, protocol, container_id, internal } = req.body;const currentDebug = req.query.debug === "true";@@ -1752,7 +1802,7 @@ app.delete("/api/custom-service-names", validateCustomServiceNameDeleteInput, (r}});-app.post("/api/custom-service-names/batch", (req, res) => {+app.post("/api/custom-service-names/batch", requireAuth, (req, res) => {const { server_id, operations } = req.body;const currentDebug = req.query.debug === "true";@@ -1883,7 +1933,7 @@ app.post("/api/custom-service-names/batch", (req, res) => {}});-app.post("/api/notes/batch", (req, res) => {+app.post("/api/notes/batch", requireAuth, (req, res) => {const { server_id, operations } = req.body;const currentDebug = req.query.debug === "true";@@ -2378,6 +2428,11 @@ app.use((err, req, res, next) => {});logger.info(`About to call app.listen on port ${PORT}`);++if (isAuthEnabled() && recoveryManager.isRecoveryModeEnabled()) {+ recoveryManager.generateKey();+}+try {app.listen(PORT, "0.0.0.0", () => {logger.info(`Server is now listening on http://0.0.0.0:${PORT}`);diff --git a/backend/lib/recovery-manager.js b/backend/lib/recovery-manager.jsnew file mode 100644index 0000000..4ce9232--- /dev/null+++ b/backend/lib/recovery-manager.js@@ -0,0 +1,125 @@+/**+ * Recovery Key Manager+ *+ * Handles emergency account recovery when users are locked out.+ * Generates time-limited, single-use recovery keys.+ */++const crypto = require('crypto');+const { Logger } = require('./logger');++const logger = new Logger('RecoveryManager', { debug: process.env.DEBUG === 'true' });++const ADJECTIVES = [+ 'hungry',+ 'stellar',+ 'brisk',+ 'caffeinated',+ 'curious',+ 'wired',+ 'silent',+ 'vigilant',+ 'midnight',+ 'luminous',+ 'restless',+ 'velvet',+ 'electric',+ 'braided',+ 'sly'+];++const NOUNS = [+ 'otter',+ 'ferret',+ 'jaguar',+ 'lemur',+ 'heron',+ 'badger',+ 'chisel',+ 'daemon',+ 'antenna',+ 'pluto',+ 'vortex',+ 'relay',+ 'sparrow',+ 'circuit',+ 'capsule'+];++function capitalizeWord(word) {+ return word.charAt(0).toUpperCase() + word.slice(1);+}++function buildFriendlyKey() {+ const adjective = capitalizeWord(ADJECTIVES[Math.floor(Math.random() * ADJECTIVES.length)]);+ const noun = capitalizeWord(NOUNS[Math.floor(Math.random() * NOUNS.length)]);+ const suffix = crypto.randomBytes(2).toString('hex').toUpperCase();+ return `${adjective}${noun}${suffix}`;+}++class RecoveryManager {+ constructor() {+ this.recoveryKey = null;+ this.expiresAt = null;+ this.used = false;+ }++ isRecoveryModeEnabled() {+ return process.env.RECOVERY_MODE === 'true';+ }++ generateKey() {+ if (!this.isRecoveryModeEnabled()) {+ return null;+ }++ this.recoveryKey = buildFriendlyKey();+ this.expiresAt = Date.now() + (15 * 60 * 1000);+ this.used = false;++ this.displayKey();+ return this.recoveryKey;+ }++ displayKey() {+ const expiresIn = Math.max(1, Math.floor((this.expiresAt - Date.now()) / 60000));++ logger.info('');+ logger.warn('Recovery mode active - use any username with this code as the password:');+ logger.warn(` ${this.recoveryKey}`);+ logger.warn(` Expires in ${expiresIn} minute${expiresIn === 1 ? '' : 's'} - single use. Treat it like root.`);+ logger.info('');+ }++ validateKey(inputKey) {+ if (!this.recoveryKey || this.used) {+ return false;+ }++ if (Date.now() > this.expiresAt) {+ logger.warn('Recovery key has expired');+ this.invalidate();+ return false;+ }++ return inputKey === this.recoveryKey;+ }++ invalidate() {+ if (this.recoveryKey) {+ logger.info('Recovery key has been invalidated');+ this.recoveryKey = null;+ this.expiresAt = null;+ this.used = true;+ }+ }++ markAsUsed() {+ this.used = true;+ logger.info('Recovery key has been used successfully');+ }+}++module.exports = new RecoveryManager();++diff --git a/backend/middleware/auth.js b/backend/middleware/auth.jsnew file mode 100644index 0000000..ec3fb14--- /dev/null+++ b/backend/middleware/auth.js@@ -0,0 +1,80 @@+/**+ * Authentication Middleware+ *+ * Provides session management and authentication checking for Portracker.+ * Authentication can be enabled/disabled via ENABLE_AUTH environment variable.+ */++const { Logger } = require('../lib/logger');++const logger = new Logger('AuthMiddleware', { debug: process.env.DEBUG === 'true' });++/**+ * Check if authentication is enabled+ * Evaluated at runtime to allow dynamic configuration+ */+function isAuthEnabled() {+ return process.env.ENABLE_AUTH === 'true';+}++/**+ * Middleware to check if authentication is enabled in the system+ */+function checkAuthEnabled(req, res, next) {+ req.authEnabled = isAuthEnabled();+ next();+}++/**+ * Middleware to require authentication if enabled+ * If auth is disabled, allows request through+ * If auth is enabled, checks for valid session+ */+function requireAuth(req, res, next) {+ if (!isAuthEnabled()) {+ return next();+ }++ if (req.session && req.session.userId) {+ return next();+ }++ logger.debug('Unauthorized access attempt to protected endpoint:', req.path);+ return res.status(401).json({+ error: 'Authentication required',+ authEnabled: true+ });+}++/**+ * Middleware to optionally check authentication+ * Passes through regardless, but sets req.isAuthenticated flag+ */+function optionalAuth(req, res, next) {+ req.isAuthenticated = false;++ if (isAuthEnabled() && req.session && req.session.userId) {+ req.isAuthenticated = true;+ req.userId = req.session.userId;+ }++ next();+}++/**+ * Check if a user is currently logged in+ */+function isLoggedIn(req) {+ if (!isAuthEnabled()) {+ return true;+ }+ return !!(req.session && req.session.userId);+}++module.exports = {+ checkAuthEnabled,+ requireAuth,+ optionalAuth,+ isLoggedIn,+ isAuthEnabled+};diff --git a/backend/package-lock.json b/backend/package-lock.jsonindex 08fbf4f..2889fb8 100644--- a/backend/package-lock.json+++ b/backend/package-lock.json@@ -1,20 +1,24 @@{"name": "backend",- "version": "1.0.0",+ "version": "1.1.1","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "backend",- "version": "1.0.0",+ "version": "1.1.1","license": "ISC","dependencies": {"axios": "^1.9.0",+ "bcryptjs": "^2.4.3","better-sqlite3": "^11.10.0",+ "cookie-parser": "^1.4.6","cors": "^2.8.5","debug": "^4.4.1","dockerode": "^4.0.7",+ "dotenv": "^17.2.3","express": "^4.18.2",+ "express-session": "^1.18.0","node-fetch": "^3.3.2","ws": "^8.14.2"},@@ -261,6 +265,12 @@"tweetnacl": "^0.14.3"}},+ "node_modules/bcryptjs": {+ "version": "2.4.3",+ "resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-2.4.3.tgz",+ "integrity": "sha512-V/Hy/X9Vt7f3BbPJEi8BdVFMByHi+jNXrYkW3huaybV/kQ0KJg0Y6PkEMbn+zeT+i+SiKZ/HMqJGIIt4LZDqNQ==",+ "license": "MIT"+ },"node_modules/better-sqlite3": {"version": "11.10.0","resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-11.10.0.tgz",@@ -551,6 +561,28 @@"node": ">= 0.6"}},+ "node_modules/cookie-parser": {+ "version": "1.4.7",+ "resolved": "https://registry.npmjs.org/cookie-parser/-/cookie-parser-1.4.7.tgz",+ "integrity": "sha512-nGUvgXnotP3BsjiLX2ypbQnWoGUPIIfHQNZkkC668ntrzGWEZVW70HDEB1qnNGMicPje6EttlIgzo51YSwNQGw==",+ "license": "MIT",+ "dependencies": {+ "cookie": "0.7.2",+ "cookie-signature": "1.0.6"+ },+ "engines": {+ "node": ">= 0.8.0"+ }+ },+ "node_modules/cookie-parser/node_modules/cookie": {+ "version": "0.7.2",+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",+ "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },"node_modules/cookie-signature": {"version": "1.0.6","resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",@@ -704,6 +736,18 @@"node": ">= 8.0"}},+ "node_modules/dotenv": {+ "version": "17.2.3",+ "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.2.3.tgz",+ "integrity": "sha512-JVUnt+DUIzu87TABbhPmNfVdBDt18BLOWjMUFJMSi/Qqg7NTYtabbvSNJGOJ7afbRuv9D/lngizHtP7QyLQ+9w==",+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://dotenvx.com"+ }+ },"node_modules/dunder-proto": {"version": "1.0.1","resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",@@ -872,6 +916,55 @@"url": "https://opencollective.com/express"}},+ "node_modules/express-session": {+ "version": "1.18.2",+ "resolved": "https://registry.npmjs.org/express-session/-/express-session-1.18.2.tgz",+ "integrity": "sha512-SZjssGQC7TzTs9rpPDuUrR23GNZ9+2+IkA/+IJWmvQilTr5OSliEHGF+D9scbIpdC6yGtTI0/VhaHoVes2AN/A==",+ "license": "MIT",+ "dependencies": {+ "cookie": "0.7.2",+ "cookie-signature": "1.0.7",+ "debug": "2.6.9",+ "depd": "~2.0.0",+ "on-headers": "~1.1.0",+ "parseurl": "~1.3.3",+ "safe-buffer": "5.2.1",+ "uid-safe": "~2.1.5"+ },+ "engines": {+ "node": ">= 0.8.0"+ }+ },+ "node_modules/express-session/node_modules/cookie": {+ "version": "0.7.2",+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",+ "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/express-session/node_modules/cookie-signature": {+ "version": "1.0.7",+ "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz",+ "integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==",+ "license": "MIT"+ },+ "node_modules/express-session/node_modules/debug": {+ "version": "2.6.9",+ "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",+ "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",+ "license": "MIT",+ "dependencies": {+ "ms": "2.0.0"+ }+ },+ "node_modules/express-session/node_modules/ms": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",+ "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",+ "license": "MIT"+ },"node_modules/express/node_modules/debug": {"version": "2.6.9","resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",@@ -1586,6 +1679,15 @@"node": ">= 0.8"}},+ "node_modules/on-headers": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.1.0.tgz",+ "integrity": "sha512-737ZY3yNnXy37FHkQxPzt4UZ2UWPWiCZWLvFZ4fu5cueciegX0zGPnrlY6bwRg4FdQOe9YU8MkmJwGhoMybl8A==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },"node_modules/once": {"version": "1.4.0","resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",@@ -1724,6 +1826,15 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/random-bytes": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/random-bytes/-/random-bytes-1.0.0.tgz",+ "integrity": "sha512-iv7LhNVO047HzYR3InF6pUcUsPQiHTM1Qal51DcGSuZFBil1aBBWG5eHPNek7bvILMaYJ/8RU1e8w1AMdHmLQQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },"node_modules/range-parser": {"version": "1.2.1","resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",@@ -2216,6 +2327,18 @@"node": ">= 0.6"}},+ "node_modules/uid-safe": {+ "version": "2.1.5",+ "resolved": "https://registry.npmjs.org/uid-safe/-/uid-safe-2.1.5.tgz",+ "integrity": "sha512-KPHm4VL5dDXKz01UuEd88Df+KzynaohSL9fBh096KWAxSKZQDI2uBrVqtvRM4rwrIrRRKsdLNML/lnaaVSRioA==",+ "license": "MIT",+ "dependencies": {+ "random-bytes": "~1.0.0"+ },+ "engines": {+ "node": ">= 0.8"+ }+ },"node_modules/undefsafe": {"version": "2.0.5","resolved": "https://registry.npmjs.org/undefsafe/-/undefsafe-2.0.5.tgz",diff --git a/backend/package.json b/backend/package.jsonindex cec9ecf..62bed22 100644--- a/backend/package.json+++ b/backend/package.json@@ -15,11 +15,15 @@"type": "commonjs","dependencies": {"axios": "^1.9.0",+ "bcryptjs": "^2.4.3","better-sqlite3": "^11.10.0",+ "cookie-parser": "^1.4.6","cors": "^2.8.5","debug": "^4.4.1","dockerode": "^4.0.7",+ "dotenv": "^17.2.3","express": "^4.18.2",+ "express-session": "^1.18.0","node-fetch": "^3.3.2","ws": "^8.14.2"},diff --git a/backend/routes/auth.js b/backend/routes/auth.jsnew file mode 100644index 0000000..c624bd9--- /dev/null+++ b/backend/routes/auth.js@@ -0,0 +1,319 @@+/**+ * Authentication Routes+ *+ * Handles user authentication including login, logout, and initial setup.+ * All endpoints use session-based authentication with bcrypt password hashing.+ */++const express = require('express');+const bcrypt = require('bcryptjs');+const crypto = require('crypto');+const db = require('../db');+const { Logger } = require('../lib/logger');+const { isAuthEnabled } = require('../middleware/auth');+const recoveryManager = require('../lib/recovery-manager');++const router = express.Router();+const logger = new Logger('AuthRoutes', { debug: process.env.DEBUG === 'true' });++router.get('/status', (req, res) => {+ try {+ if (!isAuthEnabled()) {+ return res.json({+ authEnabled: false,+ authenticated: true,+ setupRequired: false+ });+ }++ let userCount;+ try {+ userCount = db.prepare('SELECT COUNT(*) as count FROM users').get();+ } catch (err) {+ logger.warn('Users table does not exist yet, setup required:', err.message);+ return res.json({+ authEnabled: true,+ authenticated: false,+ setupRequired: true+ });+ }++ const setupRequired = userCount.count === 0;+ const authenticated = !!(req.session && req.session.userId);++ res.json({+ authEnabled: true,+ authenticated,+ setupRequired,+ username: authenticated ? req.session.username : null+ });+ } catch (error) {+ logger.error('Error checking auth status:', error.message);+ res.status(500).json({ error: 'Failed to check authentication status' });+ }+});++router.post('/setup', async (req, res) => {+ try {+ if (!isAuthEnabled()) {+ return res.status(400).json({ error: 'Authentication is not enabled' });+ }++ const { username, password } = req.body;++ if (!username || !password) {+ return res.status(400).json({ error: 'Username and password are required' });+ }++ if (typeof username !== 'string' || username.trim().length < 3) {+ return res.status(400).json({ error: 'Username must be at least 3 characters' });+ }++ if (typeof password !== 'string' || password.length < 8) {+ return res.status(400).json({ error: 'Password must be at least 8 characters' });+ }++ let userCount;+ try {+ userCount = db.prepare('SELECT COUNT(*) as count FROM users').get();+ } catch (dbError) {+ logger.error('Users table does not exist:', dbError.message);+ return res.status(500).json({ error: 'Database not initialized' });+ }++ if (userCount.count > 0) {+ return res.status(400).json({ error: 'Setup already completed' });+ }++ const passwordHash = await bcrypt.hash(password, 10);+ const userId = crypto.randomUUID();+ const now = Date.now();++ db.prepare(+ 'INSERT INTO users (id, username, password_hash, created_at, last_login) VALUES (?, ?, ?, ?, ?)'+ ).run(userId, username.trim(), passwordHash, now, now);++ req.session.regenerate((err) => {+ if (err) {+ logger.error('Session regeneration failed:', err.message);+ return res.status(500).json({ error: 'Setup failed' });+ }++ req.session.userId = userId;+ req.session.username = username.trim();++ req.session.save((saveErr) => {+ if (saveErr) {+ logger.error('Session save failed:', saveErr.message);+ return res.status(500).json({ error: 'Setup failed' });+ }++ logger.info(`Initial admin user created: ${username.trim()}`);++ res.json({+ success: true,+ message: 'Setup completed successfully',+ username: username.trim()+ });+ });+ });+ } catch (error) {+ logger.error('Error during setup:', error.message);+ res.status(500).json({ error: 'Setup failed' });+ }+});++router.post('/login', async (req, res) => {+ try {+ if (!isAuthEnabled()) {+ return res.status(400).json({ error: 'Authentication is not enabled' });+ }++ const { username, password } = req.body;++ if (!username || !password) {+ return res.status(400).json({ error: 'Username and password are required' });+ }++ const trimmedUsername = typeof username === 'string' ? username.trim() : username;++ const isRecoveryKey = recoveryManager.validateKey(password);++ if (isRecoveryKey) {+ let user;+ try {+ user = db.prepare('SELECT * FROM users LIMIT 1').get();+ } catch (dbError) {+ logger.error('Database error during recovery:', dbError.message);+ return res.status(500).json({ error: 'Recovery failed' });+ }++ if (!user) {+ return res.status(400).json({ error: 'No users found in database' });+ }++ recoveryManager.markAsUsed();++ req.session.regenerate((err) => {+ if (err) {+ logger.error('Session regeneration failed:', err.message);+ return res.status(500).json({ error: 'Recovery failed' });+ }++ req.session.userId = user.id;+ req.session.username = user.username;+ req.session.requirePasswordChange = true;++ req.session.save((saveErr) => {+ if (saveErr) {+ logger.error('Session save failed:', saveErr.message);+ return res.status(500).json({ error: 'Recovery failed' });+ }++ logger.info(`Recovery key used for user: ${user.username}`);++ return res.json({+ success: true,+ username: user.username,+ requirePasswordChange: true+ });+ });+ });+ return;+ }++ let user;+ try {+ user = db.prepare('SELECT * FROM users WHERE username = ?').get(trimmedUsername);+ } catch (dbError) {+ logger.error('Database error during login:', dbError.message);+ return res.status(500).json({ error: 'Login failed' });+ }++ const hashToCompare = user ? user.password_hash : '$2a$10$AAAAAAAAAAAAAAAAAAAAAA.AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';+ const isValid = await bcrypt.compare(password, hashToCompare);++ if (!user || !isValid) {+ logger.debug(`Failed login attempt for user: ${trimmedUsername}`);+ return res.status(401).json({ error: 'Invalid credentials' });+ }++ db.prepare('UPDATE users SET last_login = ? WHERE id = ?').run(Date.now(), user.id);++ req.session.regenerate((err) => {+ if (err) {+ logger.error('Session regeneration failed:', err.message);+ return res.status(500).json({ error: 'Login failed' });+ }++ req.session.userId = user.id;+ req.session.username = user.username;++ req.session.save((saveErr) => {+ if (saveErr) {+ logger.error('Session save failed:', saveErr.message);+ return res.status(500).json({ error: 'Login failed' });+ }++ logger.info(`User logged in: ${user.username}`);++ res.json({+ success: true,+ username: user.username+ });+ });+ });+ } catch (error) {+ logger.error('Error during login:', error.message);+ res.status(500).json({ error: 'Login failed' });+ }+});++router.post('/logout', (req, res) => {+ const username = req.session?.username;++ req.session.destroy((err) => {+ if (err) {+ logger.error('Error destroying session:', err.message);+ return res.status(500).json({ error: 'Logout failed' });+ }++ if (username) {+ logger.info(`User logged out: ${username}`);+ }++ res.json({ success: true, message: 'Logged out successfully' });+ });+});++router.post('/change-password', async (req, res) => {+ try {+ if (!isAuthEnabled()) {+ return res.status(400).json({ error: 'Authentication is not enabled' });+ }++ if (!req.session || !req.session.userId) {+ return res.status(401).json({ error: 'Not authenticated' });+ }++ const { currentPassword, newPassword } = req.body;++ if (!newPassword) {+ return res.status(400).json({ error: 'New password is required' });+ }++ if (typeof newPassword !== 'string' || newPassword.length < 8) {+ return res.status(400).json({ error: 'Password must be at least 8 characters' });+ }++ const requirePasswordChange = req.session.requirePasswordChange;++ if (!requirePasswordChange && !currentPassword) {+ return res.status(400).json({ error: 'Current password is required' });+ }++ let user;+ try {+ user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.session.userId);+ } catch (dbError) {+ logger.error('Database error during password change:', dbError.message);+ return res.status(500).json({ error: 'Password change failed' });+ }++ if (!user) {+ return res.status(404).json({ error: 'User not found' });+ }++ if (!requirePasswordChange) {+ const isValidCurrent = await bcrypt.compare(currentPassword, user.password_hash);+ if (!isValidCurrent) {+ return res.status(401).json({ error: 'Current password is incorrect' });+ }+ }++ const passwordHash = await bcrypt.hash(newPassword, 10);++ db.prepare('UPDATE users SET password_hash = ? WHERE id = ?').run(passwordHash, user.id);++ delete req.session.requirePasswordChange;++ req.session.save((saveErr) => {+ if (saveErr) {+ logger.error('Session save failed:', saveErr.message);+ return res.status(500).json({ error: 'Password change failed' });+ }++ logger.info(`Password changed for user: ${user.username}`);++ res.json({+ success: true,+ message: 'Password changed successfully'+ });+ });+ } catch (error) {+ logger.error('Error during password change:', error.message);+ res.status(500).json({ error: 'Password change failed' });+ }+});++module.exports = router;diff --git a/docker-compose.yml b/docker-compose.ymlindex 651dcbe..0078610 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -52,6 +52,15 @@ services:# - TrueNAS-specific optimizations# - TRUENAS_API_KEY=your-api-key-here+ # AUTHENTICATION (Optional - v1.2.0+)+ # Enable authentication to protect dashboard access+ # When enabled, users must login to access the dashboard+ # Note: API endpoints for peer communication remain accessible+ # - ENABLE_AUTH=true+ # Optional: Set a custom session secret (recommended for production)+ # If not set, a random secret is generated (sessions won't persist across restarts)+ # - SESSION_SECRET=your-random-secret-here-change-this+# PERFORMANCE SETTINGS (Optional)# Cache duration - increase for better performance, decrease for fresher data# - CACHE_TIMEOUT_MS=60000diff --git a/eslint.config.cjs b/eslint.config.cjsindex cfde90b..bb953b8 100644--- a/eslint.config.cjs+++ b/eslint.config.cjs@@ -8,7 +8,7 @@ try { reactPlugin = require('eslint-plugin-react'); } catch { reactPlugin = nullconst logsPlugin = {rules: {'no-line-comments': {- meta: { type: 'problem', docs: { description: 'Disallow // line comments; use block comments or remove' } },+ meta: { type: 'problem', docs: { description: 'Disallow comments; remove them' } },create(context) {const allowList = [/^eslint[- ]/i,@@ -22,15 +22,16 @@ const logsPlugin = {const sourceCode = context.sourceCode || context.getSourceCode();const comments = sourceCode.getAllComments();for (const c of comments) {- if (c.type === 'Line') {- const text = String(c.value || '').trim();- const allowed = allowList.some((re) => re.test(text));- if (!allowed) {- context.report({- loc: c.loc,- message: 'Line comments (//) are disallowed. Convert to a block comment (/* */) if this is essential documentation, or remove the comment.',- });- }+ const text = String(c.value || '').trim();+ const allowed = allowList.some((re) => re.test(text));+ // Allow JSDoc comments (start with *)+ const isJSDoc = c.type === 'Block' && text.startsWith('*');++ if (!allowed && !isJSDoc) {+ context.report({+ loc: c.loc,+ message: 'Comments are disallowed. Remove the comment.',+ });}}},diff --git a/frontend/package-lock.json b/frontend/package-lock.jsonindex a3e28bc..2e440c5 100644--- a/frontend/package-lock.json+++ b/frontend/package-lock.json@@ -1,12 +1,12 @@{"name": "frontend",- "version": "0.0.0",+ "version": "1.1.1","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "frontend",- "version": "0.0.0",+ "version": "1.1.1","dependencies": {"@radix-ui/react-accordion": "^1.2.0","@radix-ui/react-alert-dialog": "^1.1.14",@@ -2738,9 +2738,9 @@}},"node_modules/caniuse-lite": {- "version": "1.0.30001724",- "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001724.tgz",- "integrity": "sha512-WqJo7p0TbHDOythNTqYujmaJTvtYRZrjpP8TCvH6Vb9CYJerJNKamKzIWOM4BkQatWj9H2lYulpdAQNBe7QhNA==",+ "version": "1.0.30001755",+ "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001755.tgz",+ "integrity": "sha512-44V+Jm6ctPj7R52Na4TLi3Zri4dWUljJd+RDm+j8LtNCc/ihLCT+X1TzoOAkRETEWqjuLnh9581Tl80FvK7jVA==","dev": true,"funding": [{diff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex 9768ba1..da5007c 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -1,4 +1,4 @@-import React, { useEffect, useState, useCallback } from "react";+import React, { useEffect, useState, useCallback, useMemo, useRef } from "react";import { TooltipProvider } from "@/components/ui/tooltip";import {Dialog,@@ -22,25 +22,46 @@ import { BatchOperationsBar } from "./components/server/BatchOperationsBar";import { BatchRenameModal } from "./components/server/BatchRenameModal";import { BatchHideModal } from "./components/server/BatchHideModal";import { BatchNotesModal } from "./components/server/BatchNotesModal";+import { LoginPage } from "./components/auth/LoginPage";+import { ChangePasswordPage } from "./components/auth/ChangePasswordPage";import { BarChart3 } from "lucide-react";import Logger from "./lib/logger";import { useWhatsNew } from "./lib/hooks/useWhatsNew";import { saveCustomServiceName, deleteCustomServiceName, getCustomServiceNames, batchCustomServiceNames } from "./lib/api/customServiceNames";import { batchNotes, saveNote } from "./lib/api/notes";import { generatePortKey } from "./lib/utils/portUtils";+import { formatUptime } from "@/lib/utils";+import { useAuth } from "./contexts/AuthContext";+import { buildAutoRefreshMessages } from "@/lib/autoRefreshMessages";const keyOf = (srvId, p) => generatePortKey(srvId, p);const logger = new Logger('App');+const KONAMI_SEQUENCE = [+ "ArrowUp",+ "ArrowUp",+ "ArrowDown",+ "ArrowDown",+ "ArrowLeft",+ "ArrowRight",+ "ArrowLeft",+ "ArrowRight",+ "b",+ "a"+];++const KONAMI_HINTS = ["↑", "Course input detected…", "gg, keyboard pilot."];+export default function App() {+ const auth = useAuth();+ const { shouldShowButton: shouldShowWhatsNewButton, handleShow: handleShowWhatsNew, getModalProps: getWhatsNewModalProps } = useWhatsNew();+const [groups, setGroups] = useState([]);const [loading, setLoading] = useState(true);const [error, setError] = useState(null);- const { shouldShowButton: shouldShowWhatsNewButton, handleShow: handleShowWhatsNew, getModalProps: getWhatsNewModalProps } = useWhatsNew();-const [noteModalOpen, setNoteModalOpen] = useState(false);const [modalSrvId, setModalSrvId] = useState("");const [modalPort, setModalPort] = useState(null);@@ -55,6 +76,85 @@ export default function App() {const [batchNotesModalOpen, setBatchNotesModalOpen] = useState(false);const [batchLoading, setBatchLoading] = useState(false);const [renameLoading, setRenameLoading] = useState(false);+ const [hackerMode, setHackerMode] = useState(() => {+ try {+ return localStorage.getItem("portracker_hacker_mode") === "true";+ } catch {+ return false;+ }+ });+ const [konamiHint, setKonamiHint] = useState(null);+ const konamiProgressRef = useRef(0);+ const konamiHintStageRef = useRef(0);+ const konamiHintTimeoutRef = useRef(null);+ const [healthToast, setHealthToast] = useState(null);+ const healthToastTimeoutRef = useRef(null);++ const showKonamiHint = useCallback((stage) => {+ const index = Math.min(stage, KONAMI_HINTS.length - 1);+ setKonamiHint(KONAMI_HINTS[index]);+ if (konamiHintTimeoutRef.current) {+ clearTimeout(konamiHintTimeoutRef.current);+ }+ konamiHintTimeoutRef.current = setTimeout(() => setKonamiHint(null), 1200);+ }, []);++ useEffect(() => () => {+ if (konamiHintTimeoutRef.current) {+ clearTimeout(konamiHintTimeoutRef.current);+ }+ }, []);++ useEffect(() => () => {+ if (healthToastTimeoutRef.current) {+ clearTimeout(healthToastTimeoutRef.current);+ }+ }, []);++ const pushHealthToast = useCallback((payload) => {+ setHealthToast(payload);+ if (healthToastTimeoutRef.current) {+ clearTimeout(healthToastTimeoutRef.current);+ }+ healthToastTimeoutRef.current = setTimeout(() => setHealthToast(null), 4000);+ }, []);++ const toggleHackerMode = useCallback(() => {+ setHackerMode(prev => {+ const next = !prev;+ pushHealthToast({+ type: "info",+ message: next+ ? "Hacker mode activated. Use Ctrl+Shift+H to toggle."+ : "Hacker mode disabled."+ });+ return next;+ });+ konamiHintStageRef.current = 0;+ konamiProgressRef.current = 0;+ }, [pushHealthToast]);++ const disableHackerMode = useCallback(() => {+ setHackerMode(prev => {+ if (!prev) return prev;+ pushHealthToast({+ type: "info",+ message: "Hacker mode disabled."+ });+ return false;+ });+ konamiHintStageRef.current = 0;+ konamiProgressRef.current = 0;+ }, [pushHealthToast]);++ useEffect(() => {+ try {+ localStorage.setItem("portracker_hacker_mode", hackerMode ? "true" : "false");+ } catch { void 0; }+ if (typeof document !== "undefined") {+ document.body.classList.toggle("hacker-mode", hackerMode);+ }+ }, [hackerMode]);const [actionFeedback, setActionFeedback] = useState({copy: null,@@ -157,6 +257,15 @@ export default function App() {const [selectionMode, setSelectionMode] = useState(false);const [selectedPorts, setSelectedPorts] = useState(new Set());+ const [autoRefreshEnabled, setAutoRefreshEnabled] = useState(() => {+ try {+ const saved = localStorage.getItem("autoRefreshEnabled");+ return saved === "true";+ } catch {+ return false;+ }+ });+useEffect(() => {if (isDarkMode) {document.documentElement.classList.add("dark");@@ -234,6 +343,14 @@ export default function App() {}}, [searchScope]);+ useEffect(() => {+ try {+ localStorage.setItem("autoRefreshEnabled", autoRefreshEnabled.toString());+ } catch (error) {+ logger.warn("Failed to save auto-refresh setting:", error);+ }+ }, [autoRefreshEnabled]);+const handleSelectServer = useCallback((serverId) => {setSelectedServer(serverId);if (window.innerWidth < 768) {@@ -580,8 +697,11 @@ export default function App() {useEffect(() => {+ if (auth.loading || (auth.authEnabled && !auth.authenticated)) {+ return;+ }fetchAll();- }, [fetchAll]);+ }, [fetchAll, auth.loading, auth.authEnabled, auth.authenticated]);useEffect(() => {try {@@ -593,6 +713,25 @@ export default function App() {} catch { void 0; }}, []);+ useEffect(() => {+ if (auth.authenticated && !auth.loading && groups.length === 0) {+ fetchAll();+ }+ }, [auth.authenticated, auth.loading, fetchAll, groups.length]);++ useEffect(() => {+ if (!autoRefreshEnabled || auth.loading || (auth.authEnabled && !auth.authenticated)) {+ return;+ }++ const intervalId = setInterval(() => {+ logger.debug('Auto-refresh triggered');+ fetchAll();+ }, 30000);++ return () => clearInterval(intervalId);+ }, [autoRefreshEnabled, fetchAll, auth.loading, auth.authEnabled, auth.authenticated]);+useEffect(() => {if (!loading && groups.length > 0) {const selectionIsValid =@@ -623,6 +762,43 @@ export default function App() {} catch { void 0; }}, [selectedServer, deepLinkContainer]);+ useEffect(() => {+ if (typeof window === "undefined") return;+ const handleKeyDown = (event) => {+ if (event.ctrlKey && event.shiftKey && event.key.toLowerCase() === "h") {+ event.preventDefault();+ toggleHackerMode();+ return;+ }++ if (event.key === "ArrowUp" && konamiProgressRef.current === 0) {+ const stage = konamiHintStageRef.current;+ if (stage < KONAMI_HINTS.length) {+ showKonamiHint(stage);+ konamiHintStageRef.current = stage + 1;+ }+ }++ const normalized = event.key.length === 1 ? event.key.toLowerCase() : event.key;+ const expected = KONAMI_SEQUENCE[konamiProgressRef.current];++ if (normalized === expected) {+ konamiProgressRef.current += 1;+ if (konamiProgressRef.current === KONAMI_SEQUENCE.length) {+ konamiProgressRef.current = 0;+ toggleHackerMode();+ return;+ }+ return;+ }++ konamiProgressRef.current = normalized === KONAMI_SEQUENCE[0] ? 1 : 0;+ };++ window.addEventListener("keydown", handleKeyDown);+ return () => window.removeEventListener("keydown", handleKeyDown);+ }, [showKonamiHint, toggleHackerMode]);+const handleContainerOpen = useCallback((serverId, containerId) => {setDeepLinkContainer(containerId);try {@@ -1410,6 +1586,29 @@ export default function App() {setSelectionMode(true);}, []);+ const handleLogoHealthCheck = useCallback(async () => {+ const started = performance.now();+ try {+ const response = await fetch("/api/health");+ const latency = Math.round(performance.now() - started);+ if (!response.ok) {+ throw new Error(`HTTP ${response.status}`);+ }+ const data = await response.json();+ const uptimeSeconds = data?.uptimeSeconds ?? Math.floor(data?.uptime || 0);+ const uptimeLabel = uptimeSeconds ? formatUptime(uptimeSeconds) : "unknown";+ pushHealthToast({+ type: "success",+ message: `Heartbeat steady: ${latency}ms - uptime ${uptimeLabel}`,+ });+ } catch (error) {+ pushHealthToast({+ type: "error",+ message: `Health check failed: ${error.message}`,+ });+ }+ }, [pushHealthToast]);+const handleBatchRename = useCallback(() => {setBatchRenameModalOpen(true);}, []);@@ -1426,6 +1625,47 @@ export default function App() {fetchServers();}, [fetchServers]);+ const selectedServerData = useMemo(() => {+ if (!selectedServer) return null;+ return groups.find((g) => g.id === selectedServer) || null;+ }, [groups, selectedServer]);++ const appPort = useMemo(() => {+ if (typeof window === "undefined") {+ return "4999";+ }+ return window.location.port || "4999";+ }, []);++ const autoRefreshMessages = useMemo(() => {+ const isTrueNAS = Boolean(+ selectedServerData?.platformName?.toLowerCase().includes("truenas")+ );+ return buildAutoRefreshMessages({+ isTrueNAS,+ currentPort: appPort || "4999",+ });+ }, [selectedServerData, appPort]);++ if (auth.loading) {+ return (+ <div className="min-h-screen flex items-center justify-center bg-slate-50 dark:bg-slate-950">+ <div className="text-center">+ <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>+ <p className="text-slate-600 dark:text-slate-400">Loading...</p>+ </div>+ </div>+ );+ }++ if (auth.authEnabled && !auth.authenticated) {+ return <LoginPage />;+ }++ if (auth.requirePasswordChange) {+ return <ChangePasswordPage />;+ }+const filterPorts = (group) => {if (!group.ok || !group.data) return group;@@ -1571,14 +1811,38 @@ export default function App() {));}- const serverToRender = selectedServer- ? groups.find((g) => g.id === selectedServer)- : null;+ const serverToRender = selectedServerData;const noDataForSelection = selectedServer && !serverToRender && !loading;return (<TooltipProvider>- <div className="flex flex-col h-screen bg-slate-50 dark:bg-slate-950">+ {konamiHint && (+ <div className="fixed top-20 left-1/2 -translate-x-1/2 z-50 px-4 py-2 rounded-lg shadow-lg border backdrop-blur-sm pointer-events-none animate-in fade-in-0 slide-in-from-top-2 duration-200 bg-white/95 dark:bg-slate-800/95 border-slate-200 dark:border-slate-700 text-slate-900 dark:text-slate-100">+ <div className="flex items-center gap-2">+ <div className="flex-shrink-0 w-1.5 h-1.5 rounded-full bg-indigo-500 dark:bg-indigo-400 animate-pulse" />+ <span className="text-sm font-medium">{konamiHint}</span>+ </div>+ </div>+ )}+ {healthToast && (+ <div+ className={`fixed top-20 right-6 z-50 px-4 py-2.5 rounded-lg shadow-lg border backdrop-blur-sm animate-in fade-in-0 slide-in-from-top-2 duration-200 ${+ healthToast.type === "error"+ ? "bg-rose-50/95 dark:bg-rose-900/95 border-rose-200 dark:border-rose-800 text-rose-900 dark:text-rose-100"+ : "bg-white/95 dark:bg-slate-800/95 border-slate-200 dark:border-slate-700 text-slate-900 dark:text-slate-100"+ }`}+ >+ <div className="flex items-center gap-2">+ {healthToast.type === "error" ? (+ <div className="flex-shrink-0 w-1.5 h-1.5 rounded-full bg-rose-500 dark:bg-rose-400" />+ ) : (+ <div className="flex-shrink-0 w-1.5 h-1.5 rounded-full bg-indigo-500 dark:bg-indigo-400" />+ )}+ <span className="text-sm font-medium">{healthToast.message}</span>+ </div>+ </div>+ )}+ <div className={`flex flex-col h-screen bg-slate-50 dark:bg-slate-950 ${hackerMode ? "hacker-mode-active" : ""}`}><AppHeadergroups={groups}loading={loading}@@ -1599,6 +1863,12 @@ export default function App() {onToggleSidebar={() => setSidebarOpen(!isSidebarOpen)}onShowWhatsNew={shouldShowWhatsNewButton ? handleShowWhatsNew : null}hasNewFeatures={shouldShowWhatsNewButton}+ autoRefreshEnabled={autoRefreshEnabled}+ onAutoRefreshToggle={() => setAutoRefreshEnabled(!autoRefreshEnabled)}+ onLogoLongPress={handleLogoHealthCheck}+ hackerMode={hackerMode}+ onDisableHackerMode={disableHackerMode}+ autoRefreshMessages={autoRefreshMessages}/><DashboardLayoutisSidebarOpen={isSidebarOpen}@@ -1822,3 +2092,6 @@ export default function App() {}}}+++diff --git a/frontend/src/components/auth/ChangePasswordModal.jsx b/frontend/src/components/auth/ChangePasswordModal.jsxnew file mode 100644index 0000000..017ae8b--- /dev/null+++ b/frontend/src/components/auth/ChangePasswordModal.jsx@@ -0,0 +1,174 @@+import React, { useState } from 'react';+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogDescription,+} from '@/components/ui/dialog';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import { AlertCircle } from 'lucide-react';++export function ChangePasswordModal({ open, onClose, requirePasswordChange = false }) {+ const [currentPassword, setCurrentPassword] = useState('');+ const [newPassword, setNewPassword] = useState('');+ const [confirmPassword, setConfirmPassword] = useState('');+ const [error, setError] = useState('');+ const [loading, setLoading] = useState(false);++ const handleSubmit = async (e) => {+ e.preventDefault();+ setError('');++ if (newPassword.length < 8) {+ setError('Password must be at least 8 characters');+ return;+ }++ if (newPassword !== confirmPassword) {+ setError('Passwords do not match');+ return;+ }++ setLoading(true);++ try {+ const body = requirePasswordChange+ ? { newPassword }+ : { currentPassword, newPassword };++ const response = await fetch('/api/auth/change-password', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify(body),+ });++ const data = await response.json();++ if (!response.ok) {+ setError(data.error || 'Password change failed');+ setLoading(false);+ return;+ }++ onClose(true);+ } catch (error) {+ setError(error.message || 'Network error');+ setLoading(false);+ }+ };++ return (+ <Dialog open={open} onOpenChange={requirePasswordChange ? undefined : onClose}>+ <DialogContent className="sm:max-w-md" onInteractOutside={(e) => requirePasswordChange && e.preventDefault()}>+ <DialogHeader>+ <DialogTitle>+ {requirePasswordChange ? 'Set New Password' : 'Change Password'}+ </DialogTitle>+ <DialogDescription>+ {requirePasswordChange+ ? 'You must set a new password to continue'+ : 'Update your account password'}+ </DialogDescription>+ </DialogHeader>++ {requirePasswordChange && (+ <div className="flex items-start gap-3 p-3 rounded-lg bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-900">+ <AlertCircle className="w-5 h-5 text-amber-600 dark:text-amber-400 mt-0.5 flex-shrink-0" />+ <p className="text-sm text-amber-800 dark:text-amber-200">+ Recovery mode was used. Please set a new secure password.+ </p>+ </div>+ )}++ <form onSubmit={handleSubmit} className="space-y-4">+ {!requirePasswordChange && (+ <div className="space-y-2">+ <Label htmlFor="currentPassword">Current Password</Label>+ <Input+ id="currentPassword"+ type="password"+ value={currentPassword}+ onChange={(e) => setCurrentPassword(e.target.value)}+ placeholder="Enter current password"+ required+ autoComplete="current-password"+ disabled={loading}+ />+ </div>+ )}++ <div className="space-y-2">+ <Label htmlFor="newPassword">New Password</Label>+ <Input+ id="newPassword"+ type="password"+ value={newPassword}+ onChange={(e) => setNewPassword(e.target.value)}+ placeholder="At least 8 characters"+ required+ autoComplete="new-password"+ disabled={loading}+ />+ {newPassword && (+ <p className="text-xs text-slate-500 dark:text-slate-400">+ {newPassword.length >= 8 ? (+ <span className="text-green-600 dark:text-green-400">✓ Valid password</span>+ ) : (+ <span>At least 8 characters required</span>+ )}+ </p>+ )}+ </div>++ <div className="space-y-2">+ <Label htmlFor="confirmPassword">Confirm New Password</Label>+ <Input+ id="confirmPassword"+ type="password"+ value={confirmPassword}+ onChange={(e) => setConfirmPassword(e.target.value)}+ placeholder="Re-enter new password"+ required+ autoComplete="new-password"+ disabled={loading}+ />+ {confirmPassword && (+ <p className="text-xs">+ {newPassword === confirmPassword ? (+ <span className="text-green-600 dark:text-green-400">✓ Passwords match</span>+ ) : (+ <span className="text-red-600 dark:text-red-400">✗ Passwords do not match</span>+ )}+ </p>+ )}+ </div>++ {error && (+ <div className="p-3 rounded-md bg-red-50 dark:bg-red-950/30 border border-red-200 dark:border-red-900">+ <p className="text-sm text-red-800 dark:text-red-200">{error}</p>+ </div>+ )}++ <div className="flex gap-3 justify-end">+ {!requirePasswordChange && (+ <Button type="button" variant="outline" onClick={() => onClose(false)} disabled={loading}>+ Cancel+ </Button>+ )}+ <Button+ type="submit"+ disabled={loading || newPassword.length < 8 || newPassword !== confirmPassword}+ className="bg-indigo-600 hover:bg-indigo-700 text-white"+ >+ {loading ? 'Changing...' : 'Change Password'}+ </Button>+ </div>+ </form>+ </DialogContent>+ </Dialog>+ );+}diff --git a/frontend/src/components/auth/ChangePasswordPage.jsx b/frontend/src/components/auth/ChangePasswordPage.jsxnew file mode 100644index 0000000..7d2d539--- /dev/null+++ b/frontend/src/components/auth/ChangePasswordPage.jsx@@ -0,0 +1,132 @@+import React, { useState } from 'react';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import { AlertCircle, Shield } from 'lucide-react';+import Logo from '@/components/Logo';+import { useAuth } from '@/contexts/AuthContext';++export function ChangePasswordPage() {+ const { changePassword } = useAuth();+ const [newPassword, setNewPassword] = useState('');+ const [confirmPassword, setConfirmPassword] = useState('');+ const [error, setError] = useState('');+ const [loading, setLoading] = useState(false);++ const handleSubmit = async (e) => {+ e.preventDefault();+ setError('');++ if (newPassword.length < 8) {+ setError('Password must be at least 8 characters');+ return;+ }++ if (newPassword !== confirmPassword) {+ setError('Passwords do not match');+ return;+ }++ setLoading(true);++ const result = await changePassword(null, newPassword);++ if (!result.success) {+ setError(result.error);+ setLoading(false);+ }+ };++ return (+ <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 to-slate-100 dark:from-slate-950 dark:to-slate-900 px-4">+ <div className="w-full max-w-md">+ <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-xl border border-slate-200 dark:border-slate-700 p-8">+ <div className="flex flex-col items-center mb-8">+ <div className="relative group mb-4">+ <Logo size="lg" className="transition-transform duration-300 group-hover:rotate-[30deg]" />+ <div className="absolute -top-1 -right-1 bg-amber-500 text-white rounded-full p-1.5 shadow-lg transform transition-transform duration-300 group-hover:scale-110">+ <Shield className="w-4 h-4" />+ </div>+ </div>+ <h1 className="text-2xl font-bold text-slate-900 dark:text-white">+ Password Change Required+ </h1>+ <p className="text-sm text-slate-600 dark:text-slate-400 mt-1">+ Set a new secure password to continue+ </p>+ </div>++ <div className="flex items-start gap-3 p-3 rounded-lg bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-900 mb-6">+ <AlertCircle className="w-5 h-5 text-amber-600 dark:text-amber-400 mt-0.5 flex-shrink-0" />+ <p className="text-sm text-amber-800 dark:text-amber-200">+ Recovery mode was used. You must set a new password before accessing the application.+ </p>+ </div>++ <form onSubmit={handleSubmit} className="space-y-4">+ <div className="space-y-2">+ <Label htmlFor="newPassword">New Password</Label>+ <Input+ id="newPassword"+ type="password"+ value={newPassword}+ onChange={(e) => setNewPassword(e.target.value)}+ placeholder="At least 8 characters"+ required+ autoComplete="new-password"+ disabled={loading}+ autoFocus+ />+ {newPassword && (+ <p className="text-xs text-slate-500 dark:text-slate-400">+ {newPassword.length >= 8 ? (+ <span className="text-green-600 dark:text-green-400">✓ Valid password</span>+ ) : (+ <span>At least 8 characters required</span>+ )}+ </p>+ )}+ </div>++ <div className="space-y-2">+ <Label htmlFor="confirmPassword">Confirm Password</Label>+ <Input+ id="confirmPassword"+ type="password"+ value={confirmPassword}+ onChange={(e) => setConfirmPassword(e.target.value)}+ placeholder="Re-enter new password"+ required+ autoComplete="new-password"+ disabled={loading}+ />+ {confirmPassword && (+ <p className="text-xs">+ {newPassword === confirmPassword ? (+ <span className="text-green-600 dark:text-green-400">✓ Passwords match</span>+ ) : (+ <span className="text-red-600 dark:text-red-400">✗ Passwords do not match</span>+ )}+ </p>+ )}+ </div>++ {error && (+ <div className="p-3 rounded-md bg-red-50 dark:bg-red-950/30 border border-red-200 dark:border-red-900">+ <p className="text-sm text-red-800 dark:text-red-200">{error}</p>+ </div>+ )}++ <Button+ type="submit"+ disabled={loading || newPassword.length < 8 || newPassword !== confirmPassword}+ className="w-full bg-indigo-600 hover:bg-indigo-700 text-white"+ >+ {loading ? 'Changing Password...' : 'Set New Password'}+ </Button>+ </form>+ </div>+ </div>+ </div>+ );+}diff --git a/frontend/src/components/auth/LoginPage.jsx b/frontend/src/components/auth/LoginPage.jsxnew file mode 100644index 0000000..7862ace2--- /dev/null+++ b/frontend/src/components/auth/LoginPage.jsx@@ -0,0 +1,119 @@+import React, { useState, useRef, useEffect } from 'react';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import Logo from '@/components/Logo';+import { useAuth } from '@/contexts/AuthContext';+import { SetupWizard } from './SetupWizard';++export function LoginPage() {+ const { authEnabled, setupRequired, login } = useAuth();+ const [username, setUsername] = useState('');+ const [password, setPassword] = useState('');+ const [error, setError] = useState('');+ const [loading, setLoading] = useState(false);+ const passwordInputRef = useRef(null);++ useEffect(() => {+ if (error && passwordInputRef.current) {+ passwordInputRef.current.focus();+ }+ }, [error]);++ if (!authEnabled) {+ return null;+ }++ if (setupRequired) {+ return <SetupWizard />;+ }++ const handleSubmit = async (e) => {+ e.preventDefault();+ setError('');+ setLoading(true);++ const result = await login(username.trim(), password);++ if (!result.success) {+ setError(result.error);+ setPassword('');+ setLoading(false);+ }+ };++ return (+ <div className="min-h-screen flex items-center justify-center bg-slate-50 dark:bg-slate-950 p-4">+ <div className="w-full max-w-md">+ <div className="bg-white dark:bg-slate-900 rounded-lg shadow-lg border border-slate-200 dark:border-slate-800 p-8">+ <div className="flex flex-col items-center mb-8">+ <div className="mb-4 group">+ <Logo className="w-20 h-20 text-slate-600 dark:text-slate-300 hover:text-indigo-600 dark:hover:text-indigo-400 transition-all duration-300 ease-in-out group-hover:rotate-[30deg]" />+ </div>+ <h1 className="text-2xl font-bold text-slate-900 dark:text-slate-100">+ portracker+ </h1>+ <p className="text-sm text-slate-600 dark:text-slate-400 mt-1">+ Sign in to continue+ </p>+ </div>++ <form onSubmit={handleSubmit} className="space-y-4">+ <div className="space-y-2">+ <Label htmlFor="username" className="text-slate-700 dark:text-slate-300">Username</Label>+ <Input+ id="username"+ type="text"+ value={username}+ onChange={(e) => setUsername(e.target.value)}+ placeholder="Enter your username"+ required+ autoComplete="username"+ disabled={loading}+ className="h-10"+ />+ </div>++ <div className="space-y-2">+ <Label htmlFor="password" className="text-slate-700 dark:text-slate-300">Password</Label>+ <Input+ ref={passwordInputRef}+ id="password"+ type="password"+ value={password}+ onChange={(e) => setPassword(e.target.value)}+ placeholder="Enter your password"+ required+ autoComplete="current-password"+ disabled={loading}+ className="h-10"+ />+ </div>++ {error && (+ <div className="p-3 rounded-md bg-red-50 dark:bg-red-950/30 border border-red-200 dark:border-red-900">+ <p className="text-sm text-red-800 dark:text-red-200">+ {error}+ </p>+ </div>+ )}++ <Button+ type="submit"+ disabled={loading || !username || !password}+ className="w-full h-10 bg-indigo-600 hover:bg-indigo-700 text-white"+ >+ {loading ? 'Signing in...' : 'Sign In'}+ </Button>+ </form>++ <div className="mt-6 text-center">+ <p className="text-xs text-slate-500 dark:text-slate-400">+ portracker © {new Date().getFullYear()}+ </p>+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/frontend/src/components/auth/SetupWizard.jsx b/frontend/src/components/auth/SetupWizard.jsxnew file mode 100644index 0000000..78518ea--- /dev/null+++ b/frontend/src/components/auth/SetupWizard.jsx@@ -0,0 +1,178 @@+import React, { useState } from 'react';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import Logo from '@/components/Logo';+import { useAuth } from '@/contexts/AuthContext';+import { KeyRound, ShieldCheck } from 'lucide-react';++export function SetupWizard() {+ const { setup } = useAuth();+ const [username, setUsername] = useState('');+ const [password, setPassword] = useState('');+ const [confirmPassword, setConfirmPassword] = useState('');+ const [error, setError] = useState('');+ const [loading, setLoading] = useState(false);++ const handleSubmit = async (e) => {+ e.preventDefault();+ setError('');++ if (username.length < 3) {+ setError('Username must be at least 3 characters');+ return;+ }++ if (password.length < 8) {+ setError('Password must be at least 8 characters');+ return;+ }++ if (password !== confirmPassword) {+ setError('Passwords do not match');+ return;+ }++ setLoading(true);++ const result = await setup(username.trim(), password);++ if (!result.success) {+ setError(result.error);+ setLoading(false);+ }+ };++ return (+ <div className="min-h-screen flex items-center justify-center bg-slate-50 dark:bg-slate-950 p-4">+ <div className="w-full max-w-lg">+ <div className="bg-white dark:bg-slate-900 rounded-lg shadow-lg border border-slate-200 dark:border-slate-800 p-8">+ <div className="flex flex-col items-center mb-8">+ <div className="mb-4 relative group">+ <Logo className="w-20 h-20 text-slate-600 dark:text-slate-300 hover:text-indigo-600 dark:hover:text-indigo-400 transition-all duration-300 ease-in-out group-hover:rotate-[30deg]" />+ <div className="absolute -bottom-1 -right-1 bg-indigo-600 rounded-full p-2 shadow-lg transition-all duration-300 ease-in-out group-hover:scale-110">+ <ShieldCheck className="w-4 h-4 text-white" />+ </div>+ </div>+ <h1 className="text-2xl font-bold text-slate-900 dark:text-slate-100">+ Welcome to portracker+ </h1>+ <p className="text-sm text-slate-600 dark:text-slate-400 mt-1 text-center">+ Create your admin account to secure your instance+ </p>+ </div>++ <div className="mb-6 p-4 rounded-lg bg-indigo-50 dark:bg-indigo-950/30 border border-indigo-200 dark:border-indigo-900">+ <div className="flex items-start gap-3">+ <KeyRound className="w-5 h-5 text-indigo-600 dark:text-indigo-400 mt-0.5 flex-shrink-0" />+ <div>+ <h3 className="font-semibold text-indigo-900 dark:text-indigo-100 text-sm">+ First-Time Setup+ </h3>+ <p className="text-sm text-indigo-700 dark:text-indigo-300 mt-1">+ Choose a strong password. This account will have full access to your portracker instance.+ </p>+ </div>+ </div>+ </div>++ <form onSubmit={handleSubmit} className="space-y-4">+ <div className="space-y-2">+ <Label htmlFor="username" className="text-slate-700 dark:text-slate-300">Admin Username</Label>+ <Input+ id="username"+ type="text"+ value={username}+ onChange={(e) => setUsername(e.target.value)}+ placeholder="Admin username"+ required+ autoComplete="username"+ disabled={loading}+ className="h-10"+ />+ {username && (+ <p className="text-xs text-slate-500 dark:text-slate-400">+ {username.length >= 3 ? (+ <span className="text-green-600 dark:text-green-400">✓ Valid username</span>+ ) : (+ <span>At least 3 characters required</span>+ )}+ </p>+ )}+ </div>++ <div className="space-y-2">+ <Label htmlFor="password" className="text-slate-700 dark:text-slate-300">Password</Label>+ <Input+ id="password"+ type="password"+ value={password}+ onChange={(e) => setPassword(e.target.value)}+ placeholder="Password"+ required+ autoComplete="new-password"+ disabled={loading}+ className="h-10"+ />+ {password && (+ <p className="text-xs text-slate-500 dark:text-slate-400">+ {password.length >= 8 ? (+ <span className="text-green-600 dark:text-green-400">✓ Valid password</span>+ ) : (+ <span>At least 8 characters required</span>+ )}+ </p>+ )}+ </div>++ <div className="space-y-2">+ <Label htmlFor="confirmPassword" className="text-slate-700 dark:text-slate-300">Confirm Password</Label>+ <Input+ id="confirmPassword"+ type="password"+ value={confirmPassword}+ onChange={(e) => setConfirmPassword(e.target.value)}+ placeholder="Confirm password"+ required+ autoComplete="new-password"+ disabled={loading}+ className="h-10"+ />+ {confirmPassword && (+ <p className="text-xs">+ {password === confirmPassword ? (+ <span className="text-green-600 dark:text-green-400">✓ Passwords match</span>+ ) : (+ <span className="text-red-600 dark:text-red-400">✗ Passwords do not match</span>+ )}+ </p>+ )}+ </div>++ {error && (+ <div className="p-3 rounded-md bg-red-50 dark:bg-red-950/30 border border-red-200 dark:border-red-900">+ <p className="text-sm text-red-800 dark:text-red-200">+ {error}+ </p>+ </div>+ )}++ <Button+ type="submit"+ disabled={loading || username.length < 3 || password.length < 8 || password !== confirmPassword}+ className="w-full h-10 bg-indigo-600 hover:bg-indigo-700 text-white"+ >+ {loading ? 'Creating Account...' : 'Create Admin Account'}+ </Button>+ </form>++ <div className="mt-6 text-center">+ <p className="text-xs text-slate-500 dark:text-slate-400">+ portracker © {new Date().getFullYear()}+ </p>+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/frontend/src/components/layout/AppHeader.jsx b/frontend/src/components/layout/AppHeader.jsxindex cba6080..7d5e153 100644--- a/frontend/src/components/layout/AppHeader.jsx+++ b/frontend/src/components/layout/AppHeader.jsx@@ -8,11 +8,15 @@ import {DropdownMenuRadioItem,DropdownMenuSeparator,DropdownMenuTrigger,+ DropdownMenuItem,} from "@/components/ui/dropdown-menu";-import { RefreshCw, Loader2, Search, X, Sun, Moon, Menu, SlidersHorizontal, Sparkles } from "lucide-react";+import { RefreshCw, Loader2, Search, X, Sun, Moon, Menu, SlidersHorizontal, Sparkles, LogOut, User, Timer } from "lucide-react";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import Logo from "@/components/Logo";+import { useAuth } from "@/contexts/AuthContext";+import { RefreshProgress } from "@/components/ui/RefreshProgress";+import { useLongPress } from "@/lib/hooks/useLongPress";export function AppHeader({loading,@@ -32,7 +36,14 @@ export function AppHeader({onToggleSidebar,onShowWhatsNew,hasNewFeatures = false,+ autoRefreshEnabled = false,+ onAutoRefreshToggle,+ onLogoLongPress,+ hackerMode = false,+ onDisableHackerMode,+ autoRefreshMessages = [],}) {+ const auth = useAuth();const [localSearchTerm, setLocalSearchTerm] = useState(searchTerm);const [searching, setSearching] = useState(false);@@ -105,9 +116,18 @@ export function AppHeader({return "pr-10";};+ const logoLongPressHandlers = useLongPress(+ () => {+ if (onLogoLongPress) {+ onLogoLongPress();+ }+ },+ { threshold: 800 }+ );+return (- <header className="bg-white dark:bg-slate-900 border-b border-slate-200 dark:border-slate-800 relative flex-shrink-0">- <div className="min-h-16 px-4 sm:px-6 py-2 flex flex-col md:flex-row items-center justify-between gap-4">+ <header className="bg-white dark:bg-slate-900 border-b border-slate-200 dark:border-slate-800 relative flex-shrink-0 isolate z-10">+ <div className="min-h-16 px-4 sm:px-6 py-2 flex flex-col md:flex-row items-center justify-between gap-4 relative z-10"><div className="flex items-center gap-4 w-full md:w-auto"><buttononClick={onToggleSidebar}@@ -118,6 +138,7 @@ export function AppHeader({</button><buttononClick={onGoHome}+ {...logoLongPressHandlers}className="flex items-center gap-3 text-xl font-bold text-slate-800 dark:text-slate-200 group cursor-pointer"><Logo@@ -211,13 +232,13 @@ export function AppHeader({</DropdownMenuContent></DropdownMenu>- <div className="flex space-x-2">+ <div className="flex space-x-2 relative z-20">{filterButtons.map((filter) => (<Tooltip key={filter.key}><TooltipTrigger asChild><buttononClick={filter.onClick}- className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${+ className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors relative ${filter.isActive? filter.activeClass: "bg-gray-100 text-gray-600 hover:bg-gray-200 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700"@@ -250,6 +271,26 @@ export function AppHeader({<TooltipContent>{loading ? "Refreshing..." : "Refresh all data"}</TooltipContent></Tooltip>+ {onAutoRefreshToggle && (+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ variant="ghost"+ size="icon"+ onClick={onAutoRefreshToggle}+ className={`hover:bg-gray-100 dark:hover:bg-gray-800 ${+ autoRefreshEnabled ? 'text-indigo-600 dark:text-indigo-400' : ''+ }`}+ >+ <Timer className="h-5 w-5" />+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ {autoRefreshEnabled ? "Auto-refresh enabled (30s)" : "Enable auto-refresh"}+ </TooltipContent>+ </Tooltip>+ )}+<div className="h-6 border-l border-gray-200 dark:border-gray-700 hidden sm:block"></div>{onShowWhatsNew && (@@ -292,10 +333,54 @@ export function AppHeader({</TooltipTrigger><TooltipContent>{isDarkMode ? "Switch to light mode" : "Switch to dark mode"}</TooltipContent></Tooltip>++ {hackerMode && onDisableHackerMode && (+ <Button+ variant="outline"+ size="sm"+ className="text-emerald-500 border-emerald-500/40 bg-emerald-500/5 hover:bg-emerald-500/10"+ onClick={onDisableHackerMode}+ >+ Exit Hacker Mode+ </Button>+ )}++ {auth.authEnabled && auth.authenticated && (+ <DropdownMenu>+ <Tooltip>+ <TooltipTrigger asChild>+ <DropdownMenuTrigger asChild>+ <Button+ variant="ghost"+ size="icon"+ className="hover:bg-gray-100 dark:hover:bg-gray-800 cursor-pointer"+ >+ <User className="h-5 w-5" />+ </Button>+ </DropdownMenuTrigger>+ </TooltipTrigger>+ <TooltipContent>Account</TooltipContent>+ </Tooltip>+ <DropdownMenuContent align="end" className="w-48">+ <div className="px-2 py-1.5 text-sm font-medium text-slate-900 dark:text-slate-100">+ {auth.username}+ </div>+ <DropdownMenuSeparator />+ <DropdownMenuItem onClick={auth.logout} className="text-red-600 dark:text-red-400">+ <LogOut className="mr-2 h-4 w-4" />+ Logout+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ )}</div></div>-+ <RefreshProgress+ active={autoRefreshEnabled && !loading}+ duration={30000}+ messages={autoRefreshMessages || []}+ /></header>);}diff --git a/frontend/src/components/server/HiddenPortsDrawer.jsx b/frontend/src/components/server/HiddenPortsDrawer.jsxindex 966d4ee..ed538aa 100644--- a/frontend/src/components/server/HiddenPortsDrawer.jsx+++ b/frontend/src/components/server/HiddenPortsDrawer.jsx@@ -42,7 +42,7 @@ export function HiddenPortsDrawer({ hiddenPorts, onUnhide, onUnhideAll, serverIdclassName="flex items-center justify-between p-2 bg-slate-50 dark:bg-slate-800/50 rounded-md"><div className="text-sm text-slate-700 dark:text-slate-300">- <span className="font-mono">{p.host_port}</span> —{" "}+ <span className="font-mono">{p.host_port}</span> -{" "}<span className="truncate">{p.owner}</span></div><TooltipProvider>@@ -66,3 +66,5 @@ export function HiddenPortsDrawer({ hiddenPorts, onUnhide, onUnhideAll, serverId</div>);}++diff --git a/frontend/src/components/server/InternalPortDetails.jsx b/frontend/src/components/server/InternalPortDetails.jsxindex 06e0a81..baf943d 100644--- a/frontend/src/components/server/InternalPortDetails.jsx+++ b/frontend/src/components/server/InternalPortDetails.jsx@@ -10,7 +10,7 @@ import {} from "@/components/ui/drawer";import { Button } from "@/components/ui/button";import { Copy, ChevronDown, ChevronUp, Check, Box, Activity, Globe2, Network, Terminal, Settings2, Tag, HardDrive, Info, Gauge, Cpu, FileJson, Download, RefreshCw } from "lucide-react";-import { StatsSkeleton } from './parts/StatsSkeleton';+import StatsSkeleton from './parts/StatsSkeleton';import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu";import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";import { InfoTile } from './parts/InfoTile';diff --git a/frontend/src/components/server/ServerSection.jsx b/frontend/src/components/server/ServerSection.jsxindex f01b4f9..1397d0b 100644--- a/frontend/src/components/server/ServerSection.jsx+++ b/frontend/src/components/server/ServerSection.jsx@@ -146,6 +146,18 @@ function ServerSectionComponent({}, [sortConfig]);+ const portMood = useMemo(() => {+ const count = visiblePorts.length;+ if (count === 0) return null;+ if (count < 10) {+ return `Feels a bit lonely here, only ${count} service${count === 1 ? "" : "s"} standing watch.`;+ }+ if (count > 100) {+ return `Hoarder alert: ${count} services piled into this host.`;+ }+ return null;+ }, [visiblePorts.length]);+const sortedPorts = useMemo(() => {let sortablePorts = [...visiblePorts];@@ -626,6 +638,11 @@ function ServerSectionComponent({)}</div></div>+ {portMood && (+ <p className="mt-3 text-sm text-slate-500 dark:text-slate-400">+ {portMood}+ </p>+ )}</div>{ok && visiblePorts.length > 0 && (diff --git a/frontend/src/components/server/SystemInfoCard.jsx b/frontend/src/components/server/SystemInfoCard.jsxindex 62d696a..9816798 100644--- a/frontend/src/components/server/SystemInfoCard.jsx+++ b/frontend/src/components/server/SystemInfoCard.jsx@@ -48,6 +48,15 @@ export function SystemInfoCard({ systemInfo, platformName }) {containersRunning: systemInfo.containers_running,containersTotal: systemInfo.containers_total,};+ const memoryGb = info.memory ? info.memory / (1024 ** 3) : null;+ let memoryMessage = null;+ if (memoryGb != null) {+ if (memoryGb >= 128) {+ memoryMessage = "That's a lot of RAM.";+ } else if (memoryGb < 4) {+ memoryMessage = "Running lean. Respect.";+ }+ }const containerInfoValue = () => {const running = info.containersRunning;@@ -101,6 +110,11 @@ export function SystemInfoCard({ systemInfo, platformName }) {label="Memory"value={info.memory ? `Total: ${formatBytes(info.memory)}` : "N/A"}/>+ {memoryMessage && (+ <div className="col-span-2 text-xs text-slate-500 dark:text-slate-400 italic">+ {memoryMessage}+ </div>+ )}<InfoItemicon={Clock}label="Uptime"@@ -117,3 +131,5 @@ export function SystemInfoCard({ systemInfo, platformName }) {</div>);}++diff --git a/frontend/src/components/server/TrueNASApiKeyModal.jsx b/frontend/src/components/server/TrueNASApiKeyModal.jsxindex dceed31..97924e2 100644--- a/frontend/src/components/server/TrueNASApiKeyModal.jsx+++ b/frontend/src/components/server/TrueNASApiKeyModal.jsx@@ -8,6 +8,9 @@ import {} from "@/components/ui/dialog";import { Button } from "@/components/ui/button";import { Key, Check } from "lucide-react";+import Logger from '../../lib/logger';++const logger = new Logger('TrueNASApiKeyModal');/*** Modal component that provides step-by-step instructions@@ -26,7 +29,7 @@ export function TrueNASApiKeyModal({ isOpen, onClose }) {setTimeout(() => setCopiedEnvVar(false), 2000);}).catch((err) => {- console.warn("Clipboard API failed, trying fallback", err);+ logger.warn("Clipboard API failed, trying fallback", err);fallbackCopy(text);});} else {@@ -52,7 +55,7 @@ export function TrueNASApiKeyModal({ isOpen, onClose }) {setTimeout(() => setCopiedEnvVar(false), 2000);}} catch (err) {- console.error("All copy methods failed", err);+ logger.error("All copy methods failed", err);}};diff --git a/frontend/src/components/server/VMsCard.jsx b/frontend/src/components/server/VMsCard.jsxindex 9b04002..882f523 100644--- a/frontend/src/components/server/VMsCard.jsx+++ b/frontend/src/components/server/VMsCard.jsx@@ -60,7 +60,13 @@ export function VMsCard({ vms, enhancedFeaturesEnabled }) {return <TrueNASApiKeyEmptyState />;}- if (!vms || vms.length === 0) return null;+ if (!vms || vms.length === 0) {+ return (+ <div className="p-6 text-center text-slate-500 dark:text-slate-400">+ No VMs detected. This server is living a simple, uncomplicated life.+ </div>+ );+ }return (<div className="p-6 pt-4 space-y-4">diff --git a/frontend/src/components/ui/RefreshProgress.jsx b/frontend/src/components/ui/RefreshProgress.jsxindex fd032f5..c7d6a3a 100644--- a/frontend/src/components/ui/RefreshProgress.jsx+++ b/frontend/src/components/ui/RefreshProgress.jsx@@ -1,6 +1,6 @@import { useState, useEffect } from "react";-export function RefreshProgress({ active, duration = 30000 }) {+export function RefreshProgress({ active, duration = 30000, messages = [] }) {const [progress, setProgress] = useState(100);useEffect(() => {@@ -23,14 +23,36 @@ export function RefreshProgress({ active, duration = 30000 }) {return () => clearInterval(interval);}, [active, duration]);+ if (!active) {+ return null;+ }++ const elapsedFraction = 1 - progress / 100;+ const safeMessages = Array.isArray(messages) && messages.length ? messages : null;+ const message = safeMessages+ ? safeMessages[+ Math.min(+ safeMessages.length - 1,+ Math.floor(elapsedFraction * safeMessages.length)+ )+ ]+ : null;+return (- <div className="relative h-0.5 w-full overflow-hidden bg-gray-100 dark:bg-gray-800">- <div- className="absolute inset-0 bg-indigo-500 dark:bg-indigo-400 transition-all duration-100 ease-linear"- style={{- transform: `translateX(${progress - 100}%)`,- }}- />+ <div className="relative flex flex-col gap-1">+ {message && (+ <div className="px-4 text-xs text-slate-500 dark:text-slate-400 font-mono truncate">+ {message}+ </div>+ )}+ <div className="relative h-0.5 w-full overflow-hidden bg-gray-100 dark:bg-gray-800">+ <div+ className="absolute inset-0 bg-indigo-500 dark:bg-indigo-400 transition-all duration-100 ease-linear"+ style={{+ transform: `translateX(${progress - 100}%)`,+ }}+ />+ </div></div>);}diff --git a/frontend/src/components/ui/WhatsNewModal.jsx b/frontend/src/components/ui/WhatsNewModal.jsxindex 8b7ffe4..8cb2df2 100644--- a/frontend/src/components/ui/WhatsNewModal.jsx+++ b/frontend/src/components/ui/WhatsNewModal.jsx@@ -1,12 +1,13 @@import React from 'react';import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from './dialog';import { Button } from './button';-import { Globe, Database, Zap, Sparkles } from 'lucide-react';+import { Globe, Database, Sparkles, Shield, Layout, Server, HardDrive, Wrench, Package, Bandage } from 'lucide-react';import { getFeatureIcon } from '../../lib/feature-icons';import { cn } from '@/lib/utils';const FeatureCard = ({ feature, index }) => {const IconComponent = getFeatureIcon(feature);+ const hasDetails = feature.details?.length > 0;return (<div@@ -30,6 +31,27 @@ const FeatureCard = ({ feature, index }) => {<p className="text-slate-600 dark:text-slate-400 text-sm leading-relaxed">{feature.description}</p>+ {hasDetails && (+ <ul className="mt-2 ml-3 space-y-1.5">+ {feature.details.map((detail, i) => (+ <li key={i} className="flex items-start gap-2 text-sm text-slate-600 dark:text-slate-400">+ <span className="text-indigo-600 dark:text-indigo-400 mt-0.5">•</span>+ <div>+ {detail.title ? (+ <>+ <span className="font-medium text-slate-800 dark:text-slate-200">{detail.title}</span>+ {detail.description && (+ <span className="text-slate-600 dark:text-slate-400">: {detail.description}</span>+ )}+ </>+ ) : (+ <span>{detail.description}</span>+ )}+ </div>+ </li>+ ))}+ </ul>+ )}</div></div></div>@@ -75,6 +97,54 @@ const VersionSection = ({ versionData, index }) => (</div><div className="space-y-4">+ {versionData.changes.security?.length > 0 && (+ <CategorySection+ title="Security & Access Control"+ features={versionData.changes.security}+ icon={Shield}+ />+ )}++ {versionData.changes.dashboard?.length > 0 && (+ <CategorySection+ title="Dashboard & UX"+ features={versionData.changes.dashboard}+ icon={Layout}+ />+ )}++ {versionData.changes.integrations?.length > 0 && (+ <CategorySection+ title="Server Integrations"+ features={versionData.changes.integrations}+ icon={Server}+ />+ )}++ {versionData.changes.data?.length > 0 && (+ <CategorySection+ title="Data & Infrastructure"+ features={versionData.changes.data}+ icon={HardDrive}+ />+ )}++ {versionData.changes.tooling?.length > 0 && (+ <CategorySection+ title="Operations & Tooling"+ features={versionData.changes.tooling}+ icon={Wrench}+ />+ )}++ {versionData.changes.fixes?.length > 0 && (+ <CategorySection+ title="Stability & Fixes"+ features={versionData.changes.fixes}+ icon={Bandage}+ />+ )}+{versionData.changes.frontend?.length > 0 && (<CategorySectiontitle="Frontend Improvements"@@ -91,11 +161,11 @@ const VersionSection = ({ versionData, index }) => (/>)}- {versionData.changes.development?.length > 0 && (+ {versionData.changes.misc?.length > 0 && (<CategorySection- title="Development & Infrastructure"- features={versionData.changes.development}- icon={Zap}+ title="Other Updates"+ features={versionData.changes.misc}+ icon={Package}/>)}</div>@@ -104,6 +174,54 @@ const VersionSection = ({ versionData, index }) => (const FlatChangesDisplay = ({ changes }) => (<>+ {changes.security?.length > 0 && (+ <CategorySection+ title="Security & Access Control"+ features={changes.security}+ icon={Shield}+ />+ )}++ {changes.dashboard?.length > 0 && (+ <CategorySection+ title="Dashboard & UX"+ features={changes.dashboard}+ icon={Layout}+ />+ )}++ {changes.integrations?.length > 0 && (+ <CategorySection+ title="Server Integrations"+ features={changes.integrations}+ icon={Server}+ />+ )}++ {changes.data?.length > 0 && (+ <CategorySection+ title="Data & Infrastructure"+ features={changes.data}+ icon={HardDrive}+ />+ )}++ {changes.tooling?.length > 0 && (+ <CategorySection+ title="Operations & Tooling"+ features={changes.tooling}+ icon={Wrench}+ />+ )}++ {changes.fixes?.length > 0 && (+ <CategorySection+ title="Stability & Fixes"+ features={changes.fixes}+ icon={Bandage}+ />+ )}+{changes.frontend?.length > 0 && (<CategorySectiontitle="Frontend Improvements"@@ -120,11 +238,11 @@ const FlatChangesDisplay = ({ changes }) => (/>)}- {changes.development?.length > 0 && (+ {changes.misc?.length > 0 && (<CategorySection- title="Development & Infrastructure"- features={changes.development}- icon={Zap}+ title="Other Updates"+ features={changes.misc}+ icon={Package}/>)}</>diff --git a/frontend/src/contexts/AuthContext.jsx b/frontend/src/contexts/AuthContext.jsxnew file mode 100644index 0000000..bc342cc--- /dev/null+++ b/frontend/src/contexts/AuthContext.jsx@@ -0,0 +1,199 @@+import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';+import Logger from '../lib/logger';++const logger = new Logger('AuthContext');++const AuthContext = createContext(null);++export function useAuth() {+ const context = useContext(AuthContext);+ if (!context) {+ throw new Error('useAuth must be used within AuthProvider');+ }+ return context;+}++export function AuthProvider({ children }) {+ const [authState, setAuthState] = useState({+ loading: true,+ authEnabled: false,+ authenticated: false,+ setupRequired: false,+ username: null,+ requirePasswordChange: false+ });++ const checkAuthStatus = useCallback(async () => {+ try {+ const response = await fetch('/api/auth/status', {+ credentials: 'include'+ });++ if (!response.ok) {+ logger.error('Failed to check auth status:', response.status);+ setAuthState({+ loading: false,+ authEnabled: false,+ authenticated: false,+ setupRequired: false,+ username: null+ });+ return;+ }++ const data = await response.json();++ setAuthState({+ loading: false,+ authEnabled: data.authEnabled,+ authenticated: data.authenticated,+ setupRequired: data.setupRequired,+ username: data.username,+ requirePasswordChange: data.requirePasswordChange || false+ });++ logger.debug('Auth status:', data);+ } catch (error) {+ logger.error('Error checking auth status:', error.message);+ setAuthState({+ loading: false,+ authEnabled: false,+ authenticated: false,+ setupRequired: false,+ username: null,+ requirePasswordChange: false+ });+ }+ }, []);++ useEffect(() => {+ checkAuthStatus();+ }, [checkAuthStatus]);++ const login = useCallback(async (username, password) => {+ try {+ const response = await fetch('/api/auth/login', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({ username: username.trim(), password })+ });++ const data = await response.json();++ if (!response.ok) {+ return { success: false, error: data.error || 'Login failed' };+ }++ if (data.requirePasswordChange) {+ setAuthState(prev => ({+ ...prev,+ requirePasswordChange: true,+ authenticated: true,+ username: data.username+ }));+ return { success: true, requirePasswordChange: true };+ }++ await new Promise(resolve => setTimeout(resolve, 800));++ await checkAuthStatus();+ return { success: true };+ } catch (error) {+ logger.error('Login error:', error.message);+ return { success: false, error: 'Network error' };+ }+ }, [checkAuthStatus]);++ const logout = useCallback(async () => {+ try {+ const response = await fetch('/api/auth/logout', {+ method: 'POST',+ credentials: 'include'+ });++ if (!response.ok) {+ logger.error('Logout failed:', response.status);+ return;+ }++ setAuthState({+ loading: false,+ authEnabled: true,+ authenticated: false,+ setupRequired: false,+ username: null,+ requirePasswordChange: false+ });+ } catch (error) {+ logger.error('Logout error:', error.message);+ }+ }, []);++ const setup = useCallback(async (username, password) => {+ try {+ const response = await fetch('/api/auth/setup', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({ username: username.trim(), password })+ });++ const data = await response.json();++ if (!response.ok) {+ return { success: false, error: data.error || 'Setup failed' };+ }++ await new Promise(resolve => setTimeout(resolve, 800));++ await checkAuthStatus();+ return { success: true };+ } catch (error) {+ logger.error('Setup error:', error.message);+ return { success: false, error: 'Network error' };+ }+ }, [checkAuthStatus]);++ const changePassword = useCallback(async (currentPassword, newPassword) => {+ try {+ const response = await fetch('/api/auth/change-password', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({ currentPassword, newPassword })+ });++ const data = await response.json();++ if (!response.ok) {+ return { success: false, error: data.error || 'Password change failed' };+ }++ setAuthState(prev => ({+ ...prev,+ requirePasswordChange: false+ }));++ return { success: true };+ } catch (error) {+ logger.error('Change password error:', error.message);+ return { success: false, error: 'Network error' };+ }+ }, []);++ const value = {+ ...authState,+ login,+ logout,+ setup,+ changePassword,+ refreshAuth: checkAuthStatus+ };++ return (+ <AuthContext.Provider value={value}>+ {children}+ </AuthContext.Provider>+ );+}diff --git a/frontend/src/index.css b/frontend/src/index.cssindex 0651dea..5ad4c2e 100644--- a/frontend/src/index.css+++ b/frontend/src/index.css@@ -175,3 +175,92 @@.motion-safe\:shadow-lg[data-state] { box-shadow: 0 10px 15px -3px hsl(0 0% 0% / 0.15), 0 4px 6px -2px hsl(0 0% 0% / 0.1); }.motion-reduce\:shadow-none { box-shadow: none; }}++body.hacker-mode {+ background-color: #021404;+ color: #bffac2;+ font-family: 'Courier New', 'Consolas', 'Monaco', monospace;+}++body.hacker-mode .hacker-mode-active {+ background-color: transparent;+ color: inherit;+}++body.hacker-mode .bg-white,+body.hacker-mode .bg-slate-50,+body.hacker-mode .bg-slate-100,+body.hacker-mode .dark\:bg-slate-800\/50 {+ background-color: rgba(0, 20, 5, 0.9) !important;+ color: #bffac2 !important;+}++body.hacker-mode .text-slate-900,+body.hacker-mode .dark\:text-slate-100 {+ color: #bffac2 !important;+}++body.hacker-mode .border-slate-200,+body.hacker-mode .dark\:border-slate-700\/50,+body.hacker-mode .dark\:border-slate-700 {+ border-color: rgba(50, 193, 118, 0.4) !important;+}++body.hacker-mode .bg-rose-50\/95,+body.hacker-mode .dark\:bg-rose-900\/95 {+ background-color: rgba(20, 5, 0, 0.95) !important;+}++body.hacker-mode .border-rose-200,+body.hacker-mode .dark\:border-rose-800 {+ border-color: rgba(193, 50, 50, 0.4) !important;+}++body.hacker-mode .text-rose-900,+body.hacker-mode .dark\:text-rose-100 {+ color: #ffb3b3 !important;+}++body.hacker-mode .bg-rose-500,+body.hacker-mode .dark\:bg-rose-400 {+ background-color: #ff5050 !important;+}++body.hacker-mode .bg-indigo-500,+body.hacker-mode .dark\:bg-indigo-400 {+ background-color: #50ffa0 !important;+}++body.hacker-mode .bg-white\/95,+body.hacker-mode .dark\:bg-slate-800\/95 {+ background-color: rgba(0, 20, 5, 0.95) !important;+}++body.hacker-mode .text-slate-900,+body.hacker-mode .dark\:text-slate-100 {+ color: #bffac2 !important;+}++body.hacker-mode .text-slate-600,+body.hacker-mode .dark\:text-slate-400,+body.hacker-mode .text-slate-500,+body.hacker-mode .dark\:text-slate-300 {+ color: #a0e0a8 !important;+}++body.hacker-mode::before {+ content: "";+ position: fixed;+ inset: 0;+ pointer-events: none;+ background: repeating-linear-gradient(+ 0deg,+ rgba(0, 255, 170, 0.08),+ rgba(0, 255, 170, 0.08) 1px,+ transparent 1px,+ transparent 3px+ );+ opacity: 0.25;+ mix-blend-mode: screen;+ z-index: 5;+}diff --git a/frontend/src/lib/autoRefreshMessages.js b/frontend/src/lib/autoRefreshMessages.jsnew file mode 100644index 0000000..e7888ec--- /dev/null+++ b/frontend/src/lib/autoRefreshMessages.js@@ -0,0 +1,37 @@+const GENERAL_MESSAGES = [+ "Shushing noisy daemons… give us 30 seconds.",+ "Counting bits, bytes, and bad decisions.",+ "Scanning the subnet for uninvited guests.",+ "Checking if Docker went rogue again.",+ "Playing hide-and-seek under bridged networks.",+ "Waiting for services to line up for roll call.",+ "Scripting yet another docker ps flex.",+ "Watching for containers that missed curfew.",+ "Renegotiating NAT treaties at the border.",+ "Diffing firewall rules so you don’t have to.",+ "Running ip neigh gossip down the rack.",+ "Patching cables with positive thoughts.",+ "Staring down cronjobs until they blink.",+ "Cross-checking config drift in the margins.",+ "Counting open ports faster than nmap.",+ "Waiting for log ingestion to stop screaming."+];++const TRUE_NAS_MESSAGE = "Asking TrueNAS if it woke another VM.";++export function buildAutoRefreshMessages({ isTrueNAS = false, currentPort = "4999" } = {}) {+ const base = [...GENERAL_MESSAGES];++ base.push(`Confirming that Port ${currentPort} still belongs to you.`);++ if (isTrueNAS) {+ base.push(TRUE_NAS_MESSAGE);+ }++ const shuffled = base+ .map((text) => ({ text, sortKey: Math.random() }))+ .sort((a, b) => a.sortKey - b.sortKey)+ .map((entry) => entry.text);++ return shuffled;+}diff --git a/frontend/src/lib/hooks/useWhatsNew.js b/frontend/src/lib/hooks/useWhatsNew.jsindex 4533d37..03c1200 100644--- a/frontend/src/lib/hooks/useWhatsNew.js+++ b/frontend/src/lib/hooks/useWhatsNew.js@@ -138,7 +138,9 @@ export function useWhatsNew() {if (!isDismissed) {logger.debug('Opening What\'s New modal');- setIsModalOpen(true);+ setTimeout(() => {+ setIsModalOpen(true);+ }, 1000);}}}diff --git a/frontend/src/lib/whats-new.js b/frontend/src/lib/whats-new.jsindex fbc750a..3c91936 100644--- a/frontend/src/lib/whats-new.js+++ b/frontend/src/lib/whats-new.js@@ -2,45 +2,76 @@ import Logger from './logger';const logger = new Logger('WhatsNewUtils');+const CATEGORY_KEYS = [+ 'security',+ 'dashboard',+ 'integrations',+ 'data',+ 'tooling',+ 'frontend',+ 'backend',+ 'fixes',+ 'misc'+];++function createFeatureBuckets() {+ return CATEGORY_KEYS.reduce((acc, key) => {+ acc[key] = [];+ return acc;+ }, {});+}++const CATEGORY_MAPPINGS = [+ { match: /(security|auth|access)/i, bucket: 'security' },+ { match: /(dashboard|ui|ux|interface)/i, bucket: 'dashboard' },+ { match: /(server|collector|truenas|docker|integration)/i, bucket: 'integrations' },+ { match: /(data|db|database|infrastructure|performance|cache)/i, bucket: 'data' },+ { match: /(tooling|ops|operation|automation|deploy)/i, bucket: 'tooling' },+ { match: /(frontend|client)/i, bucket: 'frontend' },+ { match: /(backend|api)/i, bucket: 'backend' },+ { match: /(fix|bug|stability|patch)/i, bucket: 'fixes' },+];++function mapSectionToCategory(sectionName) {+ const normalized = sectionName.toLowerCase();+ for (const mapping of CATEGORY_MAPPINGS) {+ if (mapping.match.test(normalized)) {+ return mapping.bucket;+ }+ }+ return 'misc';+}+export function parseChangelog(changelogContent) {try {const versions = {};const lines = changelogContent.split('\n');let currentVersion = null;let currentSection = null;- let features = { frontend: [], backend: [], development: [], infrastructure: [] };+ let features = createFeatureBuckets();+ let lastFeature = null;for (let i = 0; i < lines.length; i++) {const line = lines[i].trim();const versionMatch = line.match(/^##\s*\[([^\]]+)\]/);if (versionMatch) {- if (currentVersion && (features.frontend.length > 0 || features.backend.length > 0 || features.development.length > 0 || features.infrastructure.length > 0)) {+ const hasContent = Object.values(features).some(arr => arr.length > 0);+ if (currentVersion && hasContent) {versions[currentVersion] = { ...features };}currentVersion = versionMatch[1];currentSection = null;- features = { frontend: [], backend: [], development: [], infrastructure: [] };+ features = createFeatureBuckets();+ lastFeature = null;continue;}const sectionMatch = line.match(/^###\s+(.+)$/);if (sectionMatch && currentVersion) {- const sectionName = sectionMatch[1].toLowerCase();- if (sectionName.includes('frontend')) {- currentSection = 'frontend';- } else if (sectionName.includes('backend')) {- currentSection = 'backend';- } else if (sectionName.includes('development') || sectionName.includes('infrastructure')) {- currentSection = 'development';- } else if (sectionName.includes('security') || sectionName.includes('improvements')) {- currentSection = 'development';- } else if (sectionName.includes('initial')) {- currentSection = 'development';- } else {- currentSection = 'development';- }+ currentSection = mapSectionToCategory(sectionMatch[1]);+ lastFeature = null;continue;}@@ -49,14 +80,39 @@ export function parseChangelog(changelogContent) {const title = featureMatch[1].trim();const description = featureMatch[2].trim();- features[currentSection].push({- title,- description- });+ const isSubItem = title.startsWith('[sub]');++ if (isSubItem && lastFeature) {+ const cleanTitle = title.replace(/^\[sub\]\s*/, '').trim();+ if (!lastFeature.details) {+ lastFeature.details = [];+ }+ lastFeature.details.push({ title: cleanTitle, description });+ } else {+ const feature = {+ title: isSubItem ? title.replace(/^\[sub\]\s*/, '').trim() : title,+ description,+ details: []+ };++ features[currentSection].push(feature);+ lastFeature = feature;+ }+ continue;+ }++ const subItemMatch = line.match(/^-\s*\*\*\[sub\]\*\*\s+(.+)$/);+ if (subItemMatch && lastFeature && currentSection) {+ const text = subItemMatch[1].trim();+ if (!lastFeature.details) {+ lastFeature.details = [];+ }+ lastFeature.details.push({ title: '', description: text });}}- if (currentVersion && (features.frontend.length > 0 || features.backend.length > 0 || features.development.length > 0 || features.infrastructure.length > 0)) {+ const hasContent = Object.values(features).some(arr => arr.length > 0);+ if (currentVersion && hasContent) {versions[currentVersion] = { ...features };}@@ -140,25 +196,18 @@ export function getNewVersions(parsedVersions, lastSeenVersion) {}export function combineVersionChanges(versions, versionKeys) {- const combined = { frontend: [], backend: [], development: [] };+ const combined = createFeatureBuckets();const sortedVersions = versionKeys.sort((a, b) => compareVersions(b, a));for (const version of sortedVersions) {const versionChanges = versions[version];if (versionChanges) {- if (versionChanges.frontend) {- combined.frontend.push(...versionChanges.frontend);- }- if (versionChanges.backend) {- combined.backend.push(...versionChanges.backend);- }- if (versionChanges.development) {- combined.development.push(...versionChanges.development);- }- if (versionChanges.infrastructure) {- combined.development.push(...versionChanges.infrastructure);- }+ CATEGORY_KEYS.forEach(key => {+ if (versionChanges[key]?.length) {+ combined[key].push(...versionChanges[key]);+ }+ });}}@@ -170,32 +219,21 @@ export function groupVersionChanges(versions, versionKeys) {return sortedVersions.map(version => {const versionChanges = versions[version];- const changes = { frontend: [], backend: [], development: [] };+ const changes = createFeatureBuckets();if (versionChanges) {- if (versionChanges.frontend) {- changes.frontend.push(...versionChanges.frontend);- }- if (versionChanges.backend) {- changes.backend.push(...versionChanges.backend);- }- if (versionChanges.development) {- changes.development.push(...versionChanges.development);- }- if (versionChanges.infrastructure) {- changes.development.push(...versionChanges.infrastructure);- }+ CATEGORY_KEYS.forEach(key => {+ if (versionChanges[key]?.length) {+ changes[key].push(...versionChanges[key]);+ }+ });}return {version,changes};- }).filter(item =>- item.changes.frontend.length > 0 ||- item.changes.backend.length > 0 ||- item.changes.development.length > 0- );+ }).filter(item => CATEGORY_KEYS.some(key => item.changes[key]?.length > 0));}export function shouldShowWhatsNew(currentVersion) {diff --git a/frontend/src/main.jsx b/frontend/src/main.jsxindex 9f02bf7..acdb84c 100644--- a/frontend/src/main.jsx+++ b/frontend/src/main.jsx@@ -3,13 +3,16 @@ import { createRoot } from 'react-dom/client'import { BrowserRouter, Routes, Route } from 'react-router-dom'import './index.css'import App from './App.jsx'+import { AuthProvider } from './contexts/AuthContext'createRoot(document.getElementById('root')).render(<StrictMode><BrowserRouter>- <Routes>- <Route path="/" element={<App />} />- </Routes>+ <AuthProvider>+ <Routes>+ <Route path="/" element={<App />} />+ </Routes>+ </AuthProvider></BrowserRouter></StrictMode>,)diff --git a/frontend/vite.config.js b/frontend/vite.config.jsindex c2cb01b..95a5f5e 100644--- a/frontend/vite.config.js+++ b/frontend/vite.config.js@@ -17,7 +17,7 @@ export default defineConfig({server: {proxy: {'/api': {- target: 'http://localhost:3000',+ target: 'http://localhost:4999',changeOrigin: true,secure: false,},