games_app/backend/src/services/securityNotificationService.ts
2026-08-21 20:05:49 +02:00

210 lines
6.5 KiB
TypeScript

/**
* User-facing security email and in-app notifications.
* Failures are logged but never block the primary action.
*/
import { decrypt } from '../utils/crypto';
import * as userRepository from '../repositories/userRepository';
import * as userSecurityNotificationRepository from '../repositories/userSecurityNotificationRepository';
import * as emailService from './emailService';
type LoginContext = { ipAddress?: string; userAgent?: string; countryCode?: string | null };
async function resolveUserEmail(userId: string): Promise<string | null> {
const profile = await userRepository.getProfileForUser(userId);
if (!profile?.email_encrypted) return null;
try {
return decrypt(profile.email_encrypted);
} catch {
return null;
}
}
function logNotifyError(context: string, e: unknown): void {
const detail = e instanceof Error ? e.message : String(e);
console.error(`[security-notify] ${context}:`, detail);
}
async function recordInAppNotification(data: {
userId: string;
eventType: string;
title: string;
body?: string;
metadata?: Record<string, unknown>;
}): Promise<void> {
try {
await userSecurityNotificationRepository.createUserSecurityNotification(data);
} catch (e) {
logNotifyError('in-app notification', e);
}
}
export async function notifyNewLogin(userId: string, ctx: LoginContext): Promise<void> {
void recordInAppNotification({
userId,
eventType: 'new_login',
title: 'New sign-in detected',
body: 'A sign-in from a new device or IP address was detected on your account.',
metadata: { ...ctx },
});
const email = await resolveUserEmail(userId);
if (!email) return;
try {
await emailService.sendNewLoginEmail(email, ctx);
} catch (e) {
logNotifyError('new login email', e);
}
}
export async function notifyNewCountryLogin(userId: string, ctx: LoginContext): Promise<void> {
const country = ctx.countryCode ?? 'unknown';
void recordInAppNotification({
userId,
eventType: 'new_country_login',
title: 'Sign-in from a new country',
body: `A sign-in from country ${country} was detected on your account.`,
metadata: { ...ctx },
});
const email = await resolveUserEmail(userId);
if (!email) return;
try {
await emailService.sendNewCountryLoginEmail(email, ctx);
} catch (e) {
logNotifyError('new country login email', e);
}
}
export async function notifyPasswordChanged(userId: string, ctx: LoginContext): Promise<void> {
void recordInAppNotification({
userId,
eventType: 'password_changed',
title: 'Password changed',
body: 'Your account password was changed.',
metadata: { ...ctx },
});
const email = await resolveUserEmail(userId);
if (!email) return;
try {
await emailService.sendPasswordChangedEmail(email, ctx);
} catch (e) {
logNotifyError('password changed email', e);
}
}
export async function notifyTotpEnabled(userId: string, ctx: LoginContext): Promise<void> {
void recordInAppNotification({
userId,
eventType: 'totp_enabled',
title: 'Two-factor authentication enabled',
body: '2FA was enabled on your account.',
metadata: { ...ctx },
});
const email = await resolveUserEmail(userId);
if (!email) return;
try {
await emailService.sendTotpEnabledEmail(email, ctx);
} catch (e) {
logNotifyError('2FA enabled email', e);
}
}
export async function notifyTotpDisabled(userId: string, ctx: LoginContext): Promise<void> {
void recordInAppNotification({
userId,
eventType: 'totp_disabled',
title: 'Two-factor authentication disabled',
body: '2FA was disabled on your account.',
metadata: { ...ctx },
});
const email = await resolveUserEmail(userId);
if (!email) return;
try {
await emailService.sendTotpDisabledEmail(email, ctx);
} catch (e) {
logNotifyError('2FA disabled email', e);
}
}
/**
* Notifies the account owner after an emergency CLI break-glass 2FA reset.
*/
export async function notifyBreakGlassAdmin2faReset(
userId: string,
ctx: { operator?: string | null; hostname?: string }
): Promise<void> {
const operator = ctx.operator?.trim() || 'unknown';
const hostname = ctx.hostname?.trim() || 'unknown-host';
void recordInAppNotification({
userId,
eventType: 'break_glass_admin_2fa_reset',
title: 'Emergency Super Admin 2FA reset',
body:
'Two-factor authentication was cleared via the break-glass CLI. ' +
'If you did not request this, secure the VPS immediately and change your password.',
metadata: { operator, hostname, channel: 'cli_break_glass' },
});
const email = await resolveUserEmail(userId);
if (!email) return;
try {
await emailService.sendSecurityAlertEmail(email, {
alertId: `break-glass-${userId.slice(0, 8)}`,
severity: 'critical',
type: 'break_glass_admin_2fa_reset',
title: 'Emergency Super Admin 2FA reset',
details: [
'Your Super Admin 2FA (authenticator + recovery codes) was cleared using the server break-glass CLI.',
`Operator: ${operator}`,
`Host: ${hostname}`,
'Next: sign in with password only, re-enable 2FA in Profile, and store new recovery codes offline.',
'If you did not authorize this, change your password and audit VPS SSH access immediately.',
].join('\n'),
userId,
createdAt: new Date(),
});
} catch (e) {
logNotifyError('break-glass 2FA reset email', e);
}
}
export async function notifyRolesChanged(
userId: string,
roles: string[],
ctx: LoginContext
): Promise<void> {
void recordInAppNotification({
userId,
eventType: 'roles_changed',
title: 'Account roles updated',
body: `Your roles were updated to: ${roles.join(', ') || '(none)'}.`,
metadata: { roles, ...ctx },
});
const email = await resolveUserEmail(userId);
if (!email) return;
try {
await emailService.sendRolesChangedEmail(email, roles, ctx);
} catch (e) {
logNotifyError('roles changed email', e);
}
}
export async function notifyPermissionsChanged(
userId: string,
permissions: string[],
ctx: LoginContext
): Promise<void> {
void recordInAppNotification({
userId,
eventType: 'permissions_changed',
title: 'Account permissions updated',
body: `Your permissions were updated (${permissions.length} total).`,
metadata: { permissions, ...ctx },
});
const email = await resolveUserEmail(userId);
if (!email) return;
try {
await emailService.sendPermissionsChangedEmail(email, permissions, ctx);
} catch (e) {
logNotifyError('permissions changed email', e);
}
}