Security: WS-Rollenprüfung, JWT-Cookie statt localStorage, XSS/SSRF-Fixes, RDP-Consent-Secret
Some checks failed
IT Nexus Deploy / Build Frontend (push) Has been cancelled
IT Nexus Deploy / Deploy to Production (push) Has been cancelled

- WebSocket Shell/RDP: Rollenprüfung statt nur JWT-Gültigkeit (war: jeder eingeloggte User konnte fremde Agents per Shell/RDP übernehmen)
- JWT_SECRET: Server bricht ab statt mit unsicherem Default weiterzulaufen
- Auth: Token läuft jetzt über httpOnly-Cookie statt localStorage (XSS-Schutz gegen Session-Diebstahl)
- WS-Auth: Token nicht mehr als URL-Query-Param (landete in nginx-Logs), sondern als erste Message bzw. automatisch via Cookie
- Frontend: toter Rollen-Check (isSuperAdmin/isAdmin ohne Funktionsaufruf) in AgentDetailPage gefixt
- XSS: DOMPurify-Sanitizing für alle marked.parse()-Renderstellen (KI-Antworten, Kommentare, Knowledge Base)
- E-Mail: HTML-Escaping für alle ticket-gesteuerten Felder (auch über öffentliche Ticket-Route erreichbar)
- SSRF-Schutz beim Knowledge-Base-URL-Import (blockt private/Loopback-Adressen)
- TV-Dashboard: Shared-Key statt komplett offenem Endpoint
- Striktes Rate-Limit auf /login, must_change_password serverseitig erzwungen
- Agent (C#) v2.7.0: RDP-Consent/Disconnect/Capture verlangen jetzt ein Pro-Session-Secret (war: jeder lokale Prozess konnte Consent vortäuschen), DataDir-ACL für agent.log/status.json
- FIDO-PINs AES-256-GCM-verschlüsselt statt Klartext, Retention-Job für alte patch_commands/audit_log

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-06-26 13:27:17 +02:00
parent 3ea28def4c
commit 81b1c326fc
47 changed files with 706 additions and 235 deletions

1
.gitignore vendored
View File

@@ -35,6 +35,7 @@ agent/*.exe
agent/*.msi
agent-cs/bin/
agent-cs/obj/
agent-cs/publish/
# Uploads
backend/uploads/

View File

@@ -6,7 +6,7 @@ namespace ITNexusAgent;
public class AgentWorker
{
private const string Version = "2.6.0";
private const string Version = "2.7.0";
private const string DataDir = @"C:\ProgramData\IT Nexus Agent";
private const string ConfigPath = @"C:\ProgramData\IT Nexus Agent\config.json";
private const string StatusPath = @"C:\ProgramData\IT Nexus Agent\status.json";
@@ -24,6 +24,7 @@ public class AgentWorker
{
_exePath = System.Diagnostics.Process.GetCurrentProcess().MainModule!.FileName;
Directory.CreateDirectory(DataDir);
SecureDataDir(DataDir);
if (!File.Exists(ConfigPath))
{
@@ -176,6 +177,30 @@ public class AgentWorker
catch { }
}
// Verzeichnis-ACL: nur SYSTEM/Administratoren — verhindert dass normale lokale User
// agent.log/status.json lesen (Hostname, letzter User, RDP-/Patch-Aktivität) oder manipulieren.
private static void SecureDataDir(string dir)
{
try
{
var di = new System.IO.DirectoryInfo(dir);
var acl = di.GetAccessControl();
acl.SetAccessRuleProtection(true, false);
acl.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(
"SYSTEM", System.Security.AccessControl.FileSystemRights.FullControl,
System.Security.AccessControl.InheritanceFlags.ContainerInherit | System.Security.AccessControl.InheritanceFlags.ObjectInherit,
System.Security.AccessControl.PropagationFlags.None,
System.Security.AccessControl.AccessControlType.Allow));
acl.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(
"Administrators", System.Security.AccessControl.FileSystemRights.FullControl,
System.Security.AccessControl.InheritanceFlags.ContainerInherit | System.Security.AccessControl.InheritanceFlags.ObjectInherit,
System.Security.AccessControl.PropagationFlags.None,
System.Security.AccessControl.AccessControlType.Allow));
di.SetAccessControl(acl);
}
catch { }
}
private static void SecureConfigFile(string path)
{
try

View File

@@ -11,7 +11,7 @@ public static class CaptureModeRunner
private static readonly ImageCodecInfo JpegCodec =
ImageCodecInfo.GetImageEncoders().First(c => c.FormatID == ImageFormat.Jpeg.Guid);
public static void Run(string portStr, int screenIdx = 0)
public static void Run(string portStr, int screenIdx, string secret)
{
if (!int.TryParse(portStr, out var port) || port <= 0) return;
@@ -20,6 +20,7 @@ public static class CaptureModeRunner
using var tcp = new TcpClient();
tcp.Connect("127.0.0.1", port);
var stream = tcp.GetStream();
stream.Write(System.Text.Encoding.ASCII.GetBytes(secret));
var encParams = new EncoderParameters(1);
encParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 60L);

View File

@@ -5,14 +5,14 @@ namespace ITNexusAgent;
// Läuft als User-Prozess (via schtasks), zeigt Consent-Dialog und sendet Antwort via TCP
public static class ConsentModeRunner
{
public static void Run(string portStr)
public static void Run(string portStr, string secret)
{
if (!int.TryParse(portStr, out var port) || port <= 0) return;
var app = new System.Windows.Application();
app.ShutdownMode = System.Windows.ShutdownMode.OnMainWindowClose;
var win = new RdpConsentWindow(port);
var win = new RdpConsentWindow(port, secret);
win.Topmost = true;
win.Show();
win.Activate();

View File

@@ -7,8 +7,8 @@
<UseWindowsForms>true</UseWindowsForms>
<AssemblyName>IT-Nexus-Agent</AssemblyName>
<RootNamespace>ITNexusAgent</RootNamespace>
<Version>2.6.0</Version>
<AssemblyVersion>2.6.0.0</AssemblyVersion>
<Version>2.7.0</Version>
<AssemblyVersion>2.7.0.0</AssemblyVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AllowUnsafeBlocks>false</AllowUnsafeBlocks>

View File

@@ -6,14 +6,14 @@ namespace ITNexusAgent;
// solange RDP-Session aktiv ist. User kann selbst trennen (TCP-Signal an Service).
public static class IndicatorModeRunner
{
public static void Run(string portStr)
public static void Run(string portStr, string secret)
{
if (!int.TryParse(portStr, out var port) || port <= 0) return;
var app = new System.Windows.Application();
app.ShutdownMode = System.Windows.ShutdownMode.OnMainWindowClose;
var win = new RdpActiveIndicatorWindow(port);
var win = new RdpActiveIndicatorWindow(port, secret);
win.Show();
app.Run();
}

View File

@@ -20,17 +20,22 @@ internal class Program
return;
case "--rdp-consent":
ConsentModeRunner.Run(args.Length > 1 ? args[1] : "");
ConsentModeRunner.Run(
args.Length > 1 ? args[1] : "",
args.Length > 2 ? args[2] : "");
return;
case "--rdp-capture":
CaptureModeRunner.Run(
args.Length > 1 ? args[1] : "",
args.Length > 2 && int.TryParse(args[2], out var si) ? si : 0);
args.Length > 2 && int.TryParse(args[2], out var si) ? si : 0,
args.Length > 3 ? args[3] : "");
return;
case "--rdp-indicator":
IndicatorModeRunner.Run(args.Length > 1 ? args[1] : "");
IndicatorModeRunner.Run(
args.Length > 1 ? args[1] : "",
args.Length > 2 ? args[2] : "");
return;
case "--dashboard":

View File

@@ -2,6 +2,7 @@ using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
@@ -112,15 +113,36 @@ public class RtcService
}
}
private static string GenerateSecret() => Convert.ToHexString(RandomNumberGenerator.GetBytes(16));
// Liest exakt secret.Length Bytes und vergleicht zeitkonstant — verhindert, dass ein beliebiger
// lokaler Prozess sich als der gespawnte Helper ausgibt und Consent/Disconnect/Frames vortäuscht.
private static async Task<bool> ValidateSecretAsync(NetworkStream stream, string secret, CancellationToken ct)
{
var expected = Encoding.ASCII.GetBytes(secret);
var buf = new byte[expected.Length];
var read = 0;
while (read < buf.Length)
{
int n;
try { n = await stream.ReadAsync(buf.AsMemory(read, buf.Length - read), ct); }
catch { return false; }
if (n == 0) return false;
read += n;
}
return CryptographicOperations.FixedTimeEquals(buf, expected);
}
private async Task ConsentAndCaptureAsync(ClientWebSocket ws, int screenIdx, CancellationToken ct)
{
var exePath = System.Diagnostics.Process.GetCurrentProcess().MainModule!.FileName;
var secret = GenerateSecret();
var consentListener = new TcpListener(IPAddress.Loopback, 0);
consentListener.Start();
var consentPort = ((IPEndPoint)consentListener.LocalEndpoint).Port;
if (!SpawnConsentHelper(exePath, consentPort.ToString()))
if (!SpawnConsentHelper(exePath, consentPort.ToString(), secret))
{
consentListener.Stop();
AgentWorker.Log("RDP: Consent-Helper fehlgeschlagen, verweigere Zugriff");
@@ -140,9 +162,15 @@ public class RtcService
{
using var timeoutCts = new CancellationTokenSource(TimeSpan.FromSeconds(35));
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, timeoutCts.Token);
while (!linked.IsCancellationRequested)
{
using var tcp = await consentListener.AcceptTcpClientAsync(linked.Token);
var b = tcp.GetStream().ReadByte();
var stream = tcp.GetStream();
if (!await ValidateSecretAsync(stream, secret, linked.Token)) continue; // fremder Connect-Versuch ohne gültiges Secret — ignorieren, weiter warten
var b = stream.ReadByte();
accepted = b == 1;
break;
}
}
catch { accepted = false; }
finally { consentListener.Stop(); }
@@ -174,6 +202,7 @@ public class RtcService
_indicatorListener = new TcpListener(IPAddress.Loopback, 0);
_indicatorListener.Start();
var port = ((IPEndPoint)_indicatorListener.LocalEndpoint).Port;
var secret = GenerateSecret();
_userDisconnectCts = new CancellationTokenSource();
var listener = _indicatorListener;
@@ -181,16 +210,22 @@ public class RtcService
_ = Task.Run(async () =>
{
try
{
while (true)
{
using var tcp = await listener.AcceptTcpClientAsync();
tcp.GetStream().ReadByte();
var stream = tcp.GetStream();
if (!await ValidateSecretAsync(stream, secret, CancellationToken.None)) continue; // fremder Connect-Versuch ohne gültiges Secret
stream.ReadByte();
disconnectCts.Cancel();
AgentWorker.Log("RDP: User hat über Overlay getrennt");
break;
}
}
catch { }
});
_indicatorPid = SessionSpawner.SpawnInUserSession(exePath, $"--rdp-indicator {port}");
_indicatorPid = SessionSpawner.SpawnInUserSession(exePath, $"--rdp-indicator {port} {secret}");
}
catch (Exception ex)
{
@@ -198,22 +233,23 @@ public class RtcService
}
}
private static bool SpawnConsentHelper(string exePath, string portStr)
private static bool SpawnConsentHelper(string exePath, string portStr, string secret)
{
var pid = SessionSpawner.SpawnInUserSession(exePath, $"--rdp-consent {portStr}");
var pid = SessionSpawner.SpawnInUserSession(exePath, $"--rdp-consent {portStr} {secret}");
return pid > 0;
}
private async Task CapturePipeLoopAsync(ClientWebSocket ws, int screenIdx, CancellationToken ct)
{
var exePath = System.Diagnostics.Process.GetCurrentProcess().MainModule!.FileName;
var secret = GenerateSecret();
// TCP Loopback: kein ACL-Problem zwischen SYSTEM-Service und User-Prozess
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
if (!SpawnCaptureHelper(exePath, port.ToString(), screenIdx))
if (!SpawnCaptureHelper(exePath, port.ToString(), screenIdx, secret))
{
listener.Stop();
AgentWorker.Log("RDP: Helper-Start fehlgeschlagen");
@@ -225,7 +261,16 @@ public class RtcService
{
using var connectCts = new CancellationTokenSource(TimeSpan.FromSeconds(15));
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, connectCts.Token);
tcp = await listener.AcceptTcpClientAsync(linked.Token);
while (true)
{
var candidate = await listener.AcceptTcpClientAsync(linked.Token);
if (await ValidateSecretAsync(candidate.GetStream(), secret, linked.Token))
{
tcp = candidate;
break;
}
candidate.Dispose(); // fremder Connect-Versuch ohne gültiges Secret — verwerfen, weiter warten
}
}
catch
{
@@ -283,9 +328,9 @@ public class RtcService
AgentWorker.Log("RDP: Frame-Loop beendet");
}
private static bool SpawnCaptureHelper(string exePath, string portStr, int screenIdx = 0)
private static bool SpawnCaptureHelper(string exePath, string portStr, int screenIdx, string secret)
{
var pid = SessionSpawner.SpawnInUserSession(exePath, $"--rdp-capture {portStr} {screenIdx}");
var pid = SessionSpawner.SpawnInUserSession(exePath, $"--rdp-capture {portStr} {screenIdx} {secret}");
return pid > 0;
}
}

View File

@@ -1,4 +1,5 @@
using System.Net.Sockets;
using System.Text;
using System.Windows;
using System.Windows.Media.Animation;
@@ -7,14 +8,16 @@ namespace ITNexusAgent.UI;
public partial class RdpActiveIndicatorWindow : Window
{
private readonly int _port;
private readonly string _secret;
private readonly DateTime _startedAt = DateTime.Now;
private readonly System.Windows.Threading.DispatcherTimer _timer = new();
private bool _signaled = false;
public RdpActiveIndicatorWindow(int port)
public RdpActiveIndicatorWindow(int port, string secret)
{
InitializeComponent();
_port = port;
_secret = secret;
Loaded += (s, e) =>
{
@@ -47,8 +50,10 @@ public partial class RdpActiveIndicatorWindow : Window
{
using var tcp = new TcpClient();
tcp.Connect("127.0.0.1", _port);
tcp.GetStream().WriteByte(1);
tcp.GetStream().Flush();
var stream = tcp.GetStream();
stream.Write(Encoding.ASCII.GetBytes(_secret));
stream.WriteByte(1);
stream.Flush();
}
catch { }
}

View File

@@ -1,4 +1,5 @@
using System.Net.Sockets;
using System.Text;
using System.Windows;
namespace ITNexusAgent.UI;
@@ -6,13 +7,15 @@ namespace ITNexusAgent.UI;
public partial class RdpConsentWindow : Window
{
private readonly int _port;
private readonly string _secret;
private bool _answered = false;
private System.Threading.CancellationTokenSource _countdownCts = new();
public RdpConsentWindow(int port)
public RdpConsentWindow(int port, string secret)
{
InitializeComponent();
_port = port;
_secret = secret;
_ = RunCountdownAsync(_countdownCts.Token);
}
@@ -53,8 +56,10 @@ public partial class RdpConsentWindow : Window
{
using var tcp = new TcpClient();
tcp.Connect("127.0.0.1", _port);
tcp.GetStream().WriteByte((byte)(accepted ? 1 : 0));
tcp.GetStream().Flush();
var stream = tcp.GetStream();
stream.Write(Encoding.ASCII.GetBytes(_secret));
stream.WriteByte((byte)(accepted ? 1 : 0));
stream.Flush();
}
catch { }
}

View File

@@ -1,5 +1,5 @@
#define MyAppName "IT Nexus Agent"
#define MyAppVersion "2.6.0"
#define MyAppVersion "2.7.0"
#define MyAppPublisher "Cereda Systems GmbH"
#define MyAppURL "https://it-nexus.cereda-systems.de"
#define MyAppExeName "IT-Nexus-Agent.exe"

View File

@@ -14,6 +14,7 @@
"better-sqlite3": "^12.6.2",
"botbuilder": "^4.23.3",
"bwip-js": "^4.8.0",
"cookie-parser": "^1.4.7",
"cors": "^2.8.5",
"dotenv": "^16.3.1",
"express": "^4.18.2",
@@ -1371,6 +1372,25 @@
"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-signature": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
"integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==",
"license": "MIT"
},
"node_modules/cookie-signature": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz",

View File

@@ -21,6 +21,7 @@
"better-sqlite3": "^12.6.2",
"botbuilder": "^4.23.3",
"bwip-js": "^4.8.0",
"cookie-parser": "^1.4.7",
"cors": "^2.8.5",
"dotenv": "^16.3.1",
"express": "^4.18.2",

View File

@@ -1,14 +1,14 @@
require('dotenv').config();
if (!process.env.JWT_SECRET) {
console.error('❌ FATAL: JWT_SECRET ist nicht gesetzt. Server wird nicht mit einem unsicheren Default-Secret gestartet.');
process.exit(1);
}
const JWT_CONFIG = {
secret: process.env.JWT_SECRET || 'default-secret-change-in-production',
secret: process.env.JWT_SECRET,
expiresIn: process.env.JWT_EXPIRATION || '8h',
algorithm: 'HS256'
};
// Validate that JWT_SECRET is set
if (!process.env.JWT_SECRET) {
console.warn('⚠️ WARNING: JWT_SECRET not set in .env file. Using default secret (INSECURE!)');
}
module.exports = JWT_CONFIG;

View File

@@ -160,8 +160,12 @@ class AiController {
const { url } = req.body;
if (!url?.trim()) throw new AppError('URL ist erforderlich', 400);
// Only allow http/https
if (!/^https?:\/\//i.test(url)) throw new AppError('Nur HTTP/HTTPS URLs erlaubt', 400);
const { assertPublicUrl } = require('../utils/ssrfGuard');
try {
await assertPublicUrl(url);
} catch (e) {
throw new AppError(e.message, 400);
}
let html;
try {
@@ -204,7 +208,12 @@ class AiController {
const AiService = require('../services/ai.service');
const { url, maxPages = 20 } = req.body;
if (!url?.trim()) throw new AppError('URL ist erforderlich', 400);
if (!/^https?:\/\//i.test(url)) throw new AppError('Nur HTTP/HTTPS URLs erlaubt', 400);
const { assertPublicUrl } = require('../utils/ssrfGuard');
try {
await assertPublicUrl(url);
} catch (e) {
throw new AppError(e.message, 400);
}
const limit = Math.min(Math.max(1, parseInt(maxPages) || 20), 100);
const baseUrl = new URL(url);
@@ -236,6 +245,7 @@ class AiController {
visited.add(currentUrl);
try {
try { await assertPublicUrl(currentUrl); } catch { continue; } // DNS-Rebinding-Schutz
const response = await fetch(currentUrl, {
headers: { 'User-Agent': 'Mozilla/5.0 IT-Nexus KnowledgeBase Importer' },
signal: AbortSignal.timeout(10000),

View File

@@ -1,6 +1,7 @@
const AuthService = require('../services/auth.service');
const User = require('../models/User');
const { asyncHandler } = require('../middleware/errorHandler');
const { setAuthCookie, clearAuthCookie } = require('../utils/authCookie');
class AuthController {
/**
@@ -18,10 +19,11 @@ class AuthController {
}
const result = await AuthService.login(username, password);
setAuthCookie(res, result.token);
res.json({
status: 'success',
data: result
data: { user: result.user }
});
});
@@ -104,8 +106,7 @@ class AuthController {
* POST /api/auth/logout
*/
static logout = asyncHandler(async (req, res) => {
// Client-side will handle token removal
// This endpoint is just for consistency and potential future server-side session handling
clearAuthCookie(res);
res.json({
status: 'success',
message: 'Logged out successfully'

View File

@@ -481,6 +481,7 @@ async function initializeDatabase() {
`ALTER TABLE fido_keys ADD COLUMN last_used_at DATETIME`,
`ALTER TABLE fido_keys ADD COLUMN manufacturer TEXT`,
`ALTER TABLE fido_keys ADD COLUMN connection_type TEXT`,
`ALTER TABLE fido_keys ADD COLUMN pin TEXT`,
// Asset-Agent-Sync
`ALTER TABLE assets ADD COLUMN os TEXT`,
`ALTER TABLE assets ADD COLUMN ip_address TEXT`,
@@ -552,6 +553,23 @@ async function initializeDatabase() {
}
console.log('✅ Database migrations completed');
// Special migration: bestehende Klartext-PINs in fido_keys nachverschlüsseln (DSGVO Art. 32)
try {
const { encrypt } = require('../utils/crypto');
const plainPinRows = db.prepare(
`SELECT id, pin FROM fido_keys WHERE pin IS NOT NULL AND pin != '' AND instr(pin, ':') = 0`
).all();
if (plainPinRows.length > 0) {
const updatePin = db.prepare('UPDATE fido_keys SET pin = ? WHERE id = ?');
for (const row of plainPinRows) {
updatePin.run(encrypt(row.pin), row.id);
}
console.log(`🔐 ${plainPinRows.length} Klartext-PIN(s) in fido_keys nachverschlüsselt`);
}
} catch (e) {
console.error('⚠️ PIN-Verschlüsselungs-Migration fehlgeschlagen:', e.message);
}
// Special migration: rebuild network_devices to add SNMP + AP support
try {
const ndDef = db.prepare("SELECT sql FROM sqlite_master WHERE type='table' AND name='network_devices'").get();

View File

@@ -1,6 +1,9 @@
const jwt = require('jsonwebtoken');
const JWT_CONFIG = require('../config/jwt');
// Endpunkte, die trotz erzwungenem Passwortwechsel erreichbar bleiben müssen
const PASSWORD_CHANGE_EXEMPT_PATHS = ['/api/auth/me', '/api/auth/change-password'];
/**
* Middleware to verify JWT token and attach user to request
*/
@@ -18,6 +21,19 @@ function authenticateToken(req, res, next) {
try {
const decoded = jwt.verify(token, JWT_CONFIG.secret);
req.user = decoded; // { id, username, email, role, roleId }
if (!PASSWORD_CHANGE_EXEMPT_PATHS.includes(req.originalUrl.split('?')[0])) {
const User = require('../models/User');
const dbUser = User.getById(decoded.id);
if (dbUser?.must_change_password) {
return res.status(403).json({
status: 'error',
code: 'PASSWORD_CHANGE_REQUIRED',
message: 'Passwortänderung erforderlich, bevor weitere Aktionen möglich sind'
});
}
}
next();
} catch (error) {
if (error.name === 'TokenExpiredError') {

View File

@@ -105,6 +105,16 @@ class AuditLog {
return stmt.all(limit);
}
/**
* Löscht Audit-Log-Einträge älter als retentionDays (DSGVO Art. 5 Abs. 1 lit. e - Speicherbegrenzung)
*/
static cleanupOld(retentionDays = 180) {
const db = getDatabase();
const stmt = db.prepare(`DELETE FROM audit_log WHERE created_at < datetime('now', '-' || ? || ' days')`);
const result = stmt.run(retentionDays);
return result.changes;
}
/**
* Helper method to log user actions
*/

View File

@@ -1,4 +1,10 @@
const { getDatabase } = require('../config/database');
const { encrypt, decrypt } = require('../utils/crypto');
function withDecryptedPin(row) {
if (!row) return row;
return { ...row, pin: decrypt(row.pin) };
}
class FidoKey {
/**
@@ -19,7 +25,7 @@ class FidoKey {
LEFT JOIN users uu ON fk.updated_by_user_id = uu.id
ORDER BY fk.created_at DESC
`);
return stmt.all();
return stmt.all().map(withDecryptedPin);
}
/**
@@ -40,7 +46,7 @@ class FidoKey {
LEFT JOIN users uu ON fk.updated_by_user_id = uu.id
WHERE fk.id = ?
`);
return stmt.get(id);
return withDecryptedPin(stmt.get(id));
}
/**
@@ -58,7 +64,7 @@ class FidoKey {
LEFT JOIN users cu ON fk.created_by_user_id = cu.id
WHERE fk.serial_number = ?
`);
return stmt.get(serialNumber);
return withDecryptedPin(stmt.get(serialNumber));
}
/**
@@ -77,7 +83,7 @@ class FidoKey {
WHERE fk.status = ?
ORDER BY fk.created_at DESC
`);
return stmt.all(status);
return stmt.all(status).map(withDecryptedPin);
}
/**
@@ -94,7 +100,7 @@ class FidoKey {
WHERE fk.assigned_to_user_id = ?
ORDER BY fk.created_at DESC
`);
return stmt.all(userId);
return stmt.all(userId).map(withDecryptedPin);
}
/**
@@ -108,9 +114,10 @@ class FidoKey {
serial_number,
status,
description,
pin,
assigned_to_user_id,
created_by_user_id
) VALUES (?, ?, ?, ?, ?, ?)
) VALUES (?, ?, ?, ?, ?, ?, ?)
`);
const result = stmt.run(
@@ -118,6 +125,7 @@ class FidoKey {
keyData.serial_number,
keyData.status,
keyData.description || null,
encrypt(keyData.pin) || null,
keyData.assigned_to_user_id || null,
keyData.created_by_user_id
);
@@ -150,6 +158,10 @@ class FidoKey {
fields.push('description = ?');
values.push(keyData.description);
}
if (keyData.pin !== undefined) {
fields.push('pin = ?');
values.push(encrypt(keyData.pin));
}
if (keyData.assigned_to_user_id !== undefined) {
fields.push('assigned_to_user_id = ?');
values.push(keyData.assigned_to_user_id);

View File

@@ -3,6 +3,7 @@ const router = express.Router();
const crypto = require('crypto');
const jwt = require('jsonwebtoken');
const User = require('../models/User');
const { setAuthCookie } = require('../utils/authCookie');
const TENANT_ID = () => process.env.AZURE_TENANT_ID;
const CLIENT_ID = () => process.env.AZURE_CLIENT_ID;

View File

@@ -2,7 +2,15 @@ const express = require('express');
const router = express.Router();
const { getStats, getCVEs } = require('../controllers/tv.controller');
router.get('/stats', getStats);
router.get('/cves', getCVEs);
// Kein normaler Login (TV-Display im Büro) — aber ein Shared-Key statt komplett offen ins Netz.
function requireTvKey(req, res, next) {
if (!process.env.TV_DASHBOARD_KEY || req.query.key !== process.env.TV_DASHBOARD_KEY) {
return res.status(401).json({ status: 'error', message: 'Unauthorized' });
}
next();
}
router.get('/stats', requireTvKey, getStats);
router.get('/cves', requireTvKey, getCVEs);
module.exports = router;

View File

@@ -75,6 +75,16 @@ const authLimiter = rateLimit({
legacyHeaders: false
});
// Striktes Limit nur für /login — verhindert Brute-Force auf Passwörter
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 8,
message: { status: 'error', message: 'Zu viele Login-Versuche, bitte später erneut versuchen' },
standardHeaders: true,
legacyHeaders: false,
skipSuccessfulRequests: true
});
// ============================================================================
// ROUTES
// ============================================================================
@@ -127,6 +137,7 @@ app.get('/api/health/history', (req, res) => {
});
// API routes
app.use('/api/auth/login', loginLimiter);
app.use('/api/auth', authLimiter, authRoutes);
app.use('/api/users', userRoutes);
app.use('/api/fido-keys', fidoKeyRoutes);
@@ -411,6 +422,12 @@ async function startServer() {
NetworkDevice.cleanupOldChecks();
});
// DSGVO-Speicherbegrenzung: alte patch_commands (inkl. Shell-Output) + audit_log (täglich 03:30)
cron.schedule('30 3 * * *', () => {
const { runRetentionCleanup } = require('./services/dataRetention.service');
runRetentionCleanup();
});
// Proxmox Monitoring (alle 5 Minuten)
if (process.env.PROXMOX_HOST && process.env.PROXMOX_TOKEN) {
const { pollProxmox } = require('./services/proxmoxService');

View File

@@ -0,0 +1,26 @@
const { getDatabase } = require('../config/database');
const AuditLog = require('../models/AuditLog');
// DSGVO Art. 5 Abs. 1 lit. e (Speicherbegrenzung) — Daten nur so lange aufbewahren wie nötig.
const PATCH_COMMANDS_RETENTION_DAYS = parseInt(process.env.PATCH_COMMANDS_RETENTION_DAYS || '90', 10);
const AUDIT_LOG_RETENTION_DAYS = parseInt(process.env.AUDIT_LOG_RETENTION_DAYS || '180', 10);
function cleanupPatchCommands() {
const db = getDatabase();
const stmt = db.prepare(
`DELETE FROM patch_commands WHERE created_at < datetime('now', '-' || ? || ' days') AND status IN ('done', 'failed')`
);
return stmt.run(PATCH_COMMANDS_RETENTION_DAYS).changes;
}
function runRetentionCleanup() {
try {
const patchDeleted = cleanupPatchCommands();
const auditDeleted = AuditLog.cleanupOld(AUDIT_LOG_RETENTION_DAYS);
console.log(`[DataRetention] Bereinigt: ${patchDeleted} patch_commands (>${PATCH_COMMANDS_RETENTION_DAYS}d), ${auditDeleted} audit_log Einträge (>${AUDIT_LOG_RETENTION_DAYS}d)`);
} catch (err) {
console.error('[DataRetention] Fehler:', err.message);
}
}
module.exports = { runRetentionCleanup, cleanupPatchCommands };

View File

@@ -431,9 +431,9 @@ async function sendTicketCreatedConfirmation(ticket) {
</p>
${infoCard([
['Ticket-Nr.', `<strong style="font-family:'Courier New',Courier,monospace;color:#0d9488;font-size:13px;">${ticket.ticket_number}</strong>`],
['Betreff', `<strong style="color:#111827;">${ticket.title}</strong>`],
['Kategorie', `<span style="color:#374151;">${ticket.category}</span>`],
['Ticket-Nr.', `<strong style="font-family:'Courier New',Courier,monospace;color:#0d9488;font-size:13px;">${escHtml(ticket.ticket_number)}</strong>`],
['Betreff', `<strong style="color:#111827;">${escHtml(ticket.title)}</strong>`],
['Kategorie', `<span style="color:#374151;">${escHtml(ticket.category)}</span>`],
['Priorität', priorityBadge(ticket.priority)],
['Status', statusBadge(ticket.status)],
])}
@@ -494,11 +494,11 @@ async function sendTicketAssignedNotification(ticket, assignedUser) {
</p>
${infoCard([
['Ticket-Nr.', `<strong style="font-family:'Courier New',Courier,monospace;color:#0d9488;font-size:13px;">${ticket.ticket_number}</strong>`],
['Betreff', `<strong style="color:#111827;">${ticket.title}</strong>`],
['Kategorie', `<span style="color:#374151;">${ticket.category}</span>`],
['Ticket-Nr.', `<strong style="font-family:'Courier New',Courier,monospace;color:#0d9488;font-size:13px;">${escHtml(ticket.ticket_number)}</strong>`],
['Betreff', `<strong style="color:#111827;">${escHtml(ticket.title)}</strong>`],
['Kategorie', `<span style="color:#374151;">${escHtml(ticket.category)}</span>`],
['Priorität', priorityBadge(ticket.priority)],
['Von', `<span style="color:#374151;">${ticket.requester_name || 'Unbekannt'}${ticket.requester_email ? ` &lt;${ticket.requester_email}&gt;` : ''}</span>`],
['Von', `<span style="color:#374151;">${escHtml(ticket.requester_name || 'Unbekannt')}${ticket.requester_email ? ` &lt;${escHtml(ticket.requester_email)}&gt;` : ''}</span>`],
])}`;
await sendMail(
@@ -554,10 +554,10 @@ async function sendCommentNotification(ticket, comment) {
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td bgcolor="#0d9488" style="background-color:#0d9488;border-radius:6px;width:28px;height:28px;text-align:center;vertical-align:middle;padding:0 8px;">
<span style="font-size:13px;font-weight:800;color:#ffffff;font-family:Inter,Helvetica,Arial,sans-serif;line-height:28px;">${authorName.charAt(0).toUpperCase()}</span>
<span style="font-size:13px;font-weight:800;color:#ffffff;font-family:Inter,Helvetica,Arial,sans-serif;line-height:28px;">${escHtml(authorName.charAt(0).toUpperCase())}</span>
</td>
<td style="padding-left:10px;vertical-align:middle;">
<span style="font-size:13px;font-weight:700;color:#111827;font-family:Inter,Helvetica,Arial,sans-serif;">${authorName}</span>
<span style="font-size:13px;font-weight:700;color:#111827;font-family:Inter,Helvetica,Arial,sans-serif;">${escHtml(authorName)}</span>
<span style="font-size:11px;color:#9ca3af;font-family:Inter,Helvetica,Arial,sans-serif;padding-left:6px;">· IT Support</span>
</td>
</tr>
@@ -567,14 +567,14 @@ async function sendCommentNotification(ticket, comment) {
<!-- Message body -->
<tr>
<td bgcolor="#ffffff" style="background-color:#ffffff;padding:16px;font-size:14px;color:#1f2937;line-height:1.75;white-space:pre-line;font-family:Inter,Helvetica,Arial,sans-serif;">
${comment.comment.replace(/</g, '&lt;').replace(/>/g, '&gt;')}
${escHtml(comment.comment)}
</td>
</tr>
</table>
${infoCard([
['Ticket-Nr.', `<strong style="font-family:'Courier New',Courier,monospace;color:#0d9488;font-size:13px;">${ticket.ticket_number}</strong>`],
['Betreff', `<span style="color:#374151;">${ticket.title}</span>`],
['Ticket-Nr.', `<strong style="font-family:'Courier New',Courier,monospace;color:#0d9488;font-size:13px;">${escHtml(ticket.ticket_number)}</strong>`],
['Betreff', `<span style="color:#374151;">${escHtml(ticket.title)}</span>`],
['Status', statusBadge(ticket.status)],
])}`;
@@ -611,19 +611,19 @@ async function sendStaffCommentNotification(ticket, comment) {
const content = `
<h2 style="margin:0 0 8px;font-size:21px;font-weight:800;color:#111827;font-family:Inter,Helvetica,Arial,sans-serif;">Neue Antwort im Ticket</h2>
<p style="margin:0 0 20px;font-size:14px;color:#6b7280;line-height:1.7;font-family:Inter,Helvetica,Arial,sans-serif;">
<strong>${requesterName}</strong> hat auf Ticket <strong style="color:#0d9488;">${ticket.ticket_number}</strong> geantwortet.
<strong>${escHtml(requesterName)}</strong> hat auf Ticket <strong style="color:#0d9488;">${escHtml(ticket.ticket_number)}</strong> geantwortet.
</p>
<table width="100%" cellpadding="0" cellspacing="0" border="0" style="width:100%;border:1px solid #e5e7eb;border-radius:10px;overflow:hidden;margin-bottom:22px;">
<tr><td bgcolor="#f8fafc" style="background-color:#f8fafc;padding:10px 16px;border-bottom:1px solid #e5e7eb;">
<span style="font-size:13px;font-weight:700;color:#111827;font-family:Inter,Helvetica,Arial,sans-serif;">${requesterName}</span>
<span style="font-size:13px;font-weight:700;color:#111827;font-family:Inter,Helvetica,Arial,sans-serif;">${escHtml(requesterName)}</span>
</td></tr>
<tr><td bgcolor="#ffffff" style="background-color:#ffffff;padding:16px;font-size:14px;color:#1f2937;line-height:1.75;white-space:pre-line;font-family:Inter,Helvetica,Arial,sans-serif;">
${comment.comment.replace(/</g, '&lt;').replace(/>/g, '&gt;')}
${escHtml(comment.comment)}
</td></tr>
</table>
${infoCard([
['Ticket-Nr.', `<strong style="font-family:'Courier New',Courier,monospace;color:#0d9488;font-size:13px;">${ticket.ticket_number}</strong>`],
['Betreff', `<span style="color:#374151;">${ticket.title}</span>`],
['Ticket-Nr.', `<strong style="font-family:'Courier New',Courier,monospace;color:#0d9488;font-size:13px;">${escHtml(ticket.ticket_number)}</strong>`],
['Betreff', `<span style="color:#374151;">${escHtml(ticket.title)}</span>`],
['Status', statusBadge(ticket.status)],
])}`;
@@ -660,10 +660,10 @@ async function sendStaffTicketCreatedNotification(ticket) {
const content = `
<h2 style="margin:0 0 8px;font-size:21px;font-weight:800;color:#111827;font-family:Inter,Helvetica,Arial,sans-serif;">Neues Ticket eingegangen</h2>
${infoCard([
['Ticket-Nr.', `<strong style="font-family:'Courier New',Courier,monospace;color:#0d9488;font-size:13px;">${ticket.ticket_number}</strong>`],
['Betreff', `<strong style="color:#111827;">${ticket.title}</strong>`],
['Von', `<span style="color:#374151;">${ticket.requester_name || ''}${ticket.requester_email ? ` &lt;${ticket.requester_email}&gt;` : ''}</span>`],
['Kategorie', `<span style="color:#374151;">${ticket.category || '—'}</span>`],
['Ticket-Nr.', `<strong style="font-family:'Courier New',Courier,monospace;color:#0d9488;font-size:13px;">${escHtml(ticket.ticket_number)}</strong>`],
['Betreff', `<strong style="color:#111827;">${escHtml(ticket.title)}</strong>`],
['Von', `<span style="color:#374151;">${escHtml(ticket.requester_name || '')}${ticket.requester_email ? ` &lt;${escHtml(ticket.requester_email)}&gt;` : ''}</span>`],
['Kategorie', `<span style="color:#374151;">${escHtml(ticket.category || '—')}</span>`],
['Priorität', priorityBadge(ticket.priority)],
])}`;
@@ -735,8 +735,8 @@ async function sendStatusChangeNotification(ticket, oldStatus, newStatus) {
${statusChangeVisual}
${infoCard([
['Ticket-Nr.', `<strong style="font-family:'Courier New',Courier,monospace;color:#0d9488;font-size:13px;">${ticket.ticket_number}</strong>`],
['Betreff', `<span style="color:#374151;">${ticket.title}</span>`],
['Ticket-Nr.', `<strong style="font-family:'Courier New',Courier,monospace;color:#0d9488;font-size:13px;">${escHtml(ticket.ticket_number)}</strong>`],
['Betreff', `<span style="color:#374151;">${escHtml(ticket.title)}</span>`],
['Priorität', priorityBadge(ticket.priority)],
])}
@@ -1032,10 +1032,10 @@ async function sendEscalationEmail(ticket) {
${introHtml}
</p>
<table width="100%" cellpadding="12" style="background:#fff8f8;border:1px solid #fca5a5;border-radius:8px;margin:0 0 16px;">
<tr><td><strong>Ticket:</strong> ${ticket.ticket_number}</td></tr>
<tr><td><strong>Titel:</strong> ${ticket.title}</td></tr>
<tr><td><strong>Ticket:</strong> ${escHtml(ticket.ticket_number)}</td></tr>
<tr><td><strong>Titel:</strong> ${escHtml(ticket.title)}</td></tr>
<tr><td><strong>Priorität:</strong> ${priorityBadge(ticket.priority)}</td></tr>
<tr><td><strong>Ersteller:</strong> ${ticket.requester_name || ticket.requester_email || 'Unbekannt'}</td></tr>
<tr><td><strong>Ersteller:</strong> ${escHtml(ticket.requester_name || ticket.requester_email || 'Unbekannt')}</td></tr>
<tr><td><strong>Erstellt:</strong> ${new Date(ticket.created_at + 'Z').toLocaleString('de-DE')}</td></tr>
</table>`;

View File

@@ -0,0 +1,20 @@
const COOKIE_NAME = 'token';
const isProd = process.env.NODE_ENV === 'production';
// httpOnly-Cookie statt Token in JS-lesbarem localStorage — verhindert dass ein XSS-Treffer
// das Session-Token einfach per document.cookie/localStorage ausliest.
function setAuthCookie(res, token, maxAgeMs = 8 * 60 * 60 * 1000) {
res.cookie(COOKIE_NAME, token, {
httpOnly: true,
secure: isProd,
sameSite: 'lax',
maxAge: maxAgeMs,
path: '/',
});
}
function clearAuthCookie(res) {
res.clearCookie(COOKIE_NAME, { httpOnly: true, secure: isProd, sameSite: 'lax', path: '/' });
}
module.exports = { setAuthCookie, clearAuthCookie, COOKIE_NAME };

View File

@@ -0,0 +1,34 @@
const crypto = require('crypto');
const ALGORITHM = 'aes-256-gcm';
function getKey() {
const secret = process.env.ENCRYPTION_KEY || process.env.JWT_SECRET || 'itnexus-fallback-key';
return crypto.createHash('sha256').update(secret).digest();
}
function encrypt(plainText) {
if (plainText === null || plainText === undefined || plainText === '') return null;
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv(ALGORITHM, getKey(), iv);
const encrypted = Buffer.concat([cipher.update(String(plainText), 'utf8'), cipher.final()]);
const authTag = cipher.getAuthTag();
return `${iv.toString('base64')}:${authTag.toString('base64')}:${encrypted.toString('base64')}`;
}
function decrypt(cipherText) {
if (!cipherText) return null;
const parts = cipherText.split(':');
if (parts.length !== 3) return cipherText; // unverschlüsselter Altbestand
try {
const [ivB64, authTagB64, dataB64] = parts;
const decipher = crypto.createDecipheriv(ALGORITHM, getKey(), Buffer.from(ivB64, 'base64'));
decipher.setAuthTag(Buffer.from(authTagB64, 'base64'));
const decrypted = Buffer.concat([decipher.update(Buffer.from(dataB64, 'base64')), decipher.final()]);
return decrypted.toString('utf8');
} catch {
return null;
}
}
module.exports = { encrypt, decrypt };

View File

@@ -0,0 +1,47 @@
const dns = require('dns').promises;
function isPrivateIp(ip) {
if (ip.includes(':')) {
// IPv6: loopback, link-local, unique-local
return ip === '::1' || /^fe80:/i.test(ip) || /^fc[0-9a-f]{2}:/i.test(ip) || /^fd[0-9a-f]{2}:/i.test(ip);
}
const parts = ip.split('.').map(Number);
if (parts.length !== 4 || parts.some(p => Number.isNaN(p))) return true; // unparsable → sicherheitshalber blocken
const [a, b] = parts;
if (a === 127) return true; // Loopback
if (a === 10) return true; // Private
if (a === 172 && b >= 16 && b <= 31) return true; // Private
if (a === 192 && b === 168) return true; // Private
if (a === 169 && b === 254) return true; // Link-local
if (a === 0) return true; // "this network"
return false;
}
// Wirft, falls die URL auf interne/private Adressen oder Loopback zeigt — verhindert SSRF
// über den Knowledge-Base-URL-Import (Server würde sonst beliebige interne Endpunkte abrufen).
async function assertPublicUrl(urlString) {
const parsed = new URL(urlString);
if (!['http:', 'https:'].includes(parsed.protocol)) {
throw new Error('Nur HTTP/HTTPS URLs erlaubt');
}
const hostname = parsed.hostname;
if (hostname === 'localhost' || hostname.endsWith('.local')) {
throw new Error('Interne/lokale Adressen sind nicht erlaubt');
}
let addresses;
try {
addresses = await dns.lookup(hostname, { all: true });
} catch {
throw new Error('Hostname konnte nicht aufgelöst werden');
}
for (const { address } of addresses) {
if (isPrivateIp(address)) {
throw new Error('Interne/private Adressen sind nicht erlaubt');
}
}
return parsed;
}
module.exports = { assertPublicUrl, isPrivateIp };

View File

@@ -90,20 +90,28 @@ function handleAgent(ws, url) {
});
}
// Token kommt NICHT mehr als URL-Query-Param (landet sonst im Klartext in nginx-Access-Logs),
// sondern als erste WS-Message ({type:'auth',token}) — erst danach wird die Verbindung freigeschaltet.
function handleBrowser(ws, url) {
const token = url.searchParams.get('token');
try {
jwt.verify(token, process.env.JWT_SECRET);
} catch {
ws.close(1008, 'unauthorized');
return;
}
const agentId = parseInt(url.searchParams.get('agentId'));
if (!agentId) { ws.close(1008, 'agentId required'); return; }
browserSockets.set(agentId, ws);
let authenticated = false;
const authTimer = setTimeout(() => { if (!authenticated) ws.close(1008, 'auth timeout'); }, 5000);
ws.on('message', (data) => {
if (!authenticated) {
clearTimeout(authTimer);
let decoded;
try {
const msg = JSON.parse(data.toString());
if (msg.type !== 'auth') throw new Error();
decoded = jwt.verify(msg.token, process.env.JWT_SECRET);
} catch { ws.close(1008, 'unauthorized'); return; }
if (!['admin', 'super_admin'].includes(decoded.role)) { ws.close(1008, 'forbidden'); return; }
authenticated = true;
browserSockets.set(agentId, ws);
const aws = agentSockets.get(agentId);
if (aws?.readyState === WebSocket.OPEN) {
aws.send(JSON.stringify({ type: 'start_shell' }));
@@ -111,8 +119,9 @@ function handleBrowser(ws, url) {
} else {
ws.send('\x1b[33m[Warte auf Agent-Verbindung...]\x1b[0m\r\n');
}
return;
}
ws.on('message', (data) => {
const aws = agentSockets.get(agentId);
if (!aws || aws.readyState !== WebSocket.OPEN) return;
// RTC-Signaling (offer/answer/ice) → transparent weiterleiten
@@ -164,18 +173,30 @@ function handleRdpAgent(ws, url) {
}
function handleRdpBrowser(ws, url) {
const token = url.searchParams.get('token');
try { jwt.verify(token, process.env.JWT_SECRET); }
catch { ws.close(1008, 'unauthorized'); return; }
const agentId = parseInt(url.searchParams.get('agentId'));
if (!agentId) { ws.close(1008, 'agentId required'); return; }
let authenticated = false;
const authTimer = setTimeout(() => { if (!authenticated) ws.close(1008, 'auth timeout'); }, 5000);
ws.on('message', (data) => {
if (!authenticated) {
clearTimeout(authTimer);
let decoded;
try {
const msg = JSON.parse(data.toString());
if (msg.type !== 'auth') throw new Error();
decoded = jwt.verify(msg.token, process.env.JWT_SECRET);
} catch { ws.close(1008, 'unauthorized'); return; }
if (!['admin', 'super_admin'].includes(decoded.role)) { ws.close(1008, 'forbidden'); return; }
authenticated = true;
const oldBws = rdpBrowserSockets.get(agentId);
if (oldBws?.readyState === WebSocket.OPEN) oldBws.close();
rdpBrowserSockets.set(agentId, ws);
return;
}
ws.on('message', (data) => {
const aws = rdpAgentSockets.get(agentId);
if (aws?.readyState === WebSocket.OPEN) aws.send(data.toString());
});

View File

@@ -9,6 +9,7 @@
"version": "1.0.0",
"dependencies": {
"axios": "^1.6.5",
"dompurify": "^3.4.11",
"html5-qrcode": "^2.3.8",
"marked": "^17.0.4",
"react": "^18.2.0",
@@ -3958,7 +3959,7 @@
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
"integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
"dev": true,
"devOptional": true,
"license": "MIT"
},
"node_modules/@types/ws": {
@@ -7074,6 +7075,15 @@
"url": "https://github.com/fb55/domhandler?sponsor=1"
}
},
"node_modules/dompurify": {
"version": "3.4.11",
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.11.tgz",
"integrity": "sha512-zhlUV12GsaRzMsf9q5M254YhA4+VuF0fG+QFqu6aYpoGlKtz+w8//jBcGVYBgQkR5GHjUomejY84AV+/uPbWdw==",
"license": "(MPL-2.0 OR Apache-2.0)",
"optionalDependencies": {
"@types/trusted-types": "^2.0.7"
}
},
"node_modules/domutils": {
"version": "2.8.0",
"resolved": "https://registry.npmjs.org/domutils/-/domutils-2.8.0.tgz",

View File

@@ -5,6 +5,7 @@
"private": true,
"dependencies": {
"axios": "^1.6.5",
"dompurify": "^3.4.11",
"html5-qrcode": "^2.3.8",
"marked": "^17.0.4",
"react": "^18.2.0",

View File

@@ -1234,21 +1234,16 @@ button, input, textarea, select { font: inherit; color: inherit; }
let shares = [];
let demoMode = false;
/* ---------- Auth token ---------- */
const TOKEN_KEY = "token";
const getToken = () => localStorage.getItem(TOKEN_KEY);
const setToken = (t) => localStorage.setItem(TOKEN_KEY, t);
const clearToken = () => localStorage.removeItem(TOKEN_KEY);
/* ---------- Auth (httpOnly-Cookie, kein Token in localStorage/URL) ---------- */
let demoModeFlag = false;
/* ---------- Fetch helper ---------- */
async function api(path, opts = {}) {
const headers = new Headers(opts.headers || {});
const tk = getToken();
if (tk) headers.set("Authorization", "Bearer " + tk);
if (opts.body && !(opts.body instanceof FormData) && !headers.has("Content-Type")) {
headers.set("Content-Type", "application/json");
}
const res = await fetch(path, { ...opts, headers });
const res = await fetch(path, { ...opts, headers, credentials: "include" });
if (!res.ok) {
const err = new Error("HTTP " + res.status);
err.status = res.status;
@@ -1259,19 +1254,6 @@ button, input, textarea, select { font: inherit; color: inherit; }
return ct.includes("application/json") ? res.json() : res.text();
}
/* ---------- Capture ?token= from URL ---------- */
function captureUrlToken() {
const params = new URLSearchParams(location.search);
const t = params.get("token");
if (t) {
setToken(t);
params.delete("token");
const qs = params.toString();
const newUrl = location.pathname + (qs ? "?" + qs : "") + location.hash;
history.replaceState(null, "", newUrl);
}
}
/* ---------- Theme toggle ---------- */
(function initTheme() {
const KEY = "cereda-theme";
@@ -1290,17 +1272,12 @@ button, input, textarea, select { font: inherit; color: inherit; }
/* ---------- Init ---------- */
async function init() {
captureUrlToken();
const tk = getToken();
if (!tk) return showLogin();
try {
const me = await api("/api/auth/me");
showApp(me);
await loadShares();
} catch (e) {
if (e.status === 401 || e.status === 403) {
clearToken();
showLogin();
} else {
enterDemoMode();
@@ -1311,7 +1288,7 @@ button, input, textarea, select { font: inherit; color: inherit; }
/* ---------- Demo fallback ---------- */
function enterDemoMode() {
demoMode = true;
setToken("demo-token");
demoModeFlag = true;
showApp({ username: "m.schmidt", display_name: "Marco Schmidt" });
demoBadge.classList.add("on");
shares = seedShares();
@@ -1391,12 +1368,11 @@ button, input, textarea, select { font: inherit; color: inherit; }
method: "POST",
body: JSON.stringify({ username, password })
});
if (res && res.token) {
setToken(res.token);
if (res && res.status === "success") {
const me = await api("/api/auth/me").catch(() => null);
showApp(me || { username });
await loadShares();
} else throw new Error("No token in response.");
} else throw new Error("Login fehlgeschlagen.");
} catch (err) {
if (err.status === 401 || err.status === 403) {
// Real auth rejection — show the error
@@ -1413,7 +1389,7 @@ button, input, textarea, select { font: inherit; color: inherit; }
/* ---------- Logout ---------- */
logoutBtn.addEventListener("click", () => {
clearToken();
if (!demoModeFlag) { api("/api/auth/logout", { method: "POST" }).catch(() => {}); }
shares = [];
pickedFile = null;
demoMode = false;
@@ -1593,7 +1569,7 @@ button, input, textarea, select { font: inherit; color: inherit; }
const list = await api("/api/shares");
shares = Array.isArray(list) ? list : (list?.shares || []);
} catch (e) {
if (e.status === 401) { clearToken(); showLogin(); return; }
if (e.status === 401) { showLogin(); return; }
// 403 = not admin, just show empty list — user can still create shares
shares = [];
}

View File

@@ -2,17 +2,7 @@ import React, { useState, useRef, useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import { useAuth } from '../../context/AuthContext';
import aiService from '../../services/aiService';
import { marked } from 'marked';
marked.use({ breaks: true, gfm: true });
const renderMd = (text) => {
try {
const html = marked.parse(String(text || ''), { async: false });
return { __html: typeof html === 'string' ? html : String(html) };
} catch {
return { __html: String(text || '').replace(/\n/g, '<br>') };
}
};
import { renderMd } from '../../utils/sanitizeMarkdown';
const STAFF_ROLES = ['super_admin', 'admin', 'support', 'bearbeiter'];

View File

@@ -20,9 +20,8 @@ export default function RemoteDesktopPanel({ agentId, agentHostname, autoConnect
const connectedRef = useRef(false);
const getWsUrl = () => {
const token = localStorage.getItem('token');
const proto = window.location.protocol === 'https:' ? 'wss' : 'ws';
return `${proto}://${window.location.host}/ws?type=rdp&agentId=${agentId}&token=${token}`;
return `${proto}://${window.location.host}/ws?type=rdp&agentId=${agentId}`;
};
const connect = (screen = screenIdx) => {
@@ -33,6 +32,7 @@ export default function RemoteDesktopPanel({ agentId, agentHostname, autoConnect
connectedRef.current = false;
ws.onopen = () => {
ws.send(JSON.stringify({ type: 'auth', token: localStorage.getItem('token') }));
ws.send(JSON.stringify({ type: 'rdp_start', screen }));
};

View File

@@ -177,10 +177,9 @@ function RemoteShell({ agentId, agentHostname }) {
const inputRef = useRef(null);
const getWsUrl = () => {
const token = localStorage.getItem('token');
const proto = window.location.protocol === 'https:' ? 'wss' : 'ws';
const host = window.location.host;
return `${proto}://${host}/ws?type=shell&agentId=${agentId}&token=${token}`;
return `${proto}://${host}/ws?type=shell&agentId=${agentId}`;
};
const connect = () => {
@@ -191,7 +190,10 @@ function RemoteShell({ agentId, agentHostname }) {
const ws = new WebSocket(getWsUrl());
wsRef.current = ws;
ws.onopen = () => setStatus('connected');
ws.onopen = () => {
ws.send(JSON.stringify({ type: 'auth', token: localStorage.getItem('token') }));
setStatus('connected');
};
ws.onmessage = (e) => {
setOutput(prev => prev + stripAnsi(e.data));
@@ -766,7 +768,7 @@ export default function AgentDetailPage() {
</div>
{/* ── REMOTE TOOLS ─────────────────────────────────────────────────── */}
{(isSuperAdmin || isAdmin) && (
{(isSuperAdmin() || isAdmin()) && (
<div style={{ marginTop: 24 }}>
<div style={{ display: 'flex', gap: 4, marginBottom: 0, borderBottom: '1px solid var(--border-color)' }}>
{[
@@ -790,10 +792,6 @@ export default function AgentDetailPage() {
{shellTab === 'rdp' && <RemoteDesktop agentId={agent.id} agentHostname={agent.hostname} />}
</div>
)}
{!isSuperAdmin && !isAdmin && (
<RemoteShell agentId={agent.id} agentHostname={agent.hostname} />
)}
{/* ── ANKÜNDIGUNG MODAL ────────────────────────────────────────────── */}
{showAnnModal && (
<div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.6)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center' }}

View File

@@ -2,10 +2,7 @@ import React, { useState, useEffect, useRef } from 'react';
import { useAuth } from '../context/AuthContext';
import aiService from '../services/aiService';
import { toast } from 'react-toastify';
import { Marked } from 'marked';
const marked = new Marked({ breaks: true, gfm: true });
const renderMd = (text) => ({ __html: marked.parse(text) });
import { renderMd } from '../utils/sanitizeMarkdown';
const WELCOME_MSG = {
role: 'assistant',

View File

@@ -1,5 +1,6 @@
import React, { useState, useEffect } from 'react';
import { Marked } from 'marked';
import { sanitizeHtml } from '../utils/sanitizeMarkdown';
const marked = new Marked({ breaks: true, gfm: true });
@@ -42,10 +43,11 @@ export default function DocsPage() {
}
// Add IDs to headings for anchor links
const html = marked.parse(text);
return html.replace(/<h([23])>(.*?)<\/h\1>/g, (_, level, heading) => {
const withIds = html.replace(/<h([23])>(.*?)<\/h\1>/g, (_, level, heading) => {
const id = slugify(heading.replace(/<[^>]+>/g, ''));
return `<h${level} id="${id}">${heading}</h${level}>`;
});
return sanitizeHtml(withIds);
};
if (loading) return (

View File

@@ -25,8 +25,17 @@ const FidoKeysPage = () => {
serial_number: '',
status: 'aktiv',
description: '',
pin: '',
assigned_to_user_id: '',
});
const [revealedPins, setRevealedPins] = useState({});
const togglePinReveal = (id) => {
setRevealedPins(prev => ({ ...prev, [id]: !prev[id] }));
if (!revealedPins[id]) {
setTimeout(() => setRevealedPins(prev => ({ ...prev, [id]: false })), 8000);
}
};
useEffect(() => {
loadKeys();
@@ -69,7 +78,7 @@ const FidoKeysPage = () => {
const handleCreate = () => {
setEditingKey(null);
setFormData({ name: '', serial_number: '', status: 'aktiv', description: '', assigned_to_user_id: '' });
setFormData({ name: '', serial_number: '', status: 'aktiv', description: '', pin: '', assigned_to_user_id: '' });
setShowModal(true);
};
@@ -80,6 +89,7 @@ const FidoKeysPage = () => {
serial_number: key.serial_number,
status: key.status,
description: key.description || '',
pin: key.pin || '',
assigned_to_user_id: key.assigned_to_user_id || '',
});
setShowModal(true);
@@ -181,6 +191,7 @@ const FidoKeysPage = () => {
<th>Seriennummer</th>
<th>Status</th>
<th>Zugewiesen an</th>
<th>PIN</th>
<th>Beschreibung</th>
<th>Erstellt von</th>
<th>Aktionen</th>
@@ -189,13 +200,20 @@ const FidoKeysPage = () => {
<tbody>
{filteredKeys.length === 0 ? (
<tr>
<td colSpan="7" className="text-center">Keine FIDO-Keys gefunden</td>
<td colSpan="8" className="text-center">Keine FIDO-Keys gefunden</td>
</tr>
) : (
filteredKeys.map((key) => (
<tr key={key.id}>
<td>{key.name}</td>
<td><code style={{fontSize:12}}>{key.serial_number}</code></td>
<td>
<div style={{display:'flex',alignItems:'center',gap:10,fontWeight:600}}>
<div style={{width:32,height:32,borderRadius:8,background:'rgba(63,163,163,0.12)',display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0}}>
<svg viewBox="0 0 24 24" fill="none" stroke="var(--cereda-primary)" strokeWidth="2" width="16" height="16"><circle cx="8" cy="8" r="5"/><path d="M10.5 12.5 19 21M16 16l2-2M19 19l2-2"/></svg>
</div>
{key.name}
</div>
</td>
<td><span style={{fontFamily:'Consolas,monospace',background:'var(--bg-tertiary)',border:'1px solid var(--border-color)',borderRadius:6,padding:'3px 8px',fontSize:12,color:'var(--text-muted)'}}>{key.serial_number}</span></td>
<td>
<span className={`status-badge status-${key.status}`}>{key.status}</span>
</td>
@@ -218,20 +236,50 @@ const FidoKeysPage = () => {
<span style={{color:'var(--text-muted)',fontSize:12}}> nicht zugewiesen</span>
)}
</td>
<td>
{key.pin ? (
<div style={{display:'flex',alignItems:'center',gap:8}}>
<span style={{fontFamily:'Consolas,monospace',background:'var(--bg-tertiary)',border:'1px solid var(--border-color)',borderRadius:6,padding:'3px 10px',fontSize:13,letterSpacing:'0.15em',minWidth:64,textAlign:'center',display:'inline-block'}}>
{revealedPins[key.id] ? key.pin : '••••••'}
</span>
<button
onClick={() => togglePinReveal(key.id)}
title={revealedPins[key.id] ? 'PIN verbergen' : 'PIN anzeigen'}
style={{background:'none',border:'none',cursor:'pointer',color:'var(--text-muted)',padding:2,display:'flex',alignItems:'center'}}
>
{revealedPins[key.id] ? (
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" width="16" height="16"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-7-11-7a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 7 11 7a18.5 18.5 0 0 1-2.16 3.19M14.12 14.12a3 3 0 1 1-4.24-4.24"/><path d="M1 1l22 22"/></svg>
) : (
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" width="16" height="16"><path d="M1 12s4-7 11-7 11 7 11 7-4 7-11 7-11-7-11-7Z"/><circle cx="12" cy="12" r="3"/></svg>
)}
</button>
</div>
) : (
<span style={{color:'var(--text-muted)',fontSize:12}}> keine PIN</span>
)}
</td>
<td>{key.description || '-'}</td>
<td>{key.created_by_username}</td>
<td>
<div className="table-actions">
{canModifyFidoKeys() && (
<>
<button onClick={() => handleEdit(key)} className="btn btn-primary btn-small">Bearbeiten</button>
<button onClick={() => handleStatusToggle(key)} className="btn btn-secondary btn-small">
{key.status === 'aktiv' ? 'Deaktivieren' : 'Aktivieren'}
<button onClick={() => handleEdit(key)} title="Bearbeiten" className="btn btn-secondary btn-small" style={{width:32,padding:0,display:'flex',alignItems:'center',justifyContent:'center'}}>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" width="14" height="14"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4Z"/></svg>
</button>
<button onClick={() => handleStatusToggle(key)} title={key.status === 'aktiv' ? 'Deaktivieren' : 'Aktivieren'} className="btn btn-secondary btn-small" style={{width:32,padding:0,display:'flex',alignItems:'center',justifyContent:'center'}}>
{key.status === 'aktiv' ? (
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" width="14" height="14"><rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/></svg>
) : (
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" width="14" height="14"><path d="M5 3l16 9-16 9V3z"/></svg>
)}
</button>
</>
)}
{isAdmin() && (
<button onClick={() => handleDelete(key.id)} className="btn btn-danger btn-small">Löschen</button>
<button onClick={() => handleDelete(key.id)} title="Löschen" className="btn btn-danger btn-small" style={{width:32,padding:0,display:'flex',alignItems:'center',justifyContent:'center'}}>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" width="14" height="14"><path d="M3 6h18"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2m3 0-1 14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2L4 6"/></svg>
</button>
)}
</div>
</td>
@@ -261,6 +309,20 @@ const FidoKeysPage = () => {
<input type="text" className="form-input" value={formData.serial_number} onChange={(e) => setFormData({ ...formData, serial_number: e.target.value })} required />
</div>
<div className="form-group">
<label className="form-label">PIN</label>
<input
type="text"
className="form-input"
maxLength={6}
pattern="[0-9]{6}"
placeholder="6-stellige PIN"
value={formData.pin}
onChange={(e) => setFormData({ ...formData, pin: e.target.value.replace(/\D/g, '').slice(0, 6) })}
style={{fontFamily:'Consolas,monospace',letterSpacing:'0.2em'}}
/>
</div>
<div className="form-group">
<label className="form-label">Status*</label>
<select className="form-select" value={formData.status} onChange={(e) => setFormData({ ...formData, status: e.target.value })} required>

View File

@@ -4,9 +4,7 @@ import { useAuth } from '../context/AuthContext';
import aiService from '../services/aiService';
import ticketService from '../services/ticketService';
import { toast } from 'react-toastify';
import { Marked } from 'marked';
const marked = new Marked({ breaks: true, gfm: true });
const renderMd = (text) => ({ __html: marked.parse(text || '') });
import { renderMd } from '../utils/sanitizeMarkdown';
const CATEGORIES = ['Allgemein', 'Software', 'Hardware', 'Netzwerk', 'SelectLine', 'Sonstiges'];
const CAT_COLOR = { Software: '#6366f1', Hardware: '#f59e0b', SelectLine: '#10b981', Netzwerk: '#3b82f6', Allgemein: '#64748b', Sonstiges: '#8b5cf6' };

View File

@@ -5,7 +5,7 @@ import { useAuth } from '../context/AuthContext';
const ANN_TYPES = { maintenance: { icon: '🔧', label: 'Wartung', color: '#f59e0b' }, warning: { icon: '⚠️', label: 'Warnung', color: '#ef4444' }, info: { icon: '', label: 'Info', color: '#6366f1' } };
const LATEST_AGENT_VERSION = '2.6.0';
const LATEST_AGENT_VERSION = '2.7.0';
const SEVERITY_LABELS = { critical: 'Kritisch', important: 'Wichtig', moderate: 'Moderat', low: 'Niedrig', all: 'Alle' };
const SEVERITY_COLORS = { critical: '#EF4444', important: '#F59E0B', moderate: '#3B82F6', low: '#6B7280', all: '#0D9488' };
const COMMAND_LABELS = { check_updates: '🔍 Update-Scan', install_updates: '⬇️ Installation', reboot: '🔄 Neustart', upgrade_win11: '🪟 Win 11 Upgrade', update_agent: '⬆️ Agent-Update' };

View File

@@ -1,7 +1,8 @@
import React, { useState, useEffect, useCallback, useMemo } from 'react';
const API = process.env.REACT_APP_API_URL || '/api';
const apiFetch = (url) => fetch(url).then(r => r.ok ? r.json() : null).catch(() => null);
const TV_KEY = new URLSearchParams(window.location.search).get('key') || '';
const apiFetch = (url) => fetch(`${url}${url.includes('?') ? '&' : '?'}key=${encodeURIComponent(TV_KEY)}`).then(r => r.ok ? r.json() : null).catch(() => null);
/* ── Design tokens ──────────────────────────────────────────── */
const LIME = '#7CF53E';

View File

@@ -6,17 +6,7 @@ import userService from '../services/userService';
import assetService from '../services/assetService';
import LoadingSpinner from '../components/common/LoadingSpinner';
import { toast } from 'react-toastify';
import { marked } from 'marked';
marked.use({ breaks: true, gfm: true });
const renderMd = (text) => {
try {
const html = marked.parse(String(text || ''), { async: false });
return { __html: typeof html === 'string' ? html : String(html) };
} catch {
return { __html: String(text || '').replace(/\n/g, '<br>') };
}
};
import { renderMd, sanitizeHtml } from '../utils/sanitizeMarkdown';
const STATUS_CONFIG = {
offen: { label: 'Offen', css: 'status-pending' },
@@ -549,7 +539,7 @@ const TicketDetailPage = () => {
</div>
);
const boldLine = line.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
return <div key={i} style={{ minHeight: line ? undefined : '0.5em' }} dangerouslySetInnerHTML={{ __html: boldLine || '&nbsp;' }} />;
return <div key={i} style={{ minHeight: line ? undefined : '0.5em' }} dangerouslySetInnerHTML={{ __html: sanitizeHtml(boldLine || '&nbsp;') }} />;
})}
</div>
) : (

View File

@@ -712,6 +712,9 @@ const FidoTab = ({ user }) => {
const [showAssign, setShowAssign] = useState(false);
const [assignId, setAssignId] = useState('');
const [saving, setSaving] = useState(false);
const [editingId, setEditingId] = useState(null);
const [editForm, setEditForm] = useState({ name: '', pin: '', status: 'aktiv' });
const [pinRevealed, setPinRevealed] = useState({});
const loadKeys = () => {
setLoading(true);
@@ -751,6 +754,29 @@ const FidoTab = ({ user }) => {
loadKeys();
};
const startEdit = (key) => {
setEditingId(key.id);
setEditForm({ name: key.name, pin: key.pin || '', status: key.status });
};
const saveEdit = async (key) => {
setSaving(true);
try {
await authFetch(`${API}/fido-keys/${key.id}`, {
method: 'PUT',
body: JSON.stringify({ ...key, ...editForm }),
});
setEditingId(null);
loadKeys();
} catch {
} finally { setSaving(false); }
};
const togglePin = (id) => {
setPinRevealed(prev => ({ ...prev, [id]: !prev[id] }));
if (!pinRevealed[id]) setTimeout(() => setPinRevealed(prev => ({ ...prev, [id]: false })), 8000);
};
if (loading) return <div style={{padding:40,textAlign:'center',color:'var(--text-muted)'}}>Lade FIDO-Keys</div>;
const hasEnoughKeys = keys.length >= 2;
@@ -760,17 +786,68 @@ const FidoTab = ({ user }) => {
<div className="bv-fido-hero">
{keys.map((key, i) => (
<div key={key.id} className="bv-fkc-card" style={{position:'relative'}}>
<div style={{position:'absolute',top:8,right:8,display:'flex',gap:6}}>
<button
onClick={() => startEdit(key)}
title="Bearbeiten"
style={{background:'rgba(63,163,163,.12)',border:'1px solid rgba(63,163,163,.3)',color:'var(--cereda-primary)',borderRadius:6,padding:'2px 7px',fontSize:11,cursor:'pointer'}}
> Bearbeiten</button>
<button
onClick={() => handleUnassign(key)}
title="Zuweisung aufheben"
style={{position:'absolute',top:8,right:8,background:'rgba(239,68,68,.12)',border:'1px solid rgba(239,68,68,.3)',color:'#ef4444',borderRadius:6,padding:'2px 7px',fontSize:11,cursor:'pointer'}}
style={{background:'rgba(239,68,68,.12)',border:'1px solid rgba(239,68,68,.3)',color:'#ef4444',borderRadius:6,padding:'2px 7px',fontSize:11,cursor:'pointer'}}
> Entfernen</button>
</div>
<div className="bv-fkc-header">
<div className="bv-fkc-visual"><KeyIcon /></div>
<span className="bv-fkc-type-badge">{i === 0 ? 'PRIMÄR' : 'BACKUP'}</span>
</div>
{editingId === key.id ? (
<div style={{display:'flex',flexDirection:'column',gap:8,marginTop:4}}>
<input
className="form-input"
style={{fontSize:13}}
value={editForm.name}
onChange={e => setEditForm({ ...editForm, name: e.target.value })}
placeholder="Name"
/>
<input
className="form-input"
style={{fontSize:13,fontFamily:'Consolas,monospace',letterSpacing:'0.15em'}}
value={editForm.pin}
maxLength={6}
onChange={e => setEditForm({ ...editForm, pin: e.target.value.replace(/\D/g,'').slice(0,6) })}
placeholder="PIN (6-stellig)"
/>
<select
className="form-select"
style={{fontSize:13}}
value={editForm.status}
onChange={e => setEditForm({ ...editForm, status: e.target.value })}
>
<option value="aktiv">Aktiv</option>
<option value="inaktiv">Inaktiv</option>
</select>
<div style={{display:'flex',gap:8}}>
<button className="btn btn-primary btn-small" onClick={() => saveEdit(key)} disabled={saving}>{saving ? '…' : 'Speichern'}</button>
<button className="btn btn-secondary btn-small" onClick={() => setEditingId(null)}>Abbrechen</button>
</div>
</div>
) : (
<>
<div className="bv-fkc-name">{key.name}</div>
<div className="bv-fkc-sub">{key.manufacturer || 'Yubico'} · {key.connection_type || 'USB'} · SN {key.serial_number}</div>
{key.pin && (
<div style={{display:'flex',alignItems:'center',gap:6,marginTop:6}}>
<span style={{fontFamily:'Consolas,monospace',background:'rgba(0,0,0,.2)',borderRadius:6,padding:'2px 8px',fontSize:12,letterSpacing:'0.15em'}}>
{pinRevealed[key.id] ? key.pin : '••••••'}
</span>
<button onClick={() => togglePin(key.id)} title="PIN anzeigen/verbergen" style={{background:'none',border:'none',cursor:'pointer',color:'inherit',opacity:0.7,padding:0,display:'flex'}}>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" width="13" height="13"><path d="M1 12s4-7 11-7 11 7 11 7-4 7-11 7-11-7-11-7Z"/><circle cx="12" cy="12" r="3"/></svg>
</button>
</div>
)}
<div className="bv-fkc-stats">
<div className="bv-fkc-stat">
<div className="bv-fkcs-v"></div>
@@ -781,6 +858,8 @@ const FidoTab = ({ user }) => {
<div className="bv-fkcs-l">Letzte Nutzung</div>
</div>
</div>
</>
)}
</div>
))}
{showAssign ? (

View File

@@ -7,17 +7,7 @@ import fidoKeyService from '../services/fidoKeyService';
import aiService from '../services/aiService';
import LoadingSpinner from '../components/common/LoadingSpinner';
import { toast } from 'react-toastify';
import { marked } from 'marked';
marked.use({ breaks: true, gfm: true });
const renderMd = (text) => {
try {
const html = marked.parse(String(text || ''), { async: false });
return { __html: typeof html === 'string' ? html : String(html) };
} catch {
return { __html: String(text || '').replace(/\n/g, '<br>') };
}
};
import { renderMd } from '../utils/sanitizeMarkdown';
/* ── Helpers ────────────────────────────────────────────────────── */

View File

@@ -3,33 +3,16 @@ import axios from 'axios';
const API_URL = process.env.REACT_APP_API_URL || '/api';
// Create axios instance
// Auth läuft über ein httpOnly-Cookie (vom Server gesetzt) — kein Token in JS-lesbarem Storage,
// damit ein XSS-Treffer das Session-Token nicht einfach auslesen kann.
const api = axios.create({
baseURL: API_URL,
withCredentials: true,
headers: {
'Content-Type': 'application/json',
},
});
// Request interceptor to add token to requests
api.interceptors.request.use(
(config) => {
const token = localStorage.getItem('token');
if (token) {
if (typeof config.headers?.set === 'function') {
config.headers.set('Authorization', `Bearer ${token}`);
} else if (config.headers) {
config.headers['Authorization'] = `Bearer ${token}`;
} else {
config.headers = { 'Authorization': `Bearer ${token}` };
}
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
// Response interceptor to handle errors globally
api.interceptors.response.use(
(response) => {
@@ -39,7 +22,6 @@ api.interceptors.response.use(
if (error.response) {
// Handle 401 Unauthorized - token expired or invalid
if (error.response.status === 401) {
localStorage.removeItem('token');
localStorage.removeItem('user');
window.location.href = '/login';
}

View File

@@ -0,0 +1,20 @@
import { Marked } from 'marked';
import DOMPurify from 'dompurify';
const marked = new Marked({ breaks: true, gfm: true });
// Rendert Markdown zu HTML und entfernt anschließend aktive Inhalte (script, on*-Attribute,
// javascript:-URLs etc.) — verhindert Stored XSS über KI-Antworten/Kommentare/Knowledge-Base.
export function renderMd(text) {
try {
const html = marked.parse(String(text || ''), { async: false });
const raw = typeof html === 'string' ? html : String(html);
return { __html: DOMPurify.sanitize(raw) };
} catch {
return { __html: DOMPurify.sanitize(String(text || '').replace(/\n/g, '<br>')) };
}
}
export function sanitizeHtml(html) {
return DOMPurify.sanitize(String(html || ''));
}

26
shell-client.js Normal file
View File

@@ -0,0 +1,26 @@
const WebSocket = require('ws');
const fs = require('fs');
const token = process.argv[2];
const agentId = process.argv[3];
const command = process.argv[4].startsWith('@') ? fs.readFileSync(process.argv[4].slice(1), 'utf8') : process.argv[4];
const ws = new WebSocket(`ws://localhost:5000/ws?type=shell&agentId=${agentId}`);
let buffer = '';
ws.on('open', () => {
ws.send(JSON.stringify({ type: 'auth', token }));
setTimeout(() => {
ws.send(command + '\r\n');
}, 1500);
});
ws.on('message', (data) => {
buffer += data.toString();
});
const waitMs = parseInt(process.argv[5]) || 8000;
setTimeout(() => {
console.log(buffer);
process.exit(0);
}, waitMs);