Merge remote-tracking branch 'origin/secure' into secure

This commit is contained in:
karimik
2025-10-22 13:37:24 +02:00
2 changed files with 35 additions and 33 deletions
+18 -26
View File
@@ -22,22 +22,20 @@ function logAttempt(username, status, ip, extra = '') {
} }
app.post('/login', async (req, res) => { app.post('/login', async (req, res) => {
const { username, password, captcha } = req.body; const {username, password, captcha} = req.body;
const ip = req.ip || req.connection.remoteAddress; const ip = req.ip || req.connection.remoteAddress;
const user = users.find(u => u.username === username && u.password === password); const user = users.find(u => u.username === username && u.password === password);
const now = Date.now(); const now = Date.now();
// Init
if (!loginAttempts[username]) { if (!loginAttempts[username]) {
loginAttempts[username] = { loginAttempts[username] = {
count: 0, count: 0,
lockedUntil: null, lockedUntil: null,
lastFail: null, lastFail: null,
requiresCaptcha: false requiresCaptcha: false,
cooldownUntil: null
}; };
} }
const state = loginAttempts[username]; const state = loginAttempts[username];
// Lockout prüfen
if (state.lockedUntil && now < state.lockedUntil) { if (state.lockedUntil && now < state.lockedUntil) {
const remaining = Math.ceil((state.lockedUntil - now) / 1000); const remaining = Math.ceil((state.lockedUntil - now) / 1000);
logAttempt(username, 'LOCKED', ip, `Noch gesperrt: ${remaining}s`); logAttempt(username, 'LOCKED', ip, `Noch gesperrt: ${remaining}s`);
@@ -46,7 +44,15 @@ app.post('/login', async (req, res) => {
error: `Benutzer gesperrt. Bitte in ${remaining}s erneut versuchen.` error: `Benutzer gesperrt. Bitte in ${remaining}s erneut versuchen.`
}); });
} }
if (state.cooldownUntil && now < state.cooldownUntil) {
const remaining = Math.ceil((state.cooldownUntil - now) / 1000);
logAttempt(username, 'COOLDOWN', ip, `Wartezeit noch ${remaining}s`);
return res.status(429).json({
ok: false,
error: `Bitte ${remaining}s warten, bevor du es erneut versuchst.`,
requiresCaptcha: state.requiresCaptcha
});
}
if (state.requiresCaptcha) { if (state.requiresCaptcha) {
if (!captcha || typeof captcha !== 'string') { if (!captcha || typeof captcha !== 'string') {
logAttempt(username, 'CAPTCHA_MISSING', ip); logAttempt(username, 'CAPTCHA_MISSING', ip);
@@ -56,7 +62,6 @@ app.post('/login', async (req, res) => {
requiresCaptcha: true requiresCaptcha: true
}); });
} }
try { try {
const verify = await axios.post( const verify = await axios.post(
'https://hcaptcha.com/siteverify', 'https://hcaptcha.com/siteverify',
@@ -66,7 +71,6 @@ app.post('/login', async (req, res) => {
remoteip: req.ip remoteip: req.ip
}) })
); );
if (!verify.data.success) { if (!verify.data.success) {
logAttempt(username, 'CAPTCHA_FAIL', ip); logAttempt(username, 'CAPTCHA_FAIL', ip);
return res.status(403).json({ return res.status(403).json({
@@ -84,20 +88,17 @@ app.post('/login', async (req, res) => {
}); });
} }
} }
// Erfolg
if (user) { if (user) {
loginAttempts[username] = undefined; delete loginAttempts[username];
logAttempt(username, 'SUCCESS', ip); logAttempt(username, 'SUCCESS', ip);
return res.json({ ok: true, message: 'Login erfolgreich' }); return res.json({ok: true, message: 'Login erfolgreich'});
} }
// Fehlversuch
state.count++; state.count++;
state.lastFail = now; state.lastFail = now;
logAttempt(username, 'FAIL', ip, `Fehlversuche: ${state.count}`); logAttempt(username, 'FAIL', ip, `Fehlversuche: ${state.count}`);
if (state.count >= 3) {
// Lockout nach Schwelle state.requiresCaptcha = true;
}
if (state.count >= LOCKOUT_THRESHOLD) { if (state.count >= LOCKOUT_THRESHOLD) {
state.lockedUntil = now + LOCKOUT_DURATION; state.lockedUntil = now + LOCKOUT_DURATION;
state.count = 0; state.count = 0;
@@ -107,16 +108,8 @@ app.post('/login', async (req, res) => {
error: `Zu viele Fehlversuche. Benutzer für 15 Minuten gesperrt.` error: `Zu viele Fehlversuche. Benutzer für 15 Minuten gesperrt.`
}); });
} }
// Captcha aktivieren nach 3 Fehlversuchen
if (state.count >= 3) {
state.requiresCaptcha = true;
}
// Verzögerung anwenden
const delay = PROGRESSIVE_DELAYS[state.count - 1] || LINEAR_DELAY_MS; const delay = PROGRESSIVE_DELAYS[state.count - 1] || LINEAR_DELAY_MS;
await new Promise(r => setTimeout(r, delay)); state.cooldownUntil = now + delay;
return res.status(401).json({ return res.status(401).json({
ok: false, ok: false,
error: `Falscher Benutzername oder Passwort. Wartezeit: ${delay / 1000}s`, error: `Falscher Benutzername oder Passwort. Wartezeit: ${delay / 1000}s`,
@@ -124,7 +117,6 @@ app.post('/login', async (req, res) => {
}); });
}); });
// Einfaches Frontend für Tests
app.get('/login', (req, res) => { app.get('/login', (req, res) => {
res.sendFile(__dirname + '/index.html'); res.sendFile(__dirname + '/index.html');
}); });
+17 -7
View File
@@ -1,8 +1,8 @@
<!doctype html> <!doctype html>
<html lang="de"> <html lang="de">
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Login</title> <title>Login</title>
<link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
@@ -22,7 +22,7 @@
background: white; background: white;
padding: 32px; padding: 32px;
border-radius: 12px; border-radius: 12px;
box-shadow: 0 8px 24px rgba(0,0,0,0.1); box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
max-width: 400px; max-width: 400px;
width: 100%; width: 100%;
} }
@@ -97,9 +97,9 @@
<h1>Login</h1> <h1>Login</h1>
<form id="login"> <form id="login">
<label for="username">Benutzername</label> <label for="username">Benutzername</label>
<input id="username" name="username" required /> <input id="username" name="username" required/>
<label for="password">Passwort</label> <label for="password">Passwort</label>
<input id="password" name="password" type="password" required /> <input id="password" name="password" type="password" required/>
<div id="captcha-container"> <div id="captcha-container">
<div class="h-captcha" data-sitekey="10000000-ffff-ffff-ffff-000000000001"></div> <div class="h-captcha" data-sitekey="10000000-ffff-ffff-ffff-000000000001"></div>
</div> </div>
@@ -112,6 +112,7 @@
const form = document.getElementById('login'); const form = document.getElementById('login');
const msg = document.getElementById('msg'); const msg = document.getElementById('msg');
const captchaContainer = document.getElementById('captcha-container'); const captchaContainer = document.getElementById('captcha-container');
form.addEventListener('submit', async (e) => { form.addEventListener('submit', async (e) => {
e.preventDefault(); e.preventDefault();
msg.style.display = 'none'; msg.style.display = 'none';
@@ -119,13 +120,22 @@
const password = document.getElementById('password').value; const password = document.getElementById('password').value;
const captcha = hcaptcha.getResponse(); const captcha = hcaptcha.getResponse();
const body = { username, password, captcha }; const body = { username, password, captcha };
try { try {
const res = await fetch('/login', { const res = await fetch('/login', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body) body: JSON.stringify(body)
}); });
const data = await res.json();
let data = {};
try {
data = await res.json(); // versuche JSON zu parsen
} catch (e) {
console.warn("Antwort war kein JSON:", e);
data = { ok: false, error: res.statusText };
}
msg.style.display = 'block'; msg.style.display = 'block';
if (res.ok && data.ok) { if (res.ok && data.ok) {
msg.textContent = '✅ Erfolgreich eingeloggt!'; msg.textContent = '✅ Erfolgreich eingeloggt!';
@@ -134,12 +144,12 @@
} else { } else {
msg.textContent = '❌ ' + (data.error || 'Login fehlgeschlagen'); msg.textContent = '❌ ' + (data.error || 'Login fehlgeschlagen');
msg.className = 'msg error'; msg.className = 'msg error';
msg.style.display = 'block';
if (data.requiresCaptcha) { if (data.requiresCaptcha) {
captchaContainer.style.display = 'block'; captchaContainer.style.display = 'block';
hcaptcha.reset(); hcaptcha.reset();
} }
} }
} catch (err) { } catch (err) {
msg.textContent = '⚠️ Netzwerkfehler: ' + err.message; msg.textContent = '⚠️ Netzwerkfehler: ' + err.message;
msg.className = 'msg error'; msg.className = 'msg error';