430 lines
13 KiB
TypeScript
430 lines
13 KiB
TypeScript
/**
|
||
* Platform security: ledger integrity, alerts, withdrawal suspension, admin notifications.
|
||
*/
|
||
|
||
import { config } from '../config';
|
||
import * as securityAlertRepository from '../repositories/securityAlertRepository';
|
||
import * as ledgerRepository from '../repositories/ledgerRepository';
|
||
import * as ledgerIntegrityRepository from '../repositories/ledgerIntegrityRepository';
|
||
import * as adminNotificationRepository from '../repositories/adminNotificationRepository';
|
||
import * as userRepository from '../repositories/userRepository';
|
||
import * as auditLogRepository from '../repositories/auditLogRepository';
|
||
import { sendSecurityAlertEmail } from './emailService';
|
||
import { postSlackAlert, getSlackWebhookUrl, isReferralSlackAlertType } from './slackService';
|
||
import * as referralRepository from '../repositories/referralRepository';
|
||
import { decryptSensitive } from '../utils/crypto';
|
||
import { publishSecurityAdminEvent } from './securityRealtimeService';
|
||
import type { SecurityAlert, SecurityAlertSeverity, SecurityAlertStatus } from '../models/security.model';
|
||
|
||
/** Ledger entry types that may credit or debit user balances. */
|
||
export const 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',
|
||
]);
|
||
|
||
export class SecurityBlockedError extends Error {
|
||
constructor(message: string) {
|
||
super(message);
|
||
this.name = 'SecurityBlockedError';
|
||
}
|
||
}
|
||
|
||
export async function assertUserCanWithdraw(userId: string): Promise<void> {
|
||
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.'
|
||
);
|
||
}
|
||
}
|
||
|
||
export async function suspendUserForSecurity(
|
||
userId: string,
|
||
reason: string,
|
||
alertType: string,
|
||
severity: SecurityAlertSeverity = 'high'
|
||
): Promise<void> {
|
||
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);
|
||
}
|
||
|
||
export async function raiseAlert(input: {
|
||
userId?: string | null;
|
||
severity: SecurityAlertSeverity;
|
||
alertType: string;
|
||
title: string;
|
||
details?: string;
|
||
metadata?: Record<string, unknown>;
|
||
suspendUser?: boolean;
|
||
}): Promise<SecurityAlert> {
|
||
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;
|
||
}
|
||
|
||
export async function notifyAdminsOfAlert(alert: SecurityAlert): Promise<void> {
|
||
const emails = await securityAlertRepository.getAlertEmailsDecrypted();
|
||
const details = alert.details_encrypted ? 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 sendSecurityAlertEmail(email, payload);
|
||
} catch (e) {
|
||
console.error(`Failed to send security alert email to ${email}:`, e);
|
||
}
|
||
}
|
||
|
||
const slackChannel = isReferralSlackAlertType(alert.alert_type) ? 'referral' : 'security';
|
||
let sendSlack = Boolean(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 postSlackAlert({
|
||
channel: slackChannel,
|
||
title: alert.title,
|
||
severity: alert.severity,
|
||
alertType: alert.alert_type,
|
||
details,
|
||
userId: alert.user_id,
|
||
metadata: alert.metadata as Record<string, unknown> | undefined,
|
||
});
|
||
} catch (e) {
|
||
console.error('Failed to post security alert to Slack:', e);
|
||
}
|
||
}
|
||
|
||
void publishSecurityAdminEvent({
|
||
type: 'security.alert.raised',
|
||
alertId: alert.id,
|
||
severity: alert.severity,
|
||
title: alert.title,
|
||
alertType: alert.alert_type,
|
||
});
|
||
void publishSecurityAdminEvent({ type: 'security.notification.new' });
|
||
}
|
||
|
||
export async function resolveAlert(
|
||
alertId: string,
|
||
adminUserId: string,
|
||
status: SecurityAlertStatus,
|
||
resolutionNote?: string,
|
||
reactivateWithdrawals?: boolean
|
||
): Promise<SecurityAlert | null> {
|
||
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 publishSecurityAdminEvent({ type: 'security.alert.resolved', alertId });
|
||
void publishSecurityAdminEvent({ type: 'security.audit.new', action: 'security_alert_resolved' });
|
||
|
||
return alert;
|
||
}
|
||
|
||
export type IntegrityIssue = {
|
||
userId: string;
|
||
walletTypeId: number;
|
||
accountId: string;
|
||
available: string;
|
||
locked: string;
|
||
entriesSum: string;
|
||
issue: string;
|
||
entryId?: string;
|
||
amount?: string;
|
||
};
|
||
|
||
function snapshotTampered(
|
||
snap: ledgerIntegrityRepository.LedgerSnapshotRow,
|
||
meta: ledgerIntegrityRepository.AccountLedgerMeta
|
||
): boolean {
|
||
const balanceChanged =
|
||
snap.available_balance !== meta.available_balance ||
|
||
snap.locked_balance !== meta.locked_balance;
|
||
const entriesUnchanged =
|
||
snap.entries_sum === meta.entries_sum &&
|
||
(snap.last_entry_at?.getTime() ?? 0) === (meta.last_entry_at?.getTime() ?? 0);
|
||
return balanceChanged && entriesUnchanged;
|
||
}
|
||
|
||
export async function runLedgerIntegrityCheck(): Promise<IntegrityIssue[]> {
|
||
const accounts = await ledgerRepository.listAllAccountsForIntegrity();
|
||
const issues: IntegrityIssue[] = [];
|
||
|
||
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,
|
||
[...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 && snapshotTampered(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 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'
|
||
? '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;
|
||
}
|
||
|
||
export async function getSecuritySettings(): Promise<{ alertEmails: string[] }> {
|
||
return { alertEmails: await securityAlertRepository.getAlertEmailsDecrypted() };
|
||
}
|
||
|
||
export async function updateSecuritySettings(alertEmails: string[]): Promise<{ alertEmails: string[] }> {
|
||
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();
|
||
}
|
||
|
||
export async function listSecurityAlerts(opts: {
|
||
status?: SecurityAlertStatus;
|
||
userId?: string;
|
||
limit?: number;
|
||
offset?: number;
|
||
}) {
|
||
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 ? decryptSensitive(a.details_encrypted) : null,
|
||
metadata: a.metadata,
|
||
resolvedBy: a.resolved_by,
|
||
resolvedAt: a.resolved_at,
|
||
resolutionNote: a.resolution_note_encrypted
|
||
? decryptSensitive(a.resolution_note_encrypted)
|
||
: null,
|
||
createdAt: a.created_at,
|
||
updatedAt: a.updated_at,
|
||
})),
|
||
total: result.total,
|
||
};
|
||
}
|
||
|
||
export function getIntegrityCheckIntervalMs(): number {
|
||
return config.security.integrityCheckIntervalMs;
|
||
}
|
||
|
||
/** Dismisses false-positive alerts caused by the security_alerts INSERT detection loop (pre-fix). */
|
||
export async function dismissSpuriousTamperAlerts(adminUserId: string): Promise<number> {
|
||
const { encryptSensitive } = await import('../utils/crypto');
|
||
const { query } = await import('../db/connection');
|
||
const rows = await query<{ id: string }[]>(
|
||
`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;
|
||
}
|