406 lines
17 KiB
JavaScript
406 lines
17 KiB
JavaScript
"use strict";
|
||
/**
|
||
* Platform security: ledger integrity, alerts, withdrawal suspension, admin 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.SecurityBlockedError = exports.AUTHORIZED_LEDGER_TYPES = void 0;
|
||
exports.assertUserCanWithdraw = assertUserCanWithdraw;
|
||
exports.suspendUserForSecurity = suspendUserForSecurity;
|
||
exports.raiseAlert = raiseAlert;
|
||
exports.notifyAdminsOfAlert = notifyAdminsOfAlert;
|
||
exports.resolveAlert = resolveAlert;
|
||
exports.isDirectBalanceTamper = isDirectBalanceTamper;
|
||
exports.runLedgerIntegrityCheck = runLedgerIntegrityCheck;
|
||
exports.getSecuritySettings = getSecuritySettings;
|
||
exports.updateSecuritySettings = updateSecuritySettings;
|
||
exports.listSecurityAlerts = listSecurityAlerts;
|
||
exports.getIntegrityCheckIntervalMs = getIntegrityCheckIntervalMs;
|
||
exports.dismissSpuriousTamperAlerts = dismissSpuriousTamperAlerts;
|
||
const config_1 = require("../config");
|
||
const securityAlertRepository = __importStar(require("../repositories/securityAlertRepository"));
|
||
const ledgerRepository = __importStar(require("../repositories/ledgerRepository"));
|
||
const ledgerIntegrityRepository = __importStar(require("../repositories/ledgerIntegrityRepository"));
|
||
const adminNotificationRepository = __importStar(require("../repositories/adminNotificationRepository"));
|
||
const userRepository = __importStar(require("../repositories/userRepository"));
|
||
const auditLogRepository = __importStar(require("../repositories/auditLogRepository"));
|
||
const emailService_1 = require("./emailService");
|
||
const slackService_1 = require("./slackService");
|
||
const referralRepository = __importStar(require("../repositories/referralRepository"));
|
||
const crypto_1 = require("../utils/crypto");
|
||
const securityRealtimeService_1 = require("./securityRealtimeService");
|
||
/** Ledger entry types that may credit or debit user balances. */
|
||
exports.AUTHORIZED_LEDGER_TYPES = new Set([
|
||
'deposit',
|
||
'withdrawal',
|
||
'transfer',
|
||
'game_stake',
|
||
'game_payout',
|
||
'game_refund',
|
||
'bonus',
|
||
'admin_adjustment',
|
||
'referral_bonus',
|
||
'referral_clawback',
|
||
'bonus_to_main',
|
||
'test_credit',
|
||
'solo_encouragement_bonus',
|
||
]);
|
||
class SecurityBlockedError extends Error {
|
||
constructor(message) {
|
||
super(message);
|
||
this.name = 'SecurityBlockedError';
|
||
}
|
||
}
|
||
exports.SecurityBlockedError = SecurityBlockedError;
|
||
async function assertUserCanWithdraw(userId) {
|
||
const user = await userRepository.findById(userId);
|
||
if (!user)
|
||
throw new Error('User not found');
|
||
if (user.withdrawals_suspended) {
|
||
throw new SecurityBlockedError('Withdrawals are suspended on your account pending security review. Contact support.');
|
||
}
|
||
if (user.under_surveillance) {
|
||
throw new SecurityBlockedError('Your account is under security surveillance. Withdrawals are temporarily disabled.');
|
||
}
|
||
}
|
||
async function suspendUserForSecurity(userId, reason, alertType, severity = 'high') {
|
||
await userRepository.updateSecurityFlags(userId, {
|
||
withdrawals_suspended: true,
|
||
under_surveillance: true,
|
||
security_reason_encrypted: reason,
|
||
set_suspended_at: true,
|
||
});
|
||
const alert = await securityAlertRepository.createAlert({
|
||
userId,
|
||
severity,
|
||
alertType,
|
||
title: `Security hold: ${alertType}`,
|
||
details: reason,
|
||
});
|
||
await notifyAdminsOfAlert(alert);
|
||
}
|
||
async function raiseAlert(input) {
|
||
const alert = await securityAlertRepository.createAlert(input);
|
||
if (input.suspendUser && input.userId) {
|
||
await userRepository.updateSecurityFlags(input.userId, {
|
||
withdrawals_suspended: true,
|
||
under_surveillance: true,
|
||
security_reason_encrypted: input.details ?? input.title,
|
||
set_suspended_at: true,
|
||
});
|
||
}
|
||
await auditLogRepository.create({
|
||
userId: input.userId ?? undefined,
|
||
action: 'security_alert_raised',
|
||
resourceType: 'security_alert',
|
||
resourceId: alert.id,
|
||
metadata: { alert_type: input.alertType, severity: input.severity },
|
||
});
|
||
await notifyAdminsOfAlert(alert);
|
||
return alert;
|
||
}
|
||
async function notifyAdminsOfAlert(alert) {
|
||
const emails = await securityAlertRepository.getAlertEmailsDecrypted();
|
||
const details = alert.details_encrypted ? (0, crypto_1.decryptSensitive)(alert.details_encrypted) : '';
|
||
const payload = {
|
||
alertId: alert.id,
|
||
severity: alert.severity,
|
||
type: alert.alert_type,
|
||
title: alert.title,
|
||
details,
|
||
userId: alert.user_id,
|
||
createdAt: alert.created_at,
|
||
};
|
||
console.warn('[security-alert]', JSON.stringify(payload));
|
||
try {
|
||
await adminNotificationRepository.createNotification({
|
||
title: alert.title,
|
||
body: [details, alert.user_id ? `User: ${alert.user_id}` : null].filter(Boolean).join('\n'),
|
||
severity: alert.severity,
|
||
alertId: alert.id,
|
||
});
|
||
}
|
||
catch (e) {
|
||
console.error('Failed to create admin notification:', e);
|
||
}
|
||
for (const email of emails) {
|
||
try {
|
||
await (0, emailService_1.sendSecurityAlertEmail)(email, payload);
|
||
}
|
||
catch (e) {
|
||
console.error(`Failed to send security alert email to ${email}:`, e);
|
||
}
|
||
}
|
||
const slackChannel = (0, slackService_1.isReferralSlackAlertType)(alert.alert_type) ? 'referral' : 'security';
|
||
let sendSlack = Boolean((0, slackService_1.getSlackWebhookUrl)(slackChannel));
|
||
if (slackChannel === 'referral') {
|
||
try {
|
||
const settings = await referralRepository.getSettings();
|
||
sendSlack = sendSlack && settings.slack_alerts_enabled;
|
||
}
|
||
catch (e) {
|
||
console.error('Failed to load referral settings for Slack routing:', e);
|
||
sendSlack = false;
|
||
}
|
||
}
|
||
if (sendSlack) {
|
||
try {
|
||
await (0, slackService_1.postSlackAlert)({
|
||
channel: slackChannel,
|
||
title: alert.title,
|
||
severity: alert.severity,
|
||
alertType: alert.alert_type,
|
||
details,
|
||
userId: alert.user_id,
|
||
metadata: alert.metadata,
|
||
});
|
||
}
|
||
catch (e) {
|
||
console.error('Failed to post security alert to Slack:', e);
|
||
}
|
||
}
|
||
void (0, securityRealtimeService_1.publishSecurityAdminEvent)({
|
||
type: 'security.alert.raised',
|
||
alertId: alert.id,
|
||
severity: alert.severity,
|
||
title: alert.title,
|
||
alertType: alert.alert_type,
|
||
});
|
||
void (0, securityRealtimeService_1.publishSecurityAdminEvent)({ type: 'security.notification.new' });
|
||
}
|
||
async function resolveAlert(alertId, adminUserId, status, resolutionNote, reactivateWithdrawals) {
|
||
const alert = await securityAlertRepository.updateAlertStatus(alertId, status, adminUserId, resolutionNote);
|
||
if (!alert)
|
||
return null;
|
||
if (reactivateWithdrawals && alert.user_id && status === 'resolved') {
|
||
await userRepository.updateSecurityFlags(alert.user_id, {
|
||
withdrawals_suspended: false,
|
||
under_surveillance: false,
|
||
clear_security_reason: true,
|
||
});
|
||
}
|
||
try {
|
||
await auditLogRepository.create({
|
||
userId: adminUserId,
|
||
action: 'security_alert_resolved',
|
||
resourceType: 'security_alert',
|
||
resourceId: alertId,
|
||
metadata: { status, reactivate_withdrawals: !!reactivateWithdrawals },
|
||
});
|
||
}
|
||
catch (e) {
|
||
console.error('Audit log for security alert resolution failed:', e);
|
||
}
|
||
void (0, securityRealtimeService_1.publishSecurityAdminEvent)({ type: 'security.alert.resolved', alertId });
|
||
void (0, securityRealtimeService_1.publishSecurityAdminEvent)({ type: 'security.audit.new', action: 'security_alert_resolved' });
|
||
return alert;
|
||
}
|
||
/**
|
||
* Detects balance inflation/deflation without a matching ledger entry change.
|
||
*
|
||
* Lock/unlock (withdrawal reserve / cancel) reshuffles available↔locked while keeping
|
||
* (available + locked) and entries_sum unchanged — that must NOT count as tamper.
|
||
* Real direct tamper changes the total while entries stay the same.
|
||
*/
|
||
function isDirectBalanceTamper(snap, meta) {
|
||
const snapTotal = BigInt(snap.available_balance) + BigInt(snap.locked_balance);
|
||
const metaTotal = BigInt(meta.available_balance) + BigInt(meta.locked_balance);
|
||
const totalChanged = snapTotal !== metaTotal;
|
||
const entriesUnchanged = snap.entries_sum === meta.entries_sum &&
|
||
(snap.last_entry_at?.getTime() ?? 0) === (meta.last_entry_at?.getTime() ?? 0);
|
||
return totalChanged && entriesUnchanged;
|
||
}
|
||
async function runLedgerIntegrityCheck() {
|
||
const accounts = await ledgerRepository.listAllAccountsForIntegrity();
|
||
const issues = [];
|
||
for (const account of accounts) {
|
||
const available = BigInt(account.available_balance);
|
||
const locked = BigInt(account.locked_balance);
|
||
const entriesSum = BigInt(account.entries_sum);
|
||
const total = available + locked;
|
||
if (total !== entriesSum) {
|
||
issues.push({
|
||
userId: account.user_id,
|
||
walletTypeId: account.wallet_type_id,
|
||
accountId: account.id,
|
||
available: account.available_balance,
|
||
locked: account.locked_balance,
|
||
entriesSum: account.entries_sum,
|
||
issue: 'balance_entries_mismatch',
|
||
});
|
||
}
|
||
const unauthorized = await ledgerRepository.listUnauthorizedEntryTypes(account.id, [...exports.AUTHORIZED_LEDGER_TYPES]);
|
||
if (unauthorized.length > 0) {
|
||
issues.push({
|
||
userId: account.user_id,
|
||
walletTypeId: account.wallet_type_id,
|
||
accountId: account.id,
|
||
available: account.available_balance,
|
||
locked: account.locked_balance,
|
||
entriesSum: account.entries_sum,
|
||
issue: `unauthorized_ledger_types:${unauthorized.join(',')}`,
|
||
});
|
||
}
|
||
const meta = await ledgerIntegrityRepository.getAccountLedgerMeta(account.id);
|
||
if (meta) {
|
||
const snap = await ledgerIntegrityRepository.getSnapshot(account.id);
|
||
if (snap && isDirectBalanceTamper(snap, meta)) {
|
||
issues.push({
|
||
userId: account.user_id,
|
||
walletTypeId: account.wallet_type_id,
|
||
accountId: account.id,
|
||
available: meta.available_balance,
|
||
locked: meta.locked_balance,
|
||
entriesSum: meta.entries_sum,
|
||
issue: 'direct_balance_tamper',
|
||
});
|
||
}
|
||
}
|
||
}
|
||
const lockMismatches = await ledgerIntegrityRepository.listLockedReservationMismatches();
|
||
for (const row of lockMismatches) {
|
||
issues.push({
|
||
userId: row.user_id,
|
||
walletTypeId: row.wallet_type_id,
|
||
accountId: row.account_id,
|
||
available: row.available_balance,
|
||
locked: row.locked_balance,
|
||
entriesSum: row.entries_sum,
|
||
issue: 'locked_reservation_mismatch',
|
||
amount: row.locks_sum,
|
||
});
|
||
}
|
||
const invalidRefs = await ledgerIntegrityRepository.listInvalidLedgerReferences();
|
||
for (const ref of invalidRefs) {
|
||
const account = accounts.find((a) => a.id === ref.account_id);
|
||
issues.push({
|
||
userId: ref.user_id,
|
||
walletTypeId: account?.wallet_type_id ?? 0,
|
||
accountId: ref.account_id,
|
||
available: account?.available_balance ?? '0',
|
||
locked: account?.locked_balance ?? '0',
|
||
entriesSum: account?.entries_sum ?? '0',
|
||
issue: `invalid_ledger_reference:${ref.issue}`,
|
||
entryId: ref.entry_id,
|
||
amount: ref.amount,
|
||
});
|
||
}
|
||
const issueAccountIds = new Set(issues.map((i) => i.accountId));
|
||
for (const account of accounts) {
|
||
if (issueAccountIds.has(account.id))
|
||
continue;
|
||
const meta = await ledgerIntegrityRepository.getAccountLedgerMeta(account.id);
|
||
if (meta)
|
||
await ledgerIntegrityRepository.upsertSnapshot(meta);
|
||
}
|
||
for (const issue of issues) {
|
||
const user = await userRepository.findById(issue.userId);
|
||
if (user?.under_surveillance)
|
||
continue;
|
||
const alertType = issue.issue.startsWith('unauthorized')
|
||
? 'unauthorized_ledger_entry'
|
||
: issue.issue.startsWith('invalid_ledger_reference')
|
||
? 'orphan_ledger_credit'
|
||
: issue.issue === 'direct_balance_tamper' || issue.issue === 'locked_reservation_mismatch'
|
||
? 'ledger_balance_tamper'
|
||
: 'ledger_balance_mismatch';
|
||
await suspendUserForSecurity(issue.userId, `Ledger integrity failure (${issue.issue}) on wallet type ${issue.walletTypeId}. ` +
|
||
`available=${issue.available}, locked=${issue.locked}, entries_sum=${issue.entriesSum}` +
|
||
(issue.entryId ? `, entry=${issue.entryId}` : ''), alertType, 'critical');
|
||
}
|
||
return issues;
|
||
}
|
||
async function getSecuritySettings() {
|
||
return { alertEmails: await securityAlertRepository.getAlertEmailsDecrypted() };
|
||
}
|
||
async function updateSecuritySettings(alertEmails) {
|
||
if (!Array.isArray(alertEmails)) {
|
||
throw new Error('alertEmails must be an array');
|
||
}
|
||
const emailRe = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||
for (const email of alertEmails) {
|
||
if (typeof email !== 'string' || !emailRe.test(email.trim())) {
|
||
throw new Error(`Invalid alert email: ${email}`);
|
||
}
|
||
}
|
||
await securityAlertRepository.setAlertEmails(alertEmails);
|
||
return getSecuritySettings();
|
||
}
|
||
async function listSecurityAlerts(opts) {
|
||
const result = await securityAlertRepository.listAlerts(opts);
|
||
return {
|
||
items: result.items.map((a) => ({
|
||
id: a.id,
|
||
userId: a.user_id,
|
||
severity: a.severity,
|
||
alertType: a.alert_type,
|
||
status: a.status,
|
||
title: a.title,
|
||
details: a.details_encrypted ? (0, crypto_1.decryptSensitive)(a.details_encrypted) : null,
|
||
metadata: a.metadata,
|
||
resolvedBy: a.resolved_by,
|
||
resolvedAt: a.resolved_at,
|
||
resolutionNote: a.resolution_note_encrypted
|
||
? (0, crypto_1.decryptSensitive)(a.resolution_note_encrypted)
|
||
: null,
|
||
createdAt: a.created_at,
|
||
updatedAt: a.updated_at,
|
||
})),
|
||
total: result.total,
|
||
};
|
||
}
|
||
function getIntegrityCheckIntervalMs() {
|
||
return config_1.config.security.integrityCheckIntervalMs;
|
||
}
|
||
/** Dismisses false-positive alerts caused by the security_alerts INSERT detection loop (pre-fix). */
|
||
async function dismissSpuriousTamperAlerts(adminUserId) {
|
||
const { encryptSensitive } = await Promise.resolve().then(() => __importStar(require('../utils/crypto')));
|
||
const { query } = await Promise.resolve().then(() => __importStar(require('../db/connection')));
|
||
const rows = await query(`UPDATE security_alerts
|
||
SET status = 'dismissed',
|
||
resolved_by = $1,
|
||
resolved_at = NOW(),
|
||
resolution_note_encrypted = $2,
|
||
updated_at = NOW()
|
||
WHERE status IN ('open', 'investigating')
|
||
AND alert_type = 'direct_db_tamper'
|
||
AND title LIKE 'Modification directe DB: security_alerts (INSERT)%'
|
||
RETURNING id`, [
|
||
adminUserId,
|
||
encryptSensitive('Fausse alerte automatique : insertion légitime d’alerte par l’application (boucle de détection corrigée).'),
|
||
]);
|
||
return rows.length;
|
||
}
|
||
//# sourceMappingURL=securityService.js.map
|