Initial commit

This commit is contained in:
Pit Friedrich
2025-11-15 14:58:44 +01:00
commit 84c9e3f855
38 changed files with 14052 additions and 0 deletions
+36
View File
@@ -0,0 +1,36 @@
# Dependencies
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Environment
.env
.env.local
.env.production
# Build Output
dist/
build/
# Logs
logs/
*.log
# OS
.DS_Store
Thumbs.db
# IDE
.vscode/
.idea/
*.swp
*.swo
*~
# TypeScript
*.tsbuildinfo
# PWA
sw.js
workbox-*.js
+54
View File
@@ -0,0 +1,54 @@
# Stage 1: Build Frontend
FROM node:20-alpine AS frontend-build
WORKDIR /app/frontend
COPY frontend/package*.json ./
RUN npm ci
COPY frontend/ .
RUN npm run build
# Stage 2: Build Backend
FROM node:20-alpine AS backend-build
WORKDIR /app/backend
COPY backend/package*.json ./
RUN npm ci
COPY backend/ .
RUN npm run build
# Stage 3: Production Image
FROM node:20-alpine
WORKDIR /app
# Install nginx and supervisor
RUN apk add --no-cache nginx supervisor
# Copy Backend
COPY --from=backend-build /app/backend/dist ./backend/dist
COPY --from=backend-build /app/backend/node_modules ./backend/node_modules
COPY --from=backend-build /app/backend/package.json ./backend/
# Copy Frontend
COPY --from=frontend-build /app/frontend/dist ./frontend/dist
# Nginx Config
RUN mkdir -p /run/nginx
COPY nginx.conf /etc/nginx/http.d/default.conf
# Supervisor Config
COPY supervisord.conf /etc/supervisord.conf
# Create non-root user
RUN addgroup -g 1001 -S appgroup && adduser -S appuser -u 1001
# Set permissions
RUN chown -R appuser:appgroup /app /run/nginx /var/log/nginx /var/lib/nginx
# Expose single port
EXPOSE 10000
# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
CMD wget --no-verbose --tries=1 --spider http://localhost:10000/api/health || exit 1
# Start with supervisor
CMD ["/usr/bin/supervisord", "-c", "/etc/supervisord.conf"]
+228
View File
@@ -0,0 +1,228 @@
# Unraid Monitor - Projekt-Layout
## Komplette Verzeichnisstruktur
```
unraid-monitor/
├── docker-compose.yml # Docker Compose Konfiguration
├── .gitignore # Git Ignore Rules
├── README.md # Hauptdokumentation
├── SETUP.md # Setup-Anleitung für Unraid
├── backend/ # Backend (Node.js + TypeScript)
│ ├── src/
│ │ ├── controllers/ # API Controller
│ │ │ ├── authController.ts # Login, Register, Me
│ │ │ ├── systemController.ts # System Stats, Uptime
│ │ │ └── dockerController.ts # Container Management
│ │ │
│ │ ├── services/ # Business Logic
│ │ │ ├── systemService.ts # System Info (CPU, RAM, Disk)
│ │ │ └── dockerService.ts # Docker API Integration
│ │ │
│ │ ├── middleware/ # Express Middleware
│ │ │ └── auth.ts # JWT Authentication
│ │ │
│ │ ├── types/ # TypeScript Typen
│ │ │ └── index.ts # Interfaces (User, SystemStats, etc.)
│ │ │
│ │ └── index.ts # Express Server Entry Point
│ │
│ ├── package.json # NPM Dependencies
│ ├── tsconfig.json # TypeScript Config
│ ├── Dockerfile # Docker Build
│ ├── .env.example # Environment Variables Beispiel
│ └── .env # Environment Variables (erstellen!)
└── frontend/ # Frontend (React + TypeScript + PWA)
├── public/ # Static Assets
│ ├── favicon.ico # (optional - eigenes Icon)
│ ├── icon-192.png # (optional - PWA Icon 192x192)
│ ├── icon-512.png # (optional - PWA Icon 512x512)
│ └── apple-touch-icon.png # (optional - iOS Icon)
├── src/
│ ├── components/ # React Components
│ │ ├── Login.tsx # Login-Seite
│ │ ├── Layout.tsx # Layout mit Navigation
│ │ ├── Dashboard.tsx # Dashboard mit System Stats
│ │ └── Containers.tsx # Container-Verwaltung
│ │
│ ├── stores/ # Zustand State Management
│ │ └── authStore.ts # Authentication State
│ │
│ ├── lib/ # Utilities & API
│ │ ├── api.ts # Axios API Client + Types
│ │ └── utils.ts # Helper Functions (formatBytes, etc.)
│ │
│ ├── App.tsx # Main App mit Routing
│ ├── main.tsx # React Entry Point
│ ├── index.css # Tailwind CSS + Custom Styles
│ └── vite-env.d.ts # Vite Types
├── index.html # HTML Entry
├── package.json # NPM Dependencies
├── tsconfig.json # TypeScript Config
├── tsconfig.node.json # TypeScript Config für Node
├── vite.config.ts # Vite + PWA Config
├── tailwind.config.js # Tailwind CSS Config
├── postcss.config.js # PostCSS Config
├── Dockerfile # Docker Build
├── .env.example # Environment Variables Beispiel
└── .env # Environment Variables (optional)
```
## Datei-Checkliste
### Root-Level (unraid-monitor/)
- [ ] docker-compose.yml
- [ ] .gitignore
- [ ] README.md
- [ ] SETUP.md
### Backend (backend/)
- [ ] package.json
- [ ] tsconfig.json
- [ ] Dockerfile
- [ ] .env.example
- [ ] .env (manuell erstellen!)
#### Backend Source (backend/src/)
- [ ] index.ts
##### Controllers (backend/src/controllers/)
- [ ] authController.ts
- [ ] systemController.ts
- [ ] dockerController.ts
##### Services (backend/src/services/)
- [ ] systemService.ts
- [ ] dockerService.ts
##### Middleware (backend/src/middleware/)
- [ ] auth.ts
##### Types (backend/src/types/)
- [ ] index.ts
### Frontend (frontend/)
- [ ] package.json
- [ ] tsconfig.json
- [ ] tsconfig.node.json
- [ ] vite.config.ts
- [ ] tailwind.config.js
- [ ] postcss.config.js
- [ ] Dockerfile
- [ ] index.html
- [ ] .env.example
- [ ] .env (optional)
#### Frontend Source (frontend/src/)
- [ ] main.tsx
- [ ] App.tsx
- [ ] index.css
- [ ] vite-env.d.ts
##### Components (frontend/src/components/)
- [ ] Login.tsx
- [ ] Layout.tsx
- [ ] Dashboard.tsx
- [ ] Containers.tsx
##### Stores (frontend/src/stores/)
- [ ] authStore.ts
##### Lib (frontend/src/lib/)
- [ ] api.ts
- [ ] utils.ts
#### Frontend Public (frontend/public/)
- [ ] favicon.ico (optional)
- [ ] icon-192.png (optional)
- [ ] icon-512.png (optional)
- [ ] apple-touch-icon.png (optional)
## Wichtige Ordner erstellen
Wenn du die Dateien manuell erstellst, musst du die Ordner vorher anlegen:
```bash
# Root
mkdir -p unraid-monitor
# Backend
mkdir -p unraid-monitor/backend/src/{controllers,services,middleware,types}
# Frontend
mkdir -p unraid-monitor/frontend/src/{components,stores,lib}
mkdir -p unraid-monitor/frontend/public
```
## Dateigrößen (ungefähr)
**Backend:**
- Gesamt: ~50 Dateien nach `npm install`
- Source Code: 8 TypeScript-Dateien
- node_modules/: ~200MB
**Frontend:**
- Gesamt: ~2000 Dateien nach `npm install`
- Source Code: 12 TypeScript/TSX-Dateien
- node_modules/: ~400MB
## Installation der Dependencies
**Backend:**
```bash
cd backend
npm install
```
Installiert:
- express, cors, helmet
- jsonwebtoken, bcryptjs
- dockerode, systeminformation
- dotenv, express-rate-limit
- TypeScript + Dev Tools
**Frontend:**
```bash
cd frontend
npm install
```
Installiert:
- react, react-dom, react-router-dom
- @tanstack/react-query, axios, zustand
- lucide-react, recharts
- vite, vite-plugin-pwa
- tailwindcss, postcss, autoprefixer
- TypeScript + Dev Tools
## Nach dem Setup
Nach `npm install` in beiden Ordnern:
```
backend/
├── node_modules/ # ~200MB
├── dist/ # Nach Build: Compiled JS
└── ...
frontend/
├── node_modules/ # ~400MB
├── dist/ # Nach Build: Production Files
└── ...
```
## Docker Images
Nach `docker-compose build`:
- **unraid-monitor-backend**: ~200MB
- **unraid-monitor-frontend**: ~50MB (Nginx + Build)
---
**Tipp:** Nutze das bereitgestellte Projekt-Archiv, dann sind alle Dateien bereits an der richtigen Stelle! 🎯
+2747
View File
File diff suppressed because it is too large Load Diff
+37
View File
@@ -0,0 +1,37 @@
{
"name": "unraid-monitor-backend",
"version": "1.0.0",
"description": "Backend API for Unraid Monitor PWA",
"main": "dist/index.js",
"scripts": {
"dev": "ts-node-dev --respawn --transpile-only src/index.ts",
"build": "tsc",
"start": "node dist/index.js",
"lint": "eslint src --ext .ts",
"hash": "ts-node-dev --transpile-only src/hash.ts"
},
"dependencies": {
"express": "^4.18.2",
"cors": "^2.8.5",
"dotenv": "^16.3.1",
"jsonwebtoken": "^9.0.2",
"bcryptjs": "^2.4.3",
"dockerode": "^4.0.2",
"systeminformation": "^5.12.20",
"express-validator": "^7.0.1",
"helmet": "^7.1.0",
"express-rate-limit": "^7.1.5",
"uuid": "^9.0.1"
},
"devDependencies": {
"@types/express": "^4.17.21",
"@types/cors": "^2.8.17",
"@types/jsonwebtoken": "^9.0.5",
"@types/bcryptjs": "^2.4.6",
"@types/node": "^20.10.6",
"typescript": "^5.3.3",
"ts-node-dev": "^2.0.0",
"@types/uuid": "^9.0.7",
"@types/dockerode": "3.3.46"
}
}
+129
View File
@@ -0,0 +1,129 @@
import bcrypt from 'bcryptjs';
import { v4 as uuidv4 } from 'uuid';
import { LoginRequest, LoginResponse, User } from "../types";
import { Request, Response } from 'express';
import { generateToken } from '../middleware/auth';
const users: User[] = [];
const initializeDefaultUser = () => {
if (users.length === 0) {
const hashedPassword = '$2a$10$dUjaDLdCnYdEJYRUNe5jful8f94cfYvqM0fgpiajcIEcBQllz2076';
users.push({
id: uuidv4(),
username: 'admin',
password: hashedPassword,
createdAt: new Date()
});
console.log('Default user created: admin');
}
};
initializeDefaultUser();
export class AuthController {
async login(req: Request, res: Response) {
try {
const { username, password }: LoginRequest = req.body;
if (!username || !password) {
return res.status(400).json({ error: 'Username and password required' });
}
const user = users.find(u => u.username === username);
if (!user) {
return res.status(401).json({ error: 'Invalid credentials' });
}
const isValidPassword = bcrypt.compareSync(password, user.password);
if (!isValidPassword) {
return res.status(401).json({ error: 'Invalid credentials' });
}
const token = generateToken({ id: user.id, username: user.username });
const response: LoginResponse = {
token,
user: {
id: user.id,
username: user.username
}
};
res.json(response);
} catch (error) {
console.error('Login error:', error);
res.status(500).json({ error: 'Internal server error' });
}
}
async register(req: Request, res: Response) {
try {
const { username, password } = req.body;
if (!username || !password) {
return res.status(400).json({ error: 'Username and password required' });
}
if (password.length < 6) {
return res.status(400).json({ error:'Password must be at least 6 characters' });
}
const existingUser = users.find(u => u.username === username);
if (existingUser) {
return res.status(409).json({ error: 'Username already exists' });
}
const hashedPassword = bcrypt.hashSync(password, 10);
const newUser: User = {
id: uuidv4(),
username,
password: hashedPassword,
createdAt: new Date()
};
users.push(newUser);
const token = generateToken({ id: newUser.id, username: newUser.username });
const response: LoginResponse = {
token,
user: {
id: newUser.id,
username: newUser.username
}
};
res.status(201).json(response);
} catch (error) {
console.error('Register error:', error);
res.status(500).json({ error: 'Internal server error' })
}
}
async me(req: Request, res: Response) {
try {
// @ts-ignore - user wird durch authMiddleware gesetzt
const userId = req.user.id;
const user = users.find(u => u.id === userId);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.json({
id: user.id,
username: user.username,
createdAt: user.createdAt
})
} catch (error) {
console.error('Me error:', error);
res.status(500).json({ error: 'Internal server error' })
}
}
}
@@ -0,0 +1,95 @@
import { Response } from 'express';
import { DockerService } from '../services/dockerService';
import { AuthRequest } from '../types';
import { toError } from '../utils/helper';
const dockerService = new DockerService();
export class DockerController {
async getContainers(req: AuthRequest, res: Response) {
try {
const containers = await dockerService.getContainers();
res.json(containers);
} catch (error) {
console.error('Error getting containers:', error);
res.status(500).json(toError('Failed to retrieve containers'));
}
}
async getContainer(req: AuthRequest, res: Response) {
try {
const { id } = req.params;
const container = await dockerService.getContainer(id);
if (!container) {
return res.status(404).json(toError('Container not found'));
}
res.json(container);
} catch (error) {
console.error('Error getting container:', error);
res.status(500).json(toError('Failed to retrieve container'));
}
}
async startContainer(req: AuthRequest, res: Response) {
try {
const { id } = req.params;
await dockerService.startContainer(id);
res.json({ message: 'Container started successfully' });
} catch (error) {
console.error('Error starting container:', error);
res.status(500).json(toError('Failed to start container'));
}
}
async stopContainer(req: AuthRequest, res: Response) {
try {
const { id } = req.params;
await dockerService.stopContainer(id);
res.json({ message: 'Container stopped successfully' });
} catch (error) {
console.error('Error stopping container:', error);
res.status(500).json(toError('Failed to stop container'));
}
}
async restartContainer(req: AuthRequest, res: Response) {
try {
const { id } = req.params;
await dockerService.restartContainer(id);
res.json({ message: 'Container restarted successfully' });
} catch (error) {
console.error('Error restarting container:', error);
res.status(500).json(toError('Failed to restart container'));
}
}
async getContainerLogs(req: AuthRequest, res: Response) {
try {
const { id } = req.params;
const tail = parseInt(req.query.tail as string) || 100;
const logs = await dockerService.getContainerLogs(id, tail);
res.json({ logs });
} catch (error) {
console.error('Error getting container logs:', error);
res.status(500).json(toError('Failed to retrieve container logs'));
}
}
async getContainerStats(req: AuthRequest, res: Response) {
try {
const { id } = req.params;
const stats = await dockerService.getContainerStats(id);
if (!stats) {
return res.status(404).json(toError('Container stats not available'));
}
res.json(stats);
} catch (error) {
console.error('Error getting container stats:', error);
res.status(500).json(toError('Failed to retrieve container stats'));
}
}
}
@@ -0,0 +1,31 @@
import { Response } from 'express';
import { SystemService } from '../services/systemService';
import { AuthRequest } from '../types';
import { toError } from '../utils/helper';
const systemService = new SystemService();
export class SystemController {
async getStats(req: AuthRequest, res: Response) {
try {
const stats = await systemService.getSystemStats();
res.json(stats);
} catch (error) {
console.error('Error getting system stats: ', error);
res.status(500).json(toError('Failed to retrieve system statistics'));
}
}
async getUptime(req: AuthRequest, res: Response) {
try {
const stats = await systemService.getSystemStats();
res.json({
uptime: stats.uptime,
formatted: systemService.formatUptime(stats.uptime)
});
} catch (error) {
console.error('Error getting uptime:', error);
res.status(500).json(toError('Failed to retrieve uptime'));
}
}
}
+9
View File
@@ -0,0 +1,9 @@
import bcrypt from 'bcryptjs';
const pw = process.argv[2];
if (!pw) {
console.error('Argument muss übergeben werden!');
process.exit(-1);
}
const hash = bcrypt.hashSync(pw, 10);
console.log(`Hash: ${hash}`);
+86
View File
@@ -0,0 +1,86 @@
import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import dotenv from 'dotenv';
import rateLimit from 'express-rate-limit';
import { AuthController } from './controllers/authController';
import { SystemController } from './controllers/systemController';
import { authMiddleware } from './middleware/auth';
import { toError } from './utils/helper';
import { DockerController } from './controllers/dockerController';
dotenv.config();
const app = express();
const PORT = process.env.PORT || 4000;
app.use(helmet());
app.use(cors({
origin: process.env.FRONTEND_URL || '*',
credentials: true
}));
app.use(express.json());
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 Minuten
max: 100 // Max 100 Requests pro IP
});
app.use('/api/', limiter);
const authController = new AuthController();
const systemController = new SystemController();
const dockerController = new DockerController();
// Health Check
app.get('/health', (req, res) => {
res.json({ status: 'ok', timestamp: new Date().toISOString() });
});
// Auth Routes (ohne authMiddleware)
app.post('/api/auth/login', authController.login.bind(authController));
app.post('/api/auth/register', authController.register.bind(authController));
// Protected Routes
app.get('/api/auth/me', authMiddleware, authController.me.bind(authController));
// System Routes
app.get('/api/system/stats', authMiddleware, systemController.getStats.bind(systemController));
app.get('/api/system/uptime', authMiddleware, systemController.getUptime.bind(systemController));
// Docker Routes
app.get('/api/docker/containers', authMiddleware, dockerController.getContainers.bind(dockerController));
app.get('/api/docker/containers/:id', authMiddleware, dockerController.getContainer.bind(dockerController));
app.post('/api/docker/containers/:id/start', authMiddleware, dockerController.startContainer.bind(dockerController));
app.post('/api/docker/containers/:id/stop:', authMiddleware, dockerController.stopContainer.bind(dockerController));
app.post('/api/docker/containers/:id/restart', authMiddleware, dockerController.restartContainer.bind(dockerController));
app.get('/api/docker/containers/:id/logs', authMiddleware, dockerController.getContainerLogs.bind(dockerController));
app.get('/api/docker/containers/:id/stats', authMiddleware, dockerController.getContainerStats.bind(dockerController));
// Error Handler
app.use((err: Error, req: express.Request, res: express.Response, next: express.NextFunction) => {
console.error('Error:', err);
res.status(500).json(toError('Internal server error'));
});
// 404 Handler
app.use((req, res) => {
res.status(404).json(toError('Route not found'));
});
// Server starten
app.listen(PORT, () => {
console.log(`🚀 Server running on port ${PORT}`);
console.log(`📊 Environment: ${process.env.NODE_ENV || 'development'}`);
console.log(`🔒 JWT Secret configured: ${!!process.env.JWT_SECRET}`);
});
// Graceful shutdown
process.on('SIGTERM', () => {
console.log('SIGTERM signal received: closing HTTP server');
process.exit(0);
});
process.on('SIGINT', () => {
console.log('SIGTERM signal received: closing HTTP server');
process.exit(0);
});
+39
View File
@@ -0,0 +1,39 @@
import { NextFunction, Response } from "express";
import jwt from 'jsonwebtoken';
import { AuthRequest } from "../types";
const JWT_SECRET = process.env.JWT_SECRET || "changeit";
export const authMiddleware = (
req: AuthRequest,
res: Response,
next: NextFunction
) => {
try {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'No token provided' });
}
const token = authHeader.substring(7);
const decoded = jwt.verify(token, JWT_SECRET) as {
id: string;
username: string;
};
req.user = decoded;
next();
} catch (error) {
return res.status(401).json({ error: 'Invalid token' });
}
};
export const generateToken = (user: { id: string; username: string }): string => {
return jwt.sign(
{ id: user.id, username: user.username },
JWT_SECRET,
{ expiresIn: '7d' }
);
};
+128
View File
@@ -0,0 +1,128 @@
import Docker from 'dockerode';
import { DockerContainer, DockerStats } from '../types';
export class DockerService {
private docker: Docker;
constructor() {
this.docker = new Docker({ socketPath: '/var/run/docker.sock' });
}
async getContainers(): Promise<DockerContainer[]> {
try {
const containers = await this.docker.listContainers({ all: true });
return containers.map((container) => ({
id: container.Id.substring(0, 12),
name: container.Names[0].replace('/', ''),
image: container.Image,
state: container.State,
status: container.Status,
created: container.Created,
ports: container.Ports.map(port => ({
privatePort: port.PrivatePort,
publicPort: port.PublicPort,
type: port.Type
}))
}));
} catch (error) {
console.error('Error getting containers:', error);
throw new Error('Failed to retrieve Docker containers');
}
}
async getContainer(id: string): Promise<DockerContainer | null> {
try {
const container = this.docker.getContainer(id);
const info = await container.inspect();
return {
id: info.Id.substring(0, 12),
name: info.Name.replace('/', ''),
image: info.Config.Image,
state: info.State.Status,
status: info.State.Running ? 'running' : 'stopped',
created: new Date(info.Created).getTime() / 1000,
ports: Object.entries(info.NetworkSettings.Ports || {}).flatMap(([port, bindings]) => {
if (!bindings) return [];
return bindings.map(binding => ({
privatePort: parseInt(port.split('/')[0]),
publicPort: binding.HostPort ? parseInt(binding.HostPort) : undefined,
type: port.split('/')[1]
}));
})
};
} catch (error) {
console.error('Error getting container:', error);
return null;
}
}
async startContainer(id: string): Promise<void> {
try {
const container = this.docker.getContainer(id);
await container.start();
} catch (error) {
console.error('Error starting container:', error);
throw new Error('Failed to start container');
}
}
async stopContainer(id: string): Promise<void> {
try {
const container = this.docker.getContainer(id);
await container.stop();
} catch (error) {
console.error('Error stopping container:', error);
throw new Error('Failed to stop container');
}
}
async restartContainer(id: string): Promise<void> {
try {
const container = this.docker.getContainer(id);
await container.restart();
} catch (error) {
console.error('Error restarting container:', error);
throw new Error('Failed to restart container');
}
}
async getContainerLogs(id: string, tail: number = 100): Promise<string> {
try {
const container = this.docker.getContainer(id);
const logs = await container.logs({
stdout: true,
stderr: true,
tail,
timestamps: true
});
return logs.toString('utf-8');
} catch (error) {
console.error('Error getting container logs:', error);
throw new Error('Failed to retrieve container logs');
}
}
async getContainerStats(id: string): Promise<DockerStats | null> {
try {
const container = this.docker.getContainer(id);
const stats = await container.stats({ stream: false });
const cpuDelta = stats.cpu_stats.cpu_usage.total_usage - stats.precpu_stats.cpu_usage.total_usage;
const systemDelta = stats.cpu_stats.system_cpu_usage - stats.precpu_stats.system_cpu_usage;
const cpuUsage = (cpuDelta / systemDelta) * stats.cpu_stats.online_cpus * 100;
return {
cpuUsage: Math.round(cpuUsage * 10) / 10,
memoryUsage: stats.memory_stats.usage,
memoryLimit: stats.memory_stats.limit,
networkRx: stats.networks?.eth0?.rx_bytes || 0,
networkTx: stats.networks?.eth0?.tx_bytes || 0
};
} catch (error) {
console.error('Error getting container stats:', error);
return null;
}
}
}
+68
View File
@@ -0,0 +1,68 @@
import si from 'systeminformation';
import { SystemStats } from "../types";
export class SystemService {
async getSystemStats(): Promise<SystemStats> {
try {
const [cpu, mem, fsSize, currentLoad, osInfo, cpuTemp] = await Promise.all([
si.cpu(),
si.mem(),
si.fsSize(),
si.currentLoad(),
si.osInfo(),
si.cpuTemperature()
]);
const disks = fsSize
.filter(disk =>
disk.mount !== '/boot' &&
disk.mount !== '/dev' &&
!disk.mount.startsWith('/var/lib/docker') &&
disk.size > 0
)
.map(disk => ({
device: disk.fs,
mountpoint: disk.mount,
size: disk.size,
used: disk.used,
available: disk.available,
percentage: disk.use
}));
return {
cpu: {
usage: Math.round(currentLoad.currentLoad * 10) / 10,
temp: cpuTemp.main || null,
model: cpu.brand
},
memory: {
total: mem.total,
used: mem.used,
free: mem.free,
percentage: Math.round((mem.used / mem.total) * 100 * 10) / 10
},
disk: disks,
// TODO: Wo bekommt man die Uptime her?
uptime: 0,
hostname: osInfo.hostname
};
} catch (error) {
console.error('Error getting system stats:', error);
throw new Error('Failed to retrieve system statistics');
}
}
formatUptime(seconds: number): string {
const days = Math.floor(seconds / 86400);
const hours = Math.floor((seconds % 86400) / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
if (days > 0) {
return `${days}d ${hours}h`;
} else if (hours > 0) {
return `${hours}h ${minutes}m`;
} else {
return `${minutes}m`;
}
}
}
+78
View File
@@ -0,0 +1,78 @@
import { Request } from 'express';
export interface User {
id: string;
username: string;
password: string;
createdAt: Date;
}
export interface AuthRequest extends Request {
user?: {
id: string;
username: string;
};
}
export interface SystemStats {
cpu: {
usage: number;
temp: number | null;
model: string;
};
memory: {
total: number;
used: number;
free: number;
percentage: number;
};
disk: Array<{
device: string;
mountpoint: string;
size: number;
used: number;
available: number;
percentage: number;
}>;
uptime: number;
hostname: string;
}
export interface DockerContainer {
id: string;
name: string;
image: string;
state: string;
status: string;
created: number;
ports: Array<{
privatePort: number;
publicPort?: number;
type: string;
}>;
}
export interface DockerStats {
cpuUsage: number;
memoryUsage: number;
memoryLimit: number;
networkRx: number;
networkTx: number;
}
export interface LoginRequest {
username: string;
password: string;
}
export interface LoginResponse {
token: string;
user: {
id: string;
username: string;
};
}
export interface ErrorResponse {
error: string;
}
+5
View File
@@ -0,0 +1,5 @@
import { ErrorResponse } from "../types";
export const toError = (errorText: string): ErrorResponse => {
return { error: errorText };
}
+27
View File
@@ -0,0 +1,27 @@
{
"compilerOptions": {
"target": "es2020",
"module": "commonjs",
"lib": [
"ES2020"
],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"moduleResolution": "node",
"declaration": true,
"declarationMap": true,
"sourceMap": true
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules",
"dist"
]
}
+24
View File
@@ -0,0 +1,24 @@
services:
unraid-monitor:
build: .
container_name: unraid-monitor
restart: unless-stopped
ports:
- "10000:10000"
environment:
- NODE_ENV=production
- JWT_SECRET=${JWT_SECRET:-change-this-to-a-secure-random-string}
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
networks:
- unraid-monitor
healthcheck:
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:4000/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 10s
networks:
unraid-monitor:
driver: bridge
+16
View File
@@ -0,0 +1,16 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<meta name="description" content="Monitor and manage your Unraid server" />
<meta name="theme-color" content="#ff8c2f" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<title>Unraid Monitor</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+9058
View File
File diff suppressed because it is too large Load Diff
+37
View File
@@ -0,0 +1,37 @@
{
"name": "unraid-monitor-frontend",
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
"lint": "eslint . --ext ts,tsx"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.21.1",
"@tanstack/react-query": "^5.17.9",
"axios": "^1.6.5",
"zustand": "^4.4.7",
"recharts": "^2.10.3",
"lucide-react": "^0.307.0",
"clsx": "^2.1.0",
"tailwind-merge": "^2.2.0"
},
"devDependencies": {
"@types/react": "^18.2.47",
"@types/react-dom": "^18.2.18",
"@vitejs/plugin-react": "^4.2.1",
"vite": "^5.0.11",
"vite-plugin-pwa": "^0.17.4",
"typescript": "^5.3.3",
"autoprefixer": "^10.4.16",
"postcss": "^8.4.33",
"tailwindcss": "^3.4.1",
"eslint": "^8.56.0",
"@typescript-eslint/eslint-plugin": "^6.18.1",
"@typescript-eslint/parser": "^6.18.1"
}
}
+6
View File
@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
+56
View File
@@ -0,0 +1,56 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useAuthStore } from "./stores/authStore";
import { BrowserRouter, Navigate, Route, Routes } from "react-router-dom";
import Login from "./components/Login";
import Layout from "./components/Layout";
import Dashboard from "./components/Dashboard";
import Containers from "./components/Containers";
const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: 1,
refetchOnWindowFocus: false,
},
},
});
function ProtectedRoute({ children }: { children: React.ReactNode }) {
const isAuthenticated = useAuthStore((state) => state.isAuthenticated);
return isAuthenticated ? <>{children}</> : <Navigate to="/login" />;
}
function App() {
return (
<QueryClientProvider client={queryClient}>
<BrowserRouter>
<Routes>
<Route path="/login" element={<Login />} />
<Route
path="/"
element={
<ProtectedRoute>
<Layout>
<Dashboard />
</Layout>
</ProtectedRoute>
}
/>
<Route
path="/containers"
element={
<ProtectedRoute>
<Layout>
<Containers />
</Layout>
</ProtectedRoute>
}
/>
<Route path="*" element={<Navigate to="/" />} />
</Routes>
</BrowserRouter>
</QueryClientProvider>
);
}
export default App;
+219
View File
@@ -0,0 +1,219 @@
import { formatDate } from "../lib/utils";
import { dockerApi } from "../lib/api";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { AlertCircle, Box, CheckCircle, Play, RotateCw, Square } from "lucide-react";
import { useState } from "react";
export default function Containers() {
const queryClient = useQueryClient();
const [actionLoading, setActionLoading] = useState<string | null>(null);
const [selectedContainer, setSelectedContainer] = useState<string | null>(null);
const { data: containers, isLoading, error } = useQuery({
queryKey: ['containers'],
queryFn: async () => {
const response = await dockerApi.getContainers();
return response.data;
},
refetchInterval: 5000,
});
const startMutation = useMutation({
mutationFn: (id: string) => dockerApi.startContainer(id),
onMutate: (id) => setActionLoading(id),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['containers'] });
},
onSettled: () => setActionLoading(null),
});
const stopMutation = useMutation({
mutationFn: (id: string) => dockerApi.stopContainer(id),
onMutate: (id) => setActionLoading(id),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['containers'] });
},
onSettled: () => setActionLoading(null),
});
const restartMutation = useMutation({
mutationFn: (id: string) => dockerApi.restartContainer(id),
onMutate: (id) => setActionLoading(id),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['containers'] });
},
onSettled: () => setActionLoading(null),
});
if (isLoading) {
return (
<div className="flex items-center justify-center h-96">
<div className="text-gray-400">Lade Container...</div>
</div>
);
}
if (error) {
return (
<div className="flex items-center justify-center h-96">
<div className="card max-w-md">
<div className="flex items-center gap-3 text-red-400">
<AlertCircle size={24} />
<div>
<h3 className="font-semibold">Fehler beim Laden</h3>
<p className="text-sm text-gray-400">
Container konnten nicht geladen erden
</p>
</div>
</div>
</div>
</div>
);
}
const runningContainers = containers?.filter((c) => c.state === 'running') || [];
const stoppedContainers = containers?.filter((c) => c.state !== 'running') || [];
return (
<div className="space-y-6">
<div>
<h2 className="text-2xl font-bold mb-2">Docker Containers</h2>
<p className="text-gray-400">
{runningContainers.length} laufend · {stoppedContainers.length} gestopped
</p>
</div>
{/* Running Containers */}
{runningContainers.length > 0 && (
<div className="space-y-3">
<h3 className="text-lg font-semibold flex items-center gap-2">
<CheckCircle className="text-green-500" size={20} />
Laufende Container
</h3>
<div className="grid gap-3">
{runningContainers.map((container) => (
<div
key={container.id}
className="card hover:border-gray-700 transition-colors cursor-pointer"
onClick={() =>
setSelectedContainer(selectedContainer === container.id ? null : container.id)
}
>
<div className="flex items-center justify-between">
<div className="flex items-center gap-4 flex-1">
<Box className="text-unraid-orange" size={24} />
<div className="flex-1 min-w-0">
<h4 className="font-semibold truncate">{container.name}</h4>
<p className="text-sm text-gray-400 truncate">{container.image}</p>
</div>
<div className="hidden sm:flex items-center gap-2">
<div className="w-2 h-2 bg-green-500" rounded-full animate-pulse />
<span className="text-sm text-green-500">Running</span>
</div>
</div>
<div className="flex items-center gap-2">
<button
onClick={(e) => {
e.stopPropagation();
stopMutation.mutate(container.id);
}}
disabled={actionLoading === container.id}
className="btn-danger p-2"
title="Stop"
>
<Square size={16} />
</button>
<button
onClick={(e) => {
e.stopPropagation();
restartMutation.mutate(container.id);
}}
disabled={actionLoading === container.id}
className="btn-secondary p-2"
title="Restart"
>
<RotateCw size={16} />
</button>
</div>
</div>
{selectedContainer === container.id && (
<div className="mt-4 pt-4 border-t border-gray-800 space-y-2 text-sm">
<div className="flex justify-between">
<span className="text-gray-400">ID:</span>
<span className="font-mono">{container.id}</span>
</div>
<div className="flex justify-between">
<span className="text-gray-400">Status:</span>
<span>{container.status}</span>
</div>
<div className="flex justify-between">
<span className="text-gray-400">Erstellt:</span>
<span>{formatDate(container.created)}</span>
</div>
{container.ports.length > 0 && (
<div>
<span className="text-gray-400">Ports:</span>
<div className="mt-1 space-y-1">
{container.ports.map((port, idx) => (
<div key={idx} className="font-mono text-xs">
{port.publicPort
? `${port.publicPort}${port.privatePort}/${port.type}`
: `${port.privatePort}/${port.type}`}
</div>
))}
</div>
</div>
)}
</div>
)}
</div>
))}
</div>
</div>
)}
{/* Stopped Containers */}
{stoppedContainers.length > 0 && (
<div className="space-y-3">
<h3 className="text-lg font-semibold flex items-center gap-2">
<AlertCircle className="text-gray-500" size={20} />
Gestoppte Container
</h3>
<div className="grid gap-3">
{stoppedContainers.map((container) => (
<div
key={container.id}
className="card hover:border-gray-700 transition-colors opacity-75"
>
<div className="flex items-center justify-between">
<div className="flex items-center gap-4 flex-1">
<Box className="text-gray-600" size={24} />
<div className="flex-1 min-w-0">
<h4 className="font-semibold truncate">{container.name}</h4>
<p className="text-sm text-gray-400 truncate">{container.image}</p>
</div>
<div className="hidden sm:flex items-center gap-2">
<div className="w-2 h-2 bg-gray-600 rounded-full" />
<span className="text-sm text-gray-500">Stopped</span>
</div>
</div>
<button
onClick={() => startMutation.mutate(container.id)}
disabled={actionLoading === container.id}
className="btn-primary p-2"
title="Start"
>
<Play size={16} />
</button>
</div>
</div>
))}
</div>
</div>
)}
</div>
);
}
+210
View File
@@ -0,0 +1,210 @@
import { dockerApi, systemApi } from "../lib/api";
import { formatBytes, formatUptime } from "../lib/utils";
import { useQuery } from "@tanstack/react-query";
import { Activity, AlertCircle, Cpu, HardDrive, Server } from "lucide-react";
export default function Dashboard() {
const { data: stats, isLoading: statsLoading, error: statsError } = useQuery({
queryKey: ['systemStats'],
queryFn: async () => {
const response = await systemApi.getStats();
return response.data;
},
refetchInterval: 5000, //Update alle 5 Sekunden
});
const { data: containers, isLoading: containersLoading } = useQuery({
queryKey: ['containers'],
queryFn: async () => {
const response = await dockerApi.getContainers();
return response.data;
},
refetchInterval: 10000, //Update all 10 Sekunden
});
if (statsLoading) {
return (
<div className="flex items-center justify-center h-96">
<div className="text-gray-400">Lade System-Statistiken...</div>
</div>
);
}
if (statsError) {
return (
<div className="flex items-center justify-center h-96">
<div className="card max-w-md">
<div className="flex items-center gap-3 text-red-400">
<AlertCircle size={24} />
<div>
<h3 className="font-semibold">Fehler beim Laden</h3>
<p className="text-sm text-gray-400">
System-Statistiken konnten nicht geladen werden
</p>
</div>
</div>
</div>
</div>
);
}
const runningContainers = containers?.filter((c) => c.state === 'running').length || 0;
const totalContainers = containers?.length || 0;
return (
<div className="space-y-6">
<div>
<h2 className="text-2xl font-bold mb-2">Dashboard</h2>
<p className="text-gray-400">Übersicht über deinen Unraid-Server</p>
</div>
{/* System Stats Grid */}
<div className="grid grind-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
{/* CPU */}
<div className="card">
<div className="flex items-center justify-between mb-3">
<div className="flex items-center gap-2">
<Cpu className="text-unraid-orange" size={20} />
<h3 className="font-semibold">CPU</h3>
</div>
<span className="text-2xl font-bold">{stats?.cpu.usage.toFixed(1)}%</span>
</div>
<div className="space-y-2">
<div className="w-full bg-gray-800 rounded-full h-2">
<div className="bg-unraid-orange h-2 rounded-full transition-all duration-300" style={{ width: `${stats?.cpu.usage}%` }}></div>
</div>
<div className="text-xs text-gray-400 flex justify-between">
<span>{stats?.cpu.model}</span>
{stats?.cpu.temp && <span>{stats.cpu.temp}°C</span>}
</div>
</div>
</div>
{/* Memory */}
<div className="card">
<div className="flex items-center justify-between mb-3">
<div className="flex items-center gap-2">
<Activity className="text-blue-400" size={20} />
<h3 className="font-semibold">RAM</h3>
</div>
<span className="text-2xl font-bold">{stats?.memory.percentage.toFixed(1)}%</span>
</div>
<div className="space-y-2">
<div className="w-full bg-gray-800 rounded-full h-2">
<div
className="bg-blue-400 h-2 rounded-full transition-all duration-300"
style={{ width: `${stats?.memory.percentage}%` }}
/>
</div>
<div className="text-xs text-gray-400">
{formatBytes(stats?.memory.used || 0)} / {formatBytes(stats?.memory.total || 0)}
</div>
</div>
</div>
{/* Disk */}
<div className="card">
<div className="flex items-center justify-between mb-3">
<div className="flex items-center gap-2">
<HardDrive className="text-green-400" size={20} />
<h3 className="font-semibold">Disk</h3>
</div>
<span className="text-2xl font-bold">
{stats?.disk[0]?.percentage.toFixed(1)}%
</span>
</div>
<div className="space-y-2">
<div className="w-full bg-gray-800 rounded-full h-2">
<div
className="bg-green-400 h-2 rounded-full transition-all duration-300"
style={{ width: `${stats?.disk[0]?.percentage}%` }}
/>
</div>
<div className="text-xs text-gray-400">
{formatBytes(stats?.disk[0]?.used || 0)} / {formatBytes(stats?.disk[0]?.size || 0)}
</div>
</div>
</div>
{/* Uptime & Containers */}
<div className="card">
<div className="flex items-center gap-2 mb-3">
<Server className="text-purple-400" size={20} />
<h3 className="font-semibold">System</h3>
</div>
<div className="space-y-3">
<div>
<div className="text-xs text-gray-400 mb-1">Uptime</div>
<div className="text-lg font-semibold">
{formatUptime(stats?.uptime || 0)}
</div>
</div>
<div>
<div className="text-xs text-gray-400 mb-1">Container</div>
<div className="text-lg font-semibold">
{runningContainers} / {totalContainers}
</div>
</div>
</div>
</div>
</div>
{/* Disk Details */}
{stats?.disk && stats.disk.length > 0 && (
<div className="card">
<h3 className="text-lg font-semibold mb-4">Festplatten</h3>
<div className="space-y-4">
{stats.disk.map((disk, index) => (
<div key={index} className="space-y-2">
<div className="flex items-center justify-between text-sm">
<span className="text-gray-400">{disk.mountpoint}</span>
<span className="font-semibold">{disk.percentage.toFixed(1)}%</span>
</div>
<div className="w-full bg-gray-800 rounded-full h-2">
<div
className={`h-2 rounded-full transition-all duration-300 ${
disk.percentage > 90
? 'bg-red-500'
: disk.percentage > 75
? 'bg-yellow-500'
: 'bg-green-500'
}`}
style={{ width: `${disk.percentage}%` }}
/>
</div>
<div className="flex justify-between text-xs text-gray-400">
<span>{disk.device}</span>
<span>
{formatBytes(disk.used)} / {formatBytes(disk.size)}
</span>
</div>
</div>
))}
</div>
</div>
)}
{/* Quick Container Overview */}
{!containersLoading && containers && (
<div className="card">
<h3 className="text-lg font-semibold mb-4">Container-Übersicht</h3>
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3">
{containers.slice(0, 8).map((container) => (
<div
key={container.id}
className="bg-gray-800 rounded-lg p-3 flex items-center gap-2"
>
<div
className={`w-2 h-2 rounded-full ${
container.state === 'running' ? 'bg-green-500' : 'bg-gray-600'
}`}
/>
<span className="text-sm truncate">{container.name}</span>
</div>
))}
</div>
</div>
)}
</div>
);
}
+103
View File
@@ -0,0 +1,103 @@
import { useAuthStore } from "../stores/authStore";
import { Box, Home, LogOut, Server } from "lucide-react";
import { ReactNode } from "react";
import { NavLink, useNavigate } from "react-router-dom";
interface LayoutProps {
children: ReactNode;
}
export default function Layout({ children }: LayoutProps) {
const { user, logout } = useAuthStore();
const navigate = useNavigate();
const handleLogout = () => {
logout();
navigate('/login');
};
const navItems = [
{ to: '/', icon: Home, label: 'Dashboard' },
{ to: '/containers', icon: Box, label: 'Container' },
];
return (
<div className="min-h-screen bg-gray-950">
{/* Header */}
<header className="bg-gray-900 border-b border-gray-800 sticky top-0 z-50">
<div className="max-2-7xl mx-auto px-4 py-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="bg-unraid-orange p-2 rounded-lg">
<Server size={24} />
</div>
<h1 className="text-xl font-bold">Unraid Monitor</h1>
</div>
<div className="flex items-center gap-4">
<span className="text-sm text-gray-400">{user?.username}</span>
<button
onClick={handleLogout}
className="flex items-center gap-2 text-gray-400 hover:text-white transition-colors"
>
<LogOut size={20} />
<span className="hidden sm:inline">Abmelden</span>
</button>
</div>
</div>
</div>
</header>
{/* Mobile Navigation */}
<nav className="md:hidden bg-gray-900 border-b border-gray-800 sticky top-[73px] z-40">
<div className="flex">
{navItems.map((item) => (
<NavLink
key={item.to}
to={item.to}
className={({isActive}) =>
`flex-1 flex flex-col items-center gap-1 py-3 transition-colors ${
isActive
? 'text-unraid-orange border-b-2 border-unraid-orange'
: 'text-gray-400 hover:text-white'
}`
}
>
<item.icon size={20} />
<span className="text-xs">{item.label}</span>
</NavLink>
))}
</div>
</nav>
<div className="flex">
{/* Desktop Sidebar */}
<aside className="hidden md:block w-64 bg-gray-900 min-h-[calc(100vh-73px)] border-r border-gray-800 sticky top-[73px]">
<nav className="p-4 space-y-2">
{navItems.map((item) => (
<NavLink
key={item.to}
to={item.to}
className={({isActive}) =>
`flex items-center gap-3 px-4 py-3 rounded-lg transition-colors ${
isActive
? 'bg-unraid-orange text-white'
: 'text-gray-400 hover:bg-gray-800 hover:text-white'
}`
}
>
<item.icon size={20} />
<span>{item.label}</span>
</NavLink>
))}
</nav>
</aside>
{/* Main Content */}
<main className="flex-1 p-4 md:p-6 max-w-7xl mx-auto w-full">
{children}
</main>
</div>
</div>
);
}
+91
View File
@@ -0,0 +1,91 @@
import { authApi } from "../lib/api";
import { useAuthStore } from "../stores/authStore";
import { Server } from "lucide-react";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
export default function Login() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
const login = useAuthStore((state) => state.login);
const navigate = useNavigate();
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
setLoading(true);
try {
const response = await authApi.login({ username, password });
login(response.data.token, response.data.user);
navigate('/');
} catch (err: any) {
setError(err.response?.data?.error || 'Login fehlgeschlagen');
} finally {
setLoading(false);
}
};
return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-gray-950 via gray-900 to-unraid-dark">
<div className="card max-w-md w-full mx-4">
<div className="flex flex-col items-center mb-8">
<div className="bg-unraid-orange p-4 rounded-full mb-4">
<Server size={48} />
</div>
<h1 className="text-3xl font-bold">Unraid Monitor</h1>
<p className="text-gray-400 mt-2">Melde dich an um fortzufahren</p>
</div>
<form onSubmit={handleSubmit} className="space-y-4">
{error && (
<div className="bg-red-900/50 border border-red-700 text-red-200 px-4 py-3 rounded-lg">
{error}
</div>
)}
<div>
<label htmlFor="username" className="block text-sm font-medium mb-2">Benutzername</label>
<input
id="username"
type="text"
className="input w-full"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
autoComplete="username"
/>
</div>
<div>
<label htmlFor="password" className="block text-sm font-medium mb-2">Passwort</label>
<input
id="password"
type="password"
className="input w-full"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
autoComplete="current-password"
/>
</div>
<button
type="submit"
className="btn-primary w-full"
disabled={loading}
>
{loading ? 'Anmelden...' : 'Anmelden'}
</button>
</form>
<div className="mt-6 text-center text-sm text-gray-400">
<p>Standard-Login: admin / admin</p>
</div>
</div>
</div>
);
}
+31
View File
@@ -0,0 +1,31 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
body {
@apply bg-gray-950 text-white;
}
}
@layer components {
.card {
@apply bg-gray-900 rounded-lg p-4 shadow-lg border border-gray-800;
}
.btn-primary {
@apply bg-unraid-orange hover:bg-unraid-orange-dark text-white font-semibold py-2 px-4 rounded-lg transition-colors;
}
.btn-secondary {
@apply bg-gray-800 hover:bg-gray-700 text-white font-semibold py-2 px-4 rounded-lg transition-colors;
}
.btn-danger {
@apply bg-red-600 hover:bg-red-700 text-white font-semibold py-2 px-4 rounded-lg transition-colors;
}
.input {
@apply bg-gray-800 border border-gray-700 text-white rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-unraid-orange;
}
}
+106
View File
@@ -0,0 +1,106 @@
import { useAuthStore } from "../stores/authStore";
import axios from "axios";
const API_BASE_URL = import.meta.env.VITE_API_URL || '/api';
const api = axios.create({
baseURL: API_BASE_URL,
headers: {
'Content-Type': 'application/json',
},
});
api.interceptors.request.use((config) => {
const token = useAuthStore.getState().token;
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
api.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401) {
useAuthStore.getState().logout();
}
return Promise.reject(error);
}
);
export interface SystemStats {
cpu: {
usage: number;
temp: number | null;
model: string;
};
memory: {
total: number;
used: number;
free: number;
percentage: number;
};
disk: Array<{
device: string;
mountpoint: string;
size: number;
used: number;
available: number;
percentage: number;
}>;
uptime: number;
hostname: string;
}
export interface DockerContainer {
id: string;
name: string;
image: string;
state: string;
status: string;
created: number;
ports: Array<{
privatePort: number;
publicPort?: number;
type: string;
}>;
}
export interface LoginCredentials {
username: string;
password: string;
}
export interface LoginResponse {
token: string;
user: {
id: string;
username: string;
};
}
export const authApi = {
login: (credentials: LoginCredentials) =>
api.post<LoginResponse>('/auth/login', credentials),
register: (credentials: LoginCredentials) =>
api.post<LoginResponse>('/auth/register', credentials),
me: () => api.get('/auth/me'),
};
export const systemApi = {
getStats: () => api.get<SystemStats>('/system/stats'),
getUptime: () => api.get('/system/uptime'),
};
export const dockerApi = {
getContainers: () => api.get<DockerContainer[]>('/docker/containers'),
getContainer: (id: string) => api.get<DockerContainer>(`/docker/containers/${id}`),
startContainer: (id: string) => api.post(`/docker/containers/${id}/start`),
stopContainer: (id: string) => api.post(`/docker/containers/${id}/stop`),
restartContainer: (id: string) => api.post(`/docker/containers/${id}/restart`),
getContainerLogs: (id: string, tail?: number) => api.get(`/docker/containers/${id}/logs`, { params: { tail } }),
getContainerStats: (id: string) => api.get(`/docker/containers/${id}/stats`),
};
export default api;
+33
View File
@@ -0,0 +1,33 @@
export function formatBytes(bytes: number, decimals = 2): string {
if (bytes === 0) return '0 Bytes';
const k = 1204;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
export function formatUptime(seconds: number): string {
const days = Math.floor(seconds / 86400);
const hours = Math.floor((seconds % 86400) / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
if (days > 0) {
return `${days}d ${hours}h`;
} else if (hours > 0) {
return `${hours}h ${minutes}m`;
} else {
return `${minutes}m`;
}
}
export function formatDate(timestamp: number): string {
return new Date(timestamp * 1000).toLocaleString('de-DE');
}
export function cn(...classes: (string | boolean | undefined)[]): string {
return classes.filter(Boolean).join(' ');
}
+11
View File
@@ -0,0 +1,11 @@
import React from 'react';
import App from './App';
import './index.css';
import ReactDOM from 'react-dom/client';
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
+32
View File
@@ -0,0 +1,32 @@
import { create } from "zustand";
import { persist } from "zustand/middleware";
interface User {
id: string;
username: string;
}
interface AuthState {
token: string | null;
user: User | null;
isAuthenticated: boolean;
login: (token: string, user: User) => void;
logout: () => void;
}
export const useAuthStore = create<AuthState>()(
persist(
(set) => ({
token: null,
user: null,
isAuthenticated: false,
login: (token: string, user: User) =>
set({ token, user, isAuthenticated: true }),
logout: () =>
set({ token: null, user: null, isAuthenticated: false }),
}),
{
name: 'auth-storage',
}
)
);
+10
View File
@@ -0,0 +1,10 @@
/// <reference types="vite/client" />
/// <reference types="vite-plugin-pwa/client" />
interface ImportMetaEnv {
readonly VITE_API_URL: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}
+20
View File
@@ -0,0 +1,20 @@
/** @type {import('tailwindcss').Config} */
export default {
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {
colors: {
unraid: {
orange: '#ff8c2f',
'orange-dark': '#e67922',
dark: '#1a1a1a',
'dark-lighter': '#2d2d2d',
}
}
},
},
plugins: [],
}
+31
View File
@@ -0,0 +1,31 @@
{
"compilerOptions": {
"target": "es2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "esnext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
/* Paths */
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}
+12
View File
@@ -0,0 +1,12 @@
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "esnext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true
},
"include": [
"vite.config.ts"
]
}
+69
View File
@@ -0,0 +1,69 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { VitePWA } from 'vite-plugin-pwa';
export default defineConfig({
plugins: [
react(),
VitePWA({
registerType: 'autoUpdate',
includeAssets: ['favicon.ico', 'robots.txt', 'apple-touch-icon.png'],
manifest: {
name: 'Unraid Monitor',
short_name: 'Unraid Monitor',
description: 'Monitor and manage your Unraid server',
theme_color: '#ff8c2f',
background_color: '#1a1a1a',
display: 'standalone',
orientation: 'portrait',
icons: [
{
src: '/icon-192.png',
sizes: '192x192',
type: 'image/png'
},
{
src: '/icon-512.png',
sizes: '512x512',
type: 'image/png'
},
{
src: '/icon-512.png',
sizes: '512x512',
type: 'image/png',
purpose: "any maskable"
}
]
},
workbox: {
globPatterns: ['**/*.{js,css,html,ico,png,svg}'],
runtimeCaching: [
{
urlPattern: /^https:\/\/api\..*/i,
handler: 'NetworkFirst',
options: {
cacheName: 'api-cache',
expiration: {
maxEntries: 10,
maxAgeSeconds: 60 * 5 // 5 Minuten
}
}
}
]
}
})
],
server: {
port: 10000,
proxy: {
'/api': {
target: 'http://localhost:4000',
changeOrigin: true
}
}
},
build: {
outDir: 'dist',
sourcemap: false
}
});
+53
View File
@@ -0,0 +1,53 @@
server {
listen 10000;
server_name localhost;
root /app/frontend/dist;
index index.html;
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
# API Proxy zum Backend
location /api/ {
proxy_pass http://127.0.0.1:4000/api/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
proxy_read_timeout 86400;
}
# Health Check Endpoint
location /health {
proxy_pass http://127.0.0.1:4000/health;
proxy_http_version 1.1;
proxy_set_header Host $host;
}
# Frontend Static Files
location / {
try_files $uri $uri/ /index.html;
# Cache static assets
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
}
# Security Headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
# Disable access to hidden files
location ~ /\. {
deny all;
}
}
+27
View File
@@ -0,0 +1,27 @@
[supervisord]
nodaemon=true
user=root
logfile=/var/log/supervisord.log
pidfile=/var/run/supervisord.pid
[program:nginx]
command=/usr/sbin/nginx -g "daemon off;"
autostart=true
autorestart=true
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
priority=10
[program:backend]
command=node /app/backend/dist/index.js
directory=/app/backend
autostart=true
autorestart=true
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
environment=NODE_ENV="production",PORT="4000"
priority=20