games_app/backend/dist/services/dbTamperService.js

325 lines
11 KiB
JavaScript

"use strict";
/**
* Processes PostgreSQL trigger-captured unauthorized database changes.
* Raises security alerts, emails, and in-app notifications.
*/
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.processDbTamperEvents = processDbTamperEvents;
exports.listDbTamperEvents = listDbTamperEvents;
exports.getTamperCheckIntervalMs = getTamperCheckIntervalMs;
exports.buildDbTamperEventsCsv = buildDbTamperEventsCsv;
const dbTamperRepository = __importStar(require("../repositories/dbTamperRepository"));
const securityService = __importStar(require("./securityService"));
const securityRealtimeService_1 = require("./securityRealtimeService");
const USER_CRITICAL_COLUMNS = new Set([
'role_id',
'password_hash',
'withdrawals_suspended',
'under_surveillance',
'is_enabled',
'is_account_non_locked',
'is_credentials_non_expired',
'totp_enabled',
'totp_secret_encrypted',
'security_reason_encrypted',
'security_suspended_at',
]);
const TABLE_BASE_SEVERITY = {
hot_wallets: 'critical',
cold_wallets: 'critical',
roles: 'critical',
ledger_entries: 'critical',
ledger_accounts: 'critical',
transactions: 'critical',
ledger_adjustments: 'high',
users: 'high',
candle_predict_config: 'high',
candle_predict_intervals: 'high',
candle_predict_multi_levels: 'high',
candle_predict_bets: 'high',
candle_predict_rounds: 'high',
test_wallet_credits: 'high',
test_wallet_settings: 'high',
share_card_settings: 'medium',
referral_program_settings: 'high',
platform_bonus_pools: 'high',
exchange_funding: 'high',
system_settings: 'medium',
withdrawal_locks: 'medium',
withdrawal_status_history: 'medium',
deposit_scanner_state: 'medium',
security_alerts: 'high',
refresh_tokens: 'medium',
user_wallets: 'high',
deposit_sweeps: 'high',
faq_entries: 'medium',
faq_categories: 'medium',
referral_commission_payouts: 'high',
games: 'medium',
};
function severityRank(s) {
return { low: 1, medium: 2, high: 3, critical: 4 }[s];
}
function maxSeverity(a, b) {
return severityRank(a) >= severityRank(b) ? a : b;
}
function resolveSeverity(tableName, operation, changedColumns) {
let severity = TABLE_BASE_SEVERITY[tableName] ?? 'medium';
if (tableName === 'users') {
if (operation === 'INSERT')
return 'critical';
if (operation === 'DELETE')
return 'critical';
if (operation === 'UPDATE' && changedColumns?.some((c) => USER_CRITICAL_COLUMNS.has(c))) {
return 'critical';
}
if (operation === 'UPDATE' && changedColumns?.includes('role_id')) {
return 'critical';
}
return 'high';
}
if (tableName === 'transactions') {
if (operation === 'DELETE')
return 'critical';
if (changedColumns?.some((c) => ['amount', 'status', 'type', 'blockchain_tx_id'].includes(c))) {
return 'critical';
}
}
if (tableName === 'ledger_accounts' && changedColumns?.some((c) => c.includes('balance'))) {
return 'critical';
}
if (tableName === 'roles' && operation !== 'SELECT') {
return 'critical';
}
if (tableName === 'security_alerts' && operation === 'DELETE') {
return 'critical';
}
if (tableName === 'user_wallets') {
if (operation === 'DELETE')
return 'critical';
if (changedColumns?.some((c) => ['address', 'derivation_index', 'user_id'].includes(c))) {
return 'critical';
}
}
if (tableName === 'deposit_sweeps') {
if (operation === 'DELETE')
return 'critical';
if (changedColumns?.some((c) => ['amount', 'status', 'blockchain_tx_id'].includes(c))) {
return 'critical';
}
}
if (tableName === 'referral_commission_payouts' && operation === 'DELETE') {
return 'critical';
}
if (operation === 'DELETE') {
severity = maxSeverity(severity, 'high');
}
return severity;
}
function alertTypeFor(tableName, operation, changedColumns) {
if (tableName === 'users' && operation === 'INSERT')
return 'unauthorized_user_created';
if (tableName === 'users' && changedColumns?.includes('role_id'))
return 'privilege_escalation';
if (tableName === 'ledger_accounts')
return 'ledger_balance_tamper';
if (tableName === 'ledger_entries')
return 'unauthorized_ledger_entry';
if (tableName === 'transactions')
return 'transaction_tamper';
if (tableName === 'hot_wallets' || tableName === 'cold_wallets' || tableName === 'user_wallets') {
return 'wallet_config_tamper';
}
if (tableName === 'deposit_sweeps')
return 'treasury_tamper';
if (tableName === 'faq_entries' || tableName === 'faq_categories')
return 'content_tamper';
if (tableName.startsWith('candle_predict'))
return 'game_config_tamper';
if (tableName === 'roles')
return 'role_tamper';
return 'direct_db_tamper';
}
function titleFor(tableName, operation) {
return `Modification directe DB: ${tableName} (${operation})`;
}
function extractUserId(event) {
const data = event.new_data ?? event.old_data;
if (!data)
return null;
const userId = data.user_id ?? data.userId;
return typeof userId === 'string' ? userId : null;
}
function formatDetails(event) {
const lines = [
`Table: ${event.table_name}`,
`Opération: ${event.operation}`,
event.row_id ? `ID: ${event.row_id}` : null,
`Source: ${event.source_hint}`,
event.changed_columns?.length ? `Colonnes: ${event.changed_columns.join(', ')}` : null,
].filter(Boolean);
if (event.old_data) {
lines.push(`Anciennes valeurs: ${JSON.stringify(event.old_data)}`);
}
if (event.new_data) {
lines.push(`Nouvelles valeurs: ${JSON.stringify(event.new_data)}`);
}
return lines.join('\n');
}
function isIgnoredTamperEvent(event) {
if (event.table_name === 'security_alerts' && event.operation === 'INSERT')
return true;
if (event.table_name === 'admin_notifications' && event.operation === 'INSERT')
return true;
return false;
}
async function processDbTamperEvents() {
const events = await dbTamperRepository.listUnprocessedEvents(100);
let processed = 0;
for (const event of events) {
if (isIgnoredTamperEvent(event)) {
await dbTamperRepository.markEventIgnored(event.id);
processed += 1;
continue;
}
const severity = resolveSeverity(event.table_name, event.operation, event.changed_columns);
const alertType = alertTypeFor(event.table_name, event.operation, event.changed_columns);
const userId = extractUserId(event);
const details = formatDetails(event);
const alert = await securityService.raiseAlert({
userId,
severity,
alertType,
title: titleFor(event.table_name, event.operation),
details,
metadata: {
tamperEventId: event.id,
tableName: event.table_name,
operation: event.operation,
rowId: event.row_id,
changedColumns: event.changed_columns,
sourceHint: event.source_hint,
oldData: event.old_data,
newData: event.new_data,
},
suspendUser: severity === 'critical' && Boolean(userId),
});
await dbTamperRepository.markEventProcessed(event.id, alert.id);
void (0, securityRealtimeService_1.publishSecurityAdminEvent)({
type: 'security.tamper.detected',
eventId: event.id,
tableName: event.table_name,
severity,
});
processed += 1;
}
return processed;
}
async function listDbTamperEvents(opts) {
const result = await dbTamperRepository.listRecentEvents(opts);
return {
items: result.items.map((e) => ({
id: e.id,
tableName: e.table_name,
operation: e.operation,
rowId: e.row_id,
oldData: e.old_data,
newData: e.new_data,
changedColumns: e.changed_columns,
sourceHint: e.source_hint,
severity: e.severity,
processedAt: e.processed_at,
securityAlertId: e.security_alert_id,
createdAt: e.created_at,
})),
total: result.total,
};
}
function getTamperCheckIntervalMs() {
const fromEnv = parseInt(process.env.SECURITY_TAMPER_CHECK_INTERVAL_MS ?? '60000', 10);
return Number.isFinite(fromEnv) && fromEnv > 0 ? fromEnv : 60000;
}
function csvCell(value) {
if (value === null || value === undefined)
return '';
const text = typeof value === 'string'
? value
: value instanceof Date
? value.toISOString()
: JSON.stringify(value);
if (/[",\n\r]/.test(text)) {
return `"${text.replace(/"/g, '""')}"`;
}
return text;
}
async function buildDbTamperEventsCsv(opts) {
const rows = await dbTamperRepository.listEventsForExport(opts);
const header = [
'id',
'created_at',
'table_name',
'operation',
'row_id',
'severity',
'source_hint',
'changed_columns',
'processed_at',
'security_alert_id',
'old_data',
'new_data',
];
const lines = [header.join(',')];
for (const row of rows) {
lines.push([
row.id,
row.created_at,
row.table_name,
row.operation,
row.row_id,
row.severity,
row.source_hint,
row.changed_columns,
row.processed_at,
row.security_alert_id,
row.old_data,
row.new_data,
]
.map(csvCell)
.join(','));
}
return lines.join('\n');
}
//# sourceMappingURL=dbTamperService.js.map