Datenbank bereinigt / Gitea-Integration gefixt
Dieser Commit ist enthalten in:
committet von
Server Deploy
Ursprung
395598c2b0
Commit
c21be47428
@ -5,15 +5,22 @@
|
||||
*/
|
||||
|
||||
const jwt = require('jsonwebtoken');
|
||||
const crypto = require('crypto');
|
||||
const logger = require('../utils/logger');
|
||||
const { getDb } = require('../database');
|
||||
|
||||
const JWT_SECRET = process.env.JWT_SECRET || 'UNSICHER_BITTE_AENDERN';
|
||||
const JWT_SECRET = process.env.JWT_SECRET;
|
||||
if (!JWT_SECRET || JWT_SECRET.length < 32) {
|
||||
throw new Error('JWT_SECRET muss in .env gesetzt und mindestens 32 Zeichen lang sein!');
|
||||
}
|
||||
const ACCESS_TOKEN_EXPIRY = 15; // Minuten (kürzer für mehr Sicherheit)
|
||||
const REFRESH_TOKEN_EXPIRY = 7 * 24 * 60; // 7 Tage in Minuten
|
||||
const SESSION_TIMEOUT = parseInt(process.env.SESSION_TIMEOUT) || 30; // Minuten
|
||||
|
||||
/**
|
||||
* JWT-Token generieren
|
||||
* JWT Access-Token generieren (kurze Lebensdauer)
|
||||
*/
|
||||
function generateToken(user) {
|
||||
function generateAccessToken(user) {
|
||||
// Permissions parsen falls als String gespeichert
|
||||
let permissions = user.permissions || [];
|
||||
if (typeof permissions === 'string') {
|
||||
@ -31,13 +38,38 @@ function generateToken(user) {
|
||||
displayName: user.display_name,
|
||||
color: user.color,
|
||||
role: user.role || 'user',
|
||||
permissions: permissions
|
||||
permissions: permissions,
|
||||
type: 'access'
|
||||
},
|
||||
JWT_SECRET,
|
||||
{ expiresIn: `${SESSION_TIMEOUT}m` }
|
||||
{ expiresIn: `${ACCESS_TOKEN_EXPIRY}m` }
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh-Token generieren (lange Lebensdauer)
|
||||
*/
|
||||
function generateRefreshToken(userId, ipAddress, userAgent) {
|
||||
const db = getDb();
|
||||
const token = crypto.randomBytes(32).toString('hex');
|
||||
const expiresAt = new Date(Date.now() + REFRESH_TOKEN_EXPIRY * 60 * 1000);
|
||||
|
||||
// Token in Datenbank speichern
|
||||
db.prepare(`
|
||||
INSERT INTO refresh_tokens (user_id, token, expires_at, ip_address, user_agent)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
`).run(userId, token, expiresAt.toISOString(), ipAddress, userAgent);
|
||||
|
||||
return token;
|
||||
}
|
||||
|
||||
/**
|
||||
* Legacy generateToken für Rückwärtskompatibilität
|
||||
*/
|
||||
function generateToken(user) {
|
||||
return generateAccessToken(user);
|
||||
}
|
||||
|
||||
/**
|
||||
* JWT-Token verifizieren
|
||||
*/
|
||||
@ -179,8 +211,72 @@ function generateCsrfToken() {
|
||||
return randomBytes(32).toString('hex');
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh-Token validieren und neuen Access-Token generieren
|
||||
*/
|
||||
async function refreshAccessToken(refreshToken, ipAddress, userAgent) {
|
||||
const db = getDb();
|
||||
|
||||
// Token in Datenbank suchen
|
||||
const tokenRecord = db.prepare(`
|
||||
SELECT rt.*, u.* FROM refresh_tokens rt
|
||||
JOIN users u ON rt.user_id = u.id
|
||||
WHERE rt.token = ? AND rt.expires_at > datetime('now')
|
||||
`).get(refreshToken);
|
||||
|
||||
if (!tokenRecord) {
|
||||
throw new Error('Ungültiger oder abgelaufener Refresh-Token');
|
||||
}
|
||||
|
||||
// Token als benutzt markieren
|
||||
db.prepare(`
|
||||
UPDATE refresh_tokens SET last_used = CURRENT_TIMESTAMP WHERE id = ?
|
||||
`).run(tokenRecord.id);
|
||||
|
||||
// Neuen Access-Token generieren
|
||||
const user = {
|
||||
id: tokenRecord.user_id,
|
||||
username: tokenRecord.username,
|
||||
display_name: tokenRecord.display_name,
|
||||
color: tokenRecord.color,
|
||||
role: tokenRecord.role,
|
||||
permissions: tokenRecord.permissions
|
||||
};
|
||||
|
||||
return generateAccessToken(user);
|
||||
}
|
||||
|
||||
/**
|
||||
* Alle Refresh-Tokens eines Benutzers löschen (Logout auf allen Geräten)
|
||||
*/
|
||||
function revokeAllRefreshTokens(userId) {
|
||||
const db = getDb();
|
||||
db.prepare('DELETE FROM refresh_tokens WHERE user_id = ?').run(userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Abgelaufene Refresh-Tokens aufräumen
|
||||
*/
|
||||
function cleanupExpiredTokens() {
|
||||
const db = getDb();
|
||||
const result = db.prepare(`
|
||||
DELETE FROM refresh_tokens WHERE expires_at < datetime('now')
|
||||
`).run();
|
||||
|
||||
if (result.changes > 0) {
|
||||
logger.info(`Bereinigt: ${result.changes} abgelaufene Refresh-Tokens`);
|
||||
}
|
||||
}
|
||||
|
||||
// Cleanup alle 6 Stunden
|
||||
setInterval(cleanupExpiredTokens, 6 * 60 * 60 * 1000);
|
||||
|
||||
module.exports = {
|
||||
generateToken,
|
||||
generateAccessToken,
|
||||
generateRefreshToken,
|
||||
refreshAccessToken,
|
||||
revokeAllRefreshTokens,
|
||||
verifyToken,
|
||||
authenticateToken,
|
||||
authenticateSocket,
|
||||
|
||||
@ -7,6 +7,7 @@
|
||||
const multer = require('multer');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const crypto = require('crypto');
|
||||
const { v4: uuidv4 } = require('uuid');
|
||||
const logger = require('../utils/logger');
|
||||
|
||||
@ -18,18 +19,54 @@ if (!fs.existsSync(UPLOAD_DIR)) {
|
||||
fs.mkdirSync(UPLOAD_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
// Mapping: Dateiendung -> erlaubte MIME-Types
|
||||
const EXTENSION_TO_MIME = {
|
||||
// Dokumente
|
||||
'pdf': ['application/pdf'],
|
||||
'doc': ['application/msword'],
|
||||
'docx': ['application/vnd.openxmlformats-officedocument.wordprocessingml.document'],
|
||||
'xls': ['application/vnd.ms-excel'],
|
||||
'xlsx': ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],
|
||||
'ppt': ['application/vnd.ms-powerpoint'],
|
||||
'pptx': ['application/vnd.openxmlformats-officedocument.presentationml.presentation'],
|
||||
'odt': ['application/vnd.oasis.opendocument.text'],
|
||||
'ods': ['application/vnd.oasis.opendocument.spreadsheet'],
|
||||
'odp': ['application/vnd.oasis.opendocument.presentation'],
|
||||
'rtf': ['application/rtf', 'text/rtf'],
|
||||
// Text
|
||||
'txt': ['text/plain'],
|
||||
'csv': ['text/csv', 'application/csv', 'text/comma-separated-values'],
|
||||
'md': ['text/markdown', 'text/x-markdown', 'text/plain'],
|
||||
'json': ['application/json', 'text/json'],
|
||||
'xml': ['application/xml', 'text/xml'],
|
||||
'html': ['text/html'],
|
||||
'log': ['text/plain'],
|
||||
// Bilder
|
||||
'jpg': ['image/jpeg'],
|
||||
'jpeg': ['image/jpeg'],
|
||||
'png': ['image/png'],
|
||||
'gif': ['image/gif'],
|
||||
'webp': ['image/webp'],
|
||||
'svg': ['image/svg+xml'],
|
||||
'bmp': ['image/bmp'],
|
||||
'ico': ['image/x-icon', 'image/vnd.microsoft.icon'],
|
||||
// Archive
|
||||
'zip': ['application/zip', 'application/x-zip-compressed'],
|
||||
'rar': ['application/x-rar-compressed', 'application/vnd.rar'],
|
||||
'7z': ['application/x-7z-compressed'],
|
||||
'tar': ['application/x-tar'],
|
||||
'gz': ['application/gzip', 'application/x-gzip'],
|
||||
// Code/Skripte (als text/plain akzeptiert)
|
||||
'sql': ['application/sql', 'text/plain'],
|
||||
'js': ['text/javascript', 'application/javascript', 'text/plain'],
|
||||
'css': ['text/css', 'text/plain'],
|
||||
'py': ['text/x-python', 'text/plain'],
|
||||
'sh': ['application/x-sh', 'text/plain']
|
||||
};
|
||||
|
||||
// Standard-Werte (Fallback)
|
||||
let MAX_FILE_SIZE = (parseInt(process.env.MAX_FILE_SIZE_MB) || 15) * 1024 * 1024;
|
||||
let ALLOWED_MIME_TYPES = [
|
||||
'image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml',
|
||||
'application/pdf',
|
||||
'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
||||
'text/plain', 'text/csv', 'text/markdown',
|
||||
'application/zip', 'application/x-rar-compressed', 'application/x-7z-compressed',
|
||||
'application/json'
|
||||
];
|
||||
let ALLOWED_EXTENSIONS = ['pdf', 'docx', 'txt'];
|
||||
|
||||
/**
|
||||
* Lädt Upload-Einstellungen aus der Datenbank
|
||||
@ -43,17 +80,9 @@ function loadUploadSettings() {
|
||||
if (settings) {
|
||||
MAX_FILE_SIZE = (settings.maxFileSizeMB || 15) * 1024 * 1024;
|
||||
|
||||
// Erlaubte MIME-Types aus den aktiven Kategorien zusammenstellen
|
||||
const types = [];
|
||||
if (settings.allowedTypes) {
|
||||
Object.values(settings.allowedTypes).forEach(category => {
|
||||
if (category.enabled && Array.isArray(category.types)) {
|
||||
types.push(...category.types);
|
||||
}
|
||||
});
|
||||
}
|
||||
if (types.length > 0) {
|
||||
ALLOWED_MIME_TYPES = types;
|
||||
// Erlaubte Endungen aus den Einstellungen
|
||||
if (Array.isArray(settings.allowedExtensions) && settings.allowedExtensions.length > 0) {
|
||||
ALLOWED_EXTENSIONS = settings.allowedExtensions;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
@ -67,7 +96,7 @@ function loadUploadSettings() {
|
||||
*/
|
||||
function getCurrentSettings() {
|
||||
loadUploadSettings();
|
||||
return { maxFileSize: MAX_FILE_SIZE, allowedMimeTypes: ALLOWED_MIME_TYPES };
|
||||
return { maxFileSize: MAX_FILE_SIZE, allowedExtensions: ALLOWED_EXTENSIONS };
|
||||
}
|
||||
|
||||
/**
|
||||
@ -99,19 +128,83 @@ const storage = multer.diskStorage({
|
||||
});
|
||||
|
||||
/**
|
||||
* Datei-Filter
|
||||
* Gefährliche Dateinamen prüfen
|
||||
*/
|
||||
function isSecureFilename(filename) {
|
||||
// Null-Bytes, Pfad-Traversal, Steuerzeichen blocken
|
||||
const dangerousPatterns = [
|
||||
/\x00/, // Null-Bytes
|
||||
/\.\./, // Path traversal
|
||||
/[<>:"\\|?*]/, // Windows-spezifische gefährliche Zeichen
|
||||
/[\x00-\x1F]/, // Steuerzeichen
|
||||
/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i, // Windows reservierte Namen
|
||||
];
|
||||
|
||||
return !dangerousPatterns.some(pattern => pattern.test(filename));
|
||||
}
|
||||
|
||||
/**
|
||||
* Datei-Filter: Erweiterte Sicherheitsprüfungen
|
||||
*/
|
||||
const fileFilter = (req, file, cb) => {
|
||||
// Aktuelle Einstellungen laden
|
||||
const settings = getCurrentSettings();
|
||||
|
||||
// MIME-Type prüfen
|
||||
if (settings.allowedMimeTypes.includes(file.mimetype)) {
|
||||
cb(null, true);
|
||||
} else {
|
||||
logger.warn(`Abgelehnter Upload: ${file.originalname} (${file.mimetype})`);
|
||||
cb(new Error(`Dateityp nicht erlaubt: ${file.mimetype}`), false);
|
||||
// Sicherheitsprüfungen für Dateinamen
|
||||
if (!isSecureFilename(file.originalname)) {
|
||||
logger.warn(`Unsicherer Dateiname abgelehnt: ${file.originalname}`);
|
||||
cb(new Error('Dateiname enthält nicht erlaubte Zeichen'), false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Dateiname-Länge prüfen
|
||||
if (file.originalname.length > 255) {
|
||||
logger.warn(`Dateiname zu lang: ${file.originalname}`);
|
||||
cb(new Error('Dateiname ist zu lang (max. 255 Zeichen)'), false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Dateiendung extrahieren (ohne Punkt, lowercase)
|
||||
const ext = path.extname(file.originalname).toLowerCase().replace('.', '');
|
||||
|
||||
// Doppelte Dateiendungen verhindern (z.B. script.txt.exe)
|
||||
const nameWithoutExt = path.basename(file.originalname, path.extname(file.originalname));
|
||||
if (path.extname(nameWithoutExt)) {
|
||||
logger.warn(`Doppelte Dateiendung abgelehnt: ${file.originalname}`);
|
||||
cb(new Error('Dateien mit mehreren Endungen sind nicht erlaubt'), false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Prüfen ob Endung erlaubt ist
|
||||
if (!settings.allowedExtensions.includes(ext)) {
|
||||
logger.warn(`Abgelehnter Upload (Endung): ${file.originalname} (.${ext})`);
|
||||
cb(new Error(`Dateityp .${ext} nicht erlaubt`), false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Executable Dateien zusätzlich blocken
|
||||
const executableExtensions = [
|
||||
'exe', 'bat', 'cmd', 'com', 'scr', 'pif', 'vbs', 'vbe', 'js', 'jar',
|
||||
'app', 'deb', 'pkg', 'dmg', 'run', 'bin', 'msi', 'gadget'
|
||||
];
|
||||
if (executableExtensions.includes(ext)) {
|
||||
logger.warn(`Executable Datei abgelehnt: ${file.originalname}`);
|
||||
cb(new Error('Ausführbare Dateien sind nicht erlaubt'), false);
|
||||
return;
|
||||
}
|
||||
|
||||
// MIME-Type gegen bekannte Typen prüfen
|
||||
const expectedMimes = EXTENSION_TO_MIME[ext];
|
||||
if (expectedMimes && !expectedMimes.includes(file.mimetype)) {
|
||||
logger.warn(`MIME-Mismatch: ${file.originalname} (erwartet: ${expectedMimes.join('/')}, bekommen: ${file.mimetype})`);
|
||||
// Bei kritischen Mismatches ablehnen
|
||||
if (file.mimetype === 'application/octet-stream' || file.mimetype.startsWith('application/x-')) {
|
||||
cb(new Error('Verdächtiger Dateityp erkannt'), false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
cb(null, true);
|
||||
};
|
||||
|
||||
/**
|
||||
@ -194,5 +287,6 @@ module.exports = {
|
||||
getCurrentSettings,
|
||||
UPLOAD_DIR,
|
||||
MAX_FILE_SIZE,
|
||||
ALLOWED_MIME_TYPES
|
||||
ALLOWED_EXTENSIONS,
|
||||
EXTENSION_TO_MIME
|
||||
};
|
||||
|
||||
@ -5,24 +5,52 @@
|
||||
*/
|
||||
|
||||
const sanitizeHtml = require('sanitize-html');
|
||||
const createDOMPurify = require('dompurify');
|
||||
const { JSDOM } = require('jsdom');
|
||||
|
||||
// DOMPurify für Server-side Rendering initialisieren
|
||||
const window = new JSDOM('').window;
|
||||
const DOMPurify = createDOMPurify(window);
|
||||
|
||||
/**
|
||||
* HTML-Tags entfernen (für reine Text-Felder)
|
||||
* HTML-Entities dekodieren
|
||||
*/
|
||||
function stripHtml(input) {
|
||||
if (typeof input !== 'string') return input;
|
||||
return sanitizeHtml(input, {
|
||||
allowedTags: [],
|
||||
allowedAttributes: {}
|
||||
}).trim();
|
||||
function decodeHtmlEntities(str) {
|
||||
if (typeof str !== 'string') return str;
|
||||
const entities = {
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
'"': '"',
|
||||
''': "'",
|
||||
''': "'",
|
||||
''': "'"
|
||||
};
|
||||
return str.replace(/&(amp|lt|gt|quot|#039|#x27|apos);/g, match => entities[match] || match);
|
||||
}
|
||||
|
||||
/**
|
||||
* Markdown-sichere Bereinigung (erlaubt bestimmte Tags)
|
||||
* HTML-Tags entfernen (für reine Text-Felder)
|
||||
* Wichtig: sanitize-html encoded &-Zeichen zu &, daher dekodieren wir danach
|
||||
*/
|
||||
function stripHtml(input) {
|
||||
if (typeof input !== 'string') return input;
|
||||
const sanitized = sanitizeHtml(input, {
|
||||
allowedTags: [],
|
||||
allowedAttributes: {}
|
||||
}).trim();
|
||||
// Entities wieder dekodieren, da sanitize-html sie encoded
|
||||
return decodeHtmlEntities(sanitized);
|
||||
}
|
||||
|
||||
/**
|
||||
* Markdown-sichere Bereinigung mit DOMPurify (doppelte Sicherheit)
|
||||
*/
|
||||
function sanitizeMarkdown(input) {
|
||||
if (typeof input !== 'string') return input;
|
||||
return sanitizeHtml(input, {
|
||||
|
||||
// Erste Bereinigung mit sanitize-html
|
||||
const firstPass = sanitizeHtml(input, {
|
||||
allowedTags: [
|
||||
'p', 'br', 'strong', 'em', 'u', 's', 'code', 'pre',
|
||||
'ul', 'ol', 'li', 'blockquote', 'a', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
|
||||
@ -44,6 +72,16 @@ function sanitizeMarkdown(input) {
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Zweite Bereinigung mit DOMPurify (zusätzliche Sicherheit)
|
||||
return DOMPurify.sanitize(firstPass, {
|
||||
ALLOWED_TAGS: [
|
||||
'p', 'br', 'strong', 'em', 'u', 's', 'code', 'pre',
|
||||
'ul', 'ol', 'li', 'blockquote', 'a', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
|
||||
],
|
||||
ALLOWED_ATTR: ['href', 'title', 'target', 'rel'],
|
||||
ALLOWED_URI_REGEXP: /^(?:(?:(?:f|ht)tps?|mailto):|[^a-z]|[a-z+.-]+(?:[^a-z+.-:]|$))/i
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@ -65,7 +103,15 @@ function sanitizeObject(obj, options = {}) {
|
||||
for (const [key, value] of Object.entries(obj)) {
|
||||
// Bestimmte Felder dürfen Markdown enthalten
|
||||
const allowHtml = ['description', 'content'].includes(key);
|
||||
sanitized[key] = sanitizeObject(value, { allowHtml });
|
||||
|
||||
// Passwort-Felder NICHT sanitizen (Sonderzeichen erhalten)
|
||||
const skipSanitization = ['password', 'oldPassword', 'newPassword', 'confirmPassword'].includes(key);
|
||||
|
||||
if (skipSanitization) {
|
||||
sanitized[key] = value; // Passwort unverändert lassen
|
||||
} else {
|
||||
sanitized[key] = sanitizeObject(value, { allowHtml });
|
||||
}
|
||||
}
|
||||
return sanitized;
|
||||
}
|
||||
@ -119,12 +165,32 @@ const validators = {
|
||||
},
|
||||
|
||||
/**
|
||||
* URL-Format prüfen
|
||||
* URL-Format prüfen (erweiterte Sicherheit)
|
||||
*/
|
||||
url: (value, fieldName) => {
|
||||
try {
|
||||
if (value) {
|
||||
new URL(value);
|
||||
const url = new URL(value);
|
||||
|
||||
// Nur HTTP/HTTPS erlauben
|
||||
if (!['http:', 'https:'].includes(url.protocol)) {
|
||||
return `${fieldName} muss HTTP oder HTTPS verwenden`;
|
||||
}
|
||||
|
||||
// Localhost und private IPs blocken (SSRF-Schutz)
|
||||
const hostname = url.hostname;
|
||||
if (hostname === 'localhost' ||
|
||||
hostname === '127.0.0.1' ||
|
||||
hostname.startsWith('192.168.') ||
|
||||
hostname.startsWith('10.') ||
|
||||
hostname.startsWith('172.')) {
|
||||
return `${fieldName} darf nicht auf lokale Adressen verweisen`;
|
||||
}
|
||||
|
||||
// JavaScript URLs blocken
|
||||
if (url.href.toLowerCase().startsWith('javascript:')) {
|
||||
return `${fieldName} enthält ungültigen JavaScript-Code`;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
} catch {
|
||||
|
||||
In neuem Issue referenzieren
Einen Benutzer sperren