362 lines
14 KiB
JavaScript
362 lines
14 KiB
JavaScript
"use strict";
|
|
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
}) : (function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
o[k2] = m[k];
|
|
}));
|
|
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
}) : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = (this && this.__importStar) || (function () {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
var ar = [];
|
|
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function (mod) {
|
|
if (mod && mod.__esModule) return mod;
|
|
var result = {};
|
|
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
})();
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.listAlerts = listAlerts;
|
|
exports.resolveAlert = resolveAlert;
|
|
exports.getSecuritySettings = getSecuritySettings;
|
|
exports.updateSecuritySettings = updateSecuritySettings;
|
|
exports.runIntegrityCheck = runIntegrityCheck;
|
|
exports.listDbTamperEvents = listDbTamperEvents;
|
|
exports.processDbTamperCheck = processDbTamperCheck;
|
|
exports.exportDbTamperEventsCsv = exportDbTamperEventsCsv;
|
|
exports.dismissSpuriousTamperAlerts = dismissSpuriousTamperAlerts;
|
|
exports.listAuditLogs = listAuditLogs;
|
|
exports.listFailedLogins = listFailedLogins;
|
|
exports.listLockedAccounts = listLockedAccounts;
|
|
exports.unlockAccount = unlockAccount;
|
|
exports.exportAuditLogsCsv = exportAuditLogsCsv;
|
|
exports.updateUserSecurity = updateUserSecurity;
|
|
const securityService = __importStar(require("../services/securityService"));
|
|
const auditLogRepository = __importStar(require("../repositories/auditLogRepository"));
|
|
const securityAudit_1 = require("../utils/securityAudit");
|
|
const auditDiff_1 = require("../utils/auditDiff");
|
|
const userRepository = __importStar(require("../repositories/userRepository"));
|
|
function auditLogFilters(req) {
|
|
return req.query;
|
|
}
|
|
async function listAlerts(req, res) {
|
|
try {
|
|
const { status, userId, limit, offset } = req.query;
|
|
const result = await securityService.listSecurityAlerts({ status, userId, limit, offset });
|
|
res.json(result);
|
|
}
|
|
catch (e) {
|
|
const msg = e instanceof Error ? e.message : 'Failed to list security alerts';
|
|
res.status(500).json({ error: msg });
|
|
}
|
|
}
|
|
async function resolveAlert(req, res) {
|
|
try {
|
|
const alertId = req.params.alertId;
|
|
const { status, resolutionNote, reactivateWithdrawals } = req.body;
|
|
if (!status) {
|
|
res.status(400).json({ error: 'status is required' });
|
|
return;
|
|
}
|
|
const alert = await securityService.resolveAlert(alertId, req.user.userId, status, resolutionNote, reactivateWithdrawals);
|
|
if (!alert) {
|
|
res.status(404).json({ error: 'Alert not found' });
|
|
return;
|
|
}
|
|
res.json({ message: 'Updated', alertId });
|
|
}
|
|
catch (e) {
|
|
const msg = e instanceof Error ? e.message : 'Failed to resolve alert';
|
|
res.status(400).json({ error: msg });
|
|
}
|
|
}
|
|
async function getSecuritySettings(_req, res) {
|
|
try {
|
|
const settings = await securityService.getSecuritySettings();
|
|
res.json(settings);
|
|
}
|
|
catch (e) {
|
|
const msg = e instanceof Error ? e.message : 'Failed to load security settings';
|
|
res.status(500).json({ error: msg });
|
|
}
|
|
}
|
|
async function updateSecuritySettings(req, res) {
|
|
try {
|
|
const { alertEmails } = req.body;
|
|
if (!Array.isArray(alertEmails)) {
|
|
res.status(400).json({ error: 'alertEmails array is required' });
|
|
return;
|
|
}
|
|
const settings = await securityService.updateSecuritySettings(alertEmails);
|
|
res.json(settings);
|
|
}
|
|
catch (e) {
|
|
const msg = e instanceof Error ? e.message : 'Failed to update security settings';
|
|
res.status(400).json({ error: msg });
|
|
}
|
|
}
|
|
async function runIntegrityCheck(_req, res) {
|
|
try {
|
|
const { runFileIntegrityCheck } = await Promise.resolve().then(() => __importStar(require('../services/fileIntegrityService')));
|
|
const [ledgerIssues, fileIssues] = await Promise.all([
|
|
securityService.runLedgerIntegrityCheck(),
|
|
runFileIntegrityCheck(),
|
|
]);
|
|
res.json({
|
|
issuesFound: ledgerIssues.length + fileIssues.length,
|
|
ledgerIssues,
|
|
fileIssues,
|
|
issues: ledgerIssues,
|
|
});
|
|
}
|
|
catch (e) {
|
|
const msg = e instanceof Error ? e.message : 'Integrity check failed';
|
|
res.status(500).json({ error: msg });
|
|
}
|
|
}
|
|
async function listDbTamperEvents(req, res) {
|
|
try {
|
|
const { listDbTamperEvents: listEvents } = await Promise.resolve().then(() => __importStar(require('../services/dbTamperService')));
|
|
const { limit, offset, tableName } = req.query;
|
|
const result = await listEvents({ limit, offset, tableName });
|
|
res.json(result);
|
|
}
|
|
catch (e) {
|
|
const msg = e instanceof Error ? e.message : 'Failed to list DB tamper events';
|
|
res.status(500).json({ error: msg });
|
|
}
|
|
}
|
|
async function processDbTamperCheck(_req, res) {
|
|
try {
|
|
const { processDbTamperEvents } = await Promise.resolve().then(() => __importStar(require('../services/dbTamperService')));
|
|
const processed = await processDbTamperEvents();
|
|
res.json({ processed });
|
|
}
|
|
catch (e) {
|
|
const msg = e instanceof Error ? e.message : 'DB tamper check failed';
|
|
res.status(500).json({ error: msg });
|
|
}
|
|
}
|
|
async function exportDbTamperEventsCsv(req, res) {
|
|
try {
|
|
const { buildDbTamperEventsCsv } = await Promise.resolve().then(() => __importStar(require('../services/dbTamperService')));
|
|
const { tableName, from, to } = req.query;
|
|
const csv = await buildDbTamperEventsCsv({ tableName, from, to });
|
|
const filename = `db-tamper-audit-${new Date().toISOString().slice(0, 10)}.csv`;
|
|
res.setHeader('Content-Type', 'text/csv; charset=utf-8');
|
|
res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
|
|
res.send(csv);
|
|
}
|
|
catch (e) {
|
|
const msg = e instanceof Error ? e.message : 'Export failed';
|
|
res.status(500).json({ error: msg });
|
|
}
|
|
}
|
|
async function dismissSpuriousTamperAlerts(req, res) {
|
|
try {
|
|
const count = await securityService.dismissSpuriousTamperAlerts(req.user.userId);
|
|
res.json({ dismissed: count, message: `${count} fausse(s) alerte(s) classée(s) comme rejetée(s).` });
|
|
}
|
|
catch (e) {
|
|
const msg = e instanceof Error ? e.message : 'Cleanup failed';
|
|
res.status(500).json({ error: msg });
|
|
}
|
|
}
|
|
async function listAuditLogs(req, res) {
|
|
try {
|
|
const filters = auditLogFilters(req);
|
|
const result = await auditLogRepository.listAuditLogs(filters);
|
|
res.json({
|
|
items: result.items.map((row) => ({
|
|
id: row.id,
|
|
userId: row.user_id,
|
|
action: row.action,
|
|
resourceType: row.resource_type,
|
|
resourceId: row.resource_id,
|
|
ipAddress: row.ip_address,
|
|
userAgent: row.user_agent,
|
|
metadata: row.metadata,
|
|
createdAt: row.created_at,
|
|
})),
|
|
total: result.total,
|
|
});
|
|
}
|
|
catch (e) {
|
|
const msg = e instanceof Error ? e.message : 'Failed to list audit logs';
|
|
const status = msg.includes('Invalid') ? 400 : 500;
|
|
res.status(status).json({ error: msg });
|
|
}
|
|
}
|
|
async function listFailedLogins(req, res) {
|
|
try {
|
|
const filters = auditLogFilters(req);
|
|
const result = await auditLogRepository.listAuditLogs({
|
|
...filters,
|
|
actions: ['login_failed'],
|
|
});
|
|
res.json({
|
|
items: result.items.map((row) => ({
|
|
id: row.id,
|
|
userId: row.user_id,
|
|
action: row.action,
|
|
ipAddress: row.ip_address,
|
|
userAgent: row.user_agent,
|
|
metadata: row.metadata,
|
|
createdAt: row.created_at,
|
|
})),
|
|
total: result.total,
|
|
});
|
|
}
|
|
catch (e) {
|
|
const msg = e instanceof Error ? e.message : 'Failed to list failed logins';
|
|
const status = msg.includes('Invalid') ? 400 : 500;
|
|
res.status(status).json({ error: msg });
|
|
}
|
|
}
|
|
async function listLockedAccounts(_req, res) {
|
|
try {
|
|
const loginLockoutService = await Promise.resolve().then(() => __importStar(require('../services/loginLockoutService')));
|
|
const items = await loginLockoutService.listTemporarilyLockedAccounts();
|
|
res.json({ items, total: items.length });
|
|
}
|
|
catch (e) {
|
|
const msg = e instanceof Error ? e.message : 'Failed to list locked accounts';
|
|
res.status(500).json({ error: msg });
|
|
}
|
|
}
|
|
async function unlockAccount(req, res) {
|
|
try {
|
|
const userId = req.params.userId;
|
|
if (!userId) {
|
|
res.status(400).json({ error: 'userId is required' });
|
|
return;
|
|
}
|
|
const loginLockoutService = await Promise.resolve().then(() => __importStar(require('../services/loginLockoutService')));
|
|
const { reason } = (req.body ?? {});
|
|
await loginLockoutService.adminUnlockAccount(userId, {
|
|
adminUserId: req.user.userId,
|
|
ipAddress: req.ip || undefined,
|
|
userAgent: req.get('user-agent') || undefined,
|
|
reason,
|
|
});
|
|
res.json({ ok: true });
|
|
}
|
|
catch (e) {
|
|
const msg = e instanceof Error ? e.message : 'Failed to unlock account';
|
|
const status = msg === 'User not found' ? 404 : 500;
|
|
res.status(status).json({ error: msg });
|
|
}
|
|
}
|
|
async function exportAuditLogsCsv(req, res) {
|
|
try {
|
|
const filters = req.query;
|
|
const csv = await auditLogRepository.exportAuditLogsCsv(filters);
|
|
const filename = `audit-log-${new Date().toISOString().slice(0, 10)}.csv`;
|
|
res.setHeader('Content-Type', 'text/csv; charset=utf-8');
|
|
res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
|
|
res.send(csv);
|
|
}
|
|
catch (e) {
|
|
const msg = e instanceof Error ? e.message : 'Export failed';
|
|
const status = msg.includes('Invalid') ? 400 : 500;
|
|
res.status(status).json({ error: msg });
|
|
}
|
|
}
|
|
async function updateUserSecurity(req, res) {
|
|
try {
|
|
const userId = req.params.userId;
|
|
const { withdrawalsSuspended, underSurveillance, reactivateWithdrawals, reason } = req.body;
|
|
const { updateSecurityFlags } = await Promise.resolve().then(() => __importStar(require('../repositories/userRepository')));
|
|
const auditCtx = (0, securityAudit_1.auditContextFromRequest)(req);
|
|
const existing = await userRepository.findById(userId);
|
|
if (!existing) {
|
|
res.status(404).json({ error: 'User not found' });
|
|
return;
|
|
}
|
|
const beforeSecurity = (0, auditDiff_1.userSecurityFlagsSnapshot)(existing);
|
|
if (reactivateWithdrawals) {
|
|
await updateSecurityFlags(userId, {
|
|
withdrawals_suspended: false,
|
|
under_surveillance: false,
|
|
clear_security_reason: true,
|
|
});
|
|
const updated = await userRepository.findById(userId);
|
|
const afterSecurity = updated ? (0, auditDiff_1.userSecurityFlagsSnapshot)(updated) : beforeSecurity;
|
|
const diff = (0, auditDiff_1.diffFields)(beforeSecurity, afterSecurity, [
|
|
'withdrawals_suspended',
|
|
'under_surveillance',
|
|
'security_suspended_at',
|
|
]);
|
|
await auditLogRepository.create({
|
|
userId: req.user.userId,
|
|
action: 'admin_user_security_updated',
|
|
resourceType: 'user',
|
|
resourceId: userId,
|
|
ipAddress: auditCtx.ipAddress ?? null,
|
|
userAgent: auditCtx.userAgent ?? null,
|
|
metadata: {
|
|
...(diff ?? { changed: [], before: beforeSecurity, after: afterSecurity }),
|
|
reactivateWithdrawals: true,
|
|
},
|
|
});
|
|
res.json({ message: 'Withdrawals reactivated' });
|
|
return;
|
|
}
|
|
const flags = {};
|
|
if (typeof withdrawalsSuspended === 'boolean')
|
|
flags.withdrawals_suspended = withdrawalsSuspended;
|
|
if (typeof underSurveillance === 'boolean')
|
|
flags.under_surveillance = underSurveillance;
|
|
if (reason)
|
|
flags.security_reason_encrypted = reason;
|
|
if (withdrawalsSuspended || underSurveillance)
|
|
flags.set_suspended_at = true;
|
|
if (Object.keys(flags).length === 0) {
|
|
res.status(400).json({ error: 'No security flags provided' });
|
|
return;
|
|
}
|
|
await updateSecurityFlags(userId, flags);
|
|
const updated = await userRepository.findById(userId);
|
|
const afterSecurity = updated ? (0, auditDiff_1.userSecurityFlagsSnapshot)(updated) : beforeSecurity;
|
|
const diff = (0, auditDiff_1.diffFields)(beforeSecurity, afterSecurity, [
|
|
'withdrawals_suspended',
|
|
'under_surveillance',
|
|
'security_suspended_at',
|
|
]);
|
|
await auditLogRepository.create({
|
|
userId: req.user.userId,
|
|
action: 'admin_user_security_updated',
|
|
resourceType: 'user',
|
|
resourceId: userId,
|
|
ipAddress: auditCtx.ipAddress ?? null,
|
|
userAgent: auditCtx.userAgent ?? null,
|
|
metadata: {
|
|
...(diff ?? { changed: [], before: beforeSecurity, after: afterSecurity }),
|
|
reasonProvided: Boolean(reason?.trim()),
|
|
},
|
|
});
|
|
res.json({ message: 'Security flags updated' });
|
|
}
|
|
catch (e) {
|
|
const msg = e instanceof Error ? e.message : 'Update failed';
|
|
res.status(400).json({ error: msg });
|
|
}
|
|
}
|
|
//# sourceMappingURL=securityController.js.map
|