Major refactor: auth, bug fixes, security hardening, modular routes

Bug fixes
- Sync database.js schema with actual production DB (tarifoptionen
  shape was wrong; new installs would have broken).
- Fix SQL syntax error `SELECT to.*` (reserved keyword) in single-
  schaltung provision endpoint, plus the dead fallback hierarchy
  that selected columns that were never in the query.
- Fix PUT /api/tarifoptionen/:id writing to non-existent column
  provision_betrag (should be provision_euro).
- Fix race condition in PUT /api/schaltungen/:id where forEach with
  async db.run inside a transaction could send duplicate responses.
- Delete dokumente rows explicitly before deleting schaltung
  (existing DBs lack ON DELETE CASCADE on dokumente FK).
- Replace hardcoded basisBetrag=100 for percent rules; basis is now
  configurable per rule via the new basis_euro column.

Security
- Multi-user authentication: users table, bcryptjs, express-session
  with SQLite store, login/logout/me/setup/change-password endpoints.
- Auth gate on all /api/* except /api/auth/*.
- CLI to create users: npm run create-user -- <user> <pass> [--admin].
- helmet for security headers.
- CORS restricted to ALLOWED_ORIGINS env (default same-origin).
- Rate limits: 300/min global, 20/15min on login.
- Path-traversal validation on document download/delete.
- XSS hardening in frontend: escapeHtml helper applied to all
  DB-derived innerHTML interpolations; inline onclick handlers that
  embedded user-controlled strings replaced with data-* attrs +
  addEventListener.

Architecture
- Provision calculation centralised in provisionService.js as the
  single source of truth (was duplicated and inconsistent).
- server.js cut from 2138 to ~140 lines; routes split into per-
  resource modules under routes/.
- Promise wrapper db.js for sqlite3 callbacks; async/await in routes.
- middleware/ for auth and async error handling.

Tests
- 14 unit tests for provisionService covering fallback hierarchy,
  percent calculation, tarifoptionen, hardware logic, employee
  commission. All green.

Config
- dotenv loads .env.local at startup (gitignored).
- .gitignore extended for sessions.db and .env*.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
kerimatilganandClaude Opus 4.7 committed 2026-05-14 21:43:19 +02:00
1 parent 55ec916f35
commit 4303b00b9b
23 files changed
+2427 -2575

No files matched your search

+105
View File
@@ -0,0 +1,105 @@
const express = require('express');
const fs = require('fs');
const path = require('path');
const multer = require('multer');
const db = require('../db');
const asyncHandler = require('../middleware/asyncHandler');
const router = express.Router();
const ALLOWED_FILE_TYPES = {
'application/pdf': ['.pdf'],
'image/jpeg': ['.jpg', '.jpeg'],
'image/png': ['.png'],
'application/msword': ['.doc'],
'application/vnd.openxmlformats-officedocument.wordprocessingml.document': ['.docx'],
};
function fileFilter(req, file, cb) {
const allowedExtensions = Object.values(ALLOWED_FILE_TYPES).flat();
const ext = path.extname(file.originalname).toLowerCase();
if (allowedExtensions.includes(ext) && ALLOWED_FILE_TYPES[file.mimetype]) {
cb(null, true);
} else {
cb(new Error(`Dateityp nicht erlaubt: ${ext}. Erlaubt sind: PDF, JPG, PNG, DOC, DOCX`), false);
}
}
const storage = multer.diskStorage({
destination: (req, file, cb) => cb(null, 'uploads/'),
filename: (req, file, cb) => {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
cb(null, uniqueSuffix + path.extname(file.originalname));
},
});
const upload = multer({ storage, fileFilter, limits: { fileSize: 10 * 1024 * 1024 } });
// Upload document for a schaltung (mounted as /api/schaltungen/:id/dokumente by server.js)
router.post('/schaltungen/:id/dokumente', upload.single('document'), asyncHandler(async (req, res) => {
const schaltung_id = req.params.id;
const file = req.file;
if (!file) return res.status(400).json({ error: 'Keine Datei hochgeladen' });
const cleanup = () => {
fs.unlink(file.path, (e) => {
if (e) console.error('Cleanup error:', e.message);
});
};
const schaltung = await db.get('SELECT id FROM schaltungen WHERE id = ?', [schaltung_id]);
if (!schaltung) {
cleanup();
return res.status(404).json({ error: 'Schaltung nicht gefunden' });
}
try {
const result = await db.run(
`INSERT INTO dokumente (schaltung_id, filename, original_filename, filepath, filesize, mimetype)
VALUES (?, ?, ?, ?, ?, ?)`,
[schaltung_id, file.filename, file.originalname, file.path, file.size, file.mimetype]
);
res.json({ id: result.lastID, message: 'Dokument erfolgreich hochgeladen', filename: file.originalname });
} catch (err) {
cleanup();
throw err;
}
}));
// List documents for a schaltung
router.get('/schaltungen/:id/dokumente', asyncHandler(async (req, res) => {
const rows = await db.all('SELECT * FROM dokumente WHERE schaltung_id = ?', [req.params.id]);
res.json(rows);
}));
// Download single document
router.get('/dokumente/:id/download', asyncHandler(async (req, res) => {
const row = await db.get('SELECT * FROM dokumente WHERE id = ?', [req.params.id]);
if (!row) return res.status(404).json({ error: 'Dokument nicht gefunden' });
const filepath = req.app.locals.safeUploadPath(row.filepath);
if (!filepath) {
console.error(`Path traversal attempt or invalid path for document ${row.id}: ${row.filepath}`);
return res.status(400).json({ error: 'Ungültiger Dateipfad' });
}
res.download(filepath, row.original_filename);
}));
// Delete document
router.delete('/dokumente/:id', asyncHandler(async (req, res) => {
const row = await db.get('SELECT * FROM dokumente WHERE id = ?', [req.params.id]);
if (!row) return res.status(404).json({ error: 'Dokument nicht gefunden' });
await db.run('DELETE FROM dokumente WHERE id = ?', [req.params.id]);
const filepath = req.app.locals.safeUploadPath(row.filepath);
if (filepath) {
fs.unlink(filepath, (err) => {
if (err) console.error('Fehler beim Löschen der Datei:', err.message);
});
} else {
console.error(`Skipping file delete - invalid path: ${row.filepath}`);
}
res.json({ message: 'Dokument erfolgreich gelöscht' });
}));
module.exports = router;