# All files / src/services securityService.ts

0% Statements 0/104
0% Branches 0/65
0% Functions 0/17
0% Lines 0/91

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288

     import { apiClient } from './api';
    import { extractErrorMessage } from '@/lib/error-message';
    import type {
      SecurityStatsResponse,
      SecurityIncidentsResponse,
      SecurityBansResponse,
      SecurityFilters,
      CreateSecurityBanRequest,
      SecurityBan,
      SecurityIncident,
      UnbanUserRequest,
      UserBanStatus} from '../types/security';

    interface SecurityIncidentDetails {
      description?: string;
      severity?: 'low' | 'medium' | 'high' | 'critical';
      metadata?: Record<string, unknown>;
      timestamp?: string;
      location?: string;
    }

    export class SecurityService {
      private static readonly BASE_URL = '/api/admin/security';

      /**
       * Get security statistics
       */
      static async getSecurityStats(): Promise<SecurityStatsResponse> {
        const response = await apiClient.get<SecurityStatsResponse>(`${this.BASE_URL}/stats`);
        if (response.success) {
          return response.data;
        }
        throw new Error(extractErrorMessage(response.error, 'Failed to fetch security stats'));
      }

      /**
       * Get security incidents with filters
       */
      static async getSecurityIncidents(filters?: SecurityFilters): Promise<SecurityIncidentsResponse> {
        const params = new URLSearchParams();

        if (filters?.incident_type) params.append('incident_type', filters.incident_type);
        if (filters?.username) params.append('username', filters.username);
        if (filters?.start_date) params.append('start_date', filters.start_date);
        if (filters?.end_date) params.append('end_date', filters.end_date);
        if (filters?.page) params.append('page', filters.page.toString());
        if (filters?.limit) params.append('limit', filters.limit.toString());

        const queryString = params.toString();
        const url = queryString ? `${this.BASE_URL}/incidents?${queryString}` : `${this.BASE_URL}/incidents`;

        const response = await apiClient.get<SecurityIncidentsResponse>(url);
        if (response.success) {
          return response.data;
        }
        throw new Error(extractErrorMessage(response.error, 'Failed to fetch security incidents'));
      }

      /**
       * Delete a security incident
       */
      static async deleteSecurityIncident(incidentId: number): Promise<{ success: boolean; message: string }> {
        const response = await apiClient.delete<{ success: boolean; message: string }>(`${this.BASE_URL}/incidents/${incidentId}`);
        if (response.success) {
          return response.data;
        }
        throw new Error(extractErrorMessage(response.error, 'Failed to delete security incident'));
      }

      /**
       * Get security bans
       */
      static async getSecurityBans(filters?: SecurityFilters): Promise<SecurityBansResponse> {
        const params = new URLSearchParams();

        if (filters?.username) params.append('username', filters.username);
        if (filters?.page) params.append('page', filters.page.toString());
        if (filters?.limit) params.append('limit', filters.limit.toString());

        const queryString = params.toString();
        const url = queryString ? `${this.BASE_URL}/bans?${queryString}` : `${this.BASE_URL}/bans`;

        const response = await apiClient.get<SecurityBansResponse>(url);
        if (response.success) {
          return response.data;
        }
        throw new Error(extractErrorMessage(response.error, 'Failed to fetch security bans'));
      }

      /**
       * Create a manual security ban
       */
      static async createSecurityBan(request: CreateSecurityBanRequest): Promise<SecurityBan> {
        const response = await apiClient.post<SecurityBan>(`${this.BASE_URL}/bans`, request);
        if (response.success) {
          return response.data;
        }
        throw new Error(extractErrorMessage(response.error, 'Failed to create security ban'));
      }

      /**
       * Unban a user
       */
      static async unbanUser(username: string, reason: string): Promise<{ success: boolean; message: string }> {
        const request: UnbanUserRequest = { reason };
        const response = await apiClient.post<{ success: boolean; message: string }>(`${this.BASE_URL}/users/${encodeURIComponent(username)}/unban`, request);
        if (response.success) {
          return response.data;
        }
        throw new Error(extractErrorMessage(response.error, 'Failed to unban user'));
      }

      /**
       * Check a user's ban status
       */
      static async checkUserBanStatus(username: string): Promise<UserBanStatus> {
        const response = await apiClient.get<UserBanStatus>(`${this.BASE_URL}/users/${encodeURIComponent(username)}/ban-status`);
        if (response.success) {
          return response.data;
        }
        throw new Error(extractErrorMessage(response.error, 'Failed to check user ban status'));
      }

      /**
       * Clean up expired bans
       */
      static async cleanupExpiredBans(): Promise<{ success: boolean; cleaned_bans: number; message: string }> {
        const response = await apiClient.post<{ success: boolean; cleaned_bans: number; message: string }>(`${this.BASE_URL}/bans/cleanup`, {});
        if (response.success) {
          return response.data;
        }
        throw new Error(extractErrorMessage(response.error, 'Failed to cleanup expired bans'));
      }

      /**
       * Create a manual security incident
       */
      static async createSecurityIncident(request: {
        username: string;
        incident_type: string;
        ip_address?: string;
        user_agent?: string;
        device_id?: string;
        details?: SecurityIncidentDetails;
      }): Promise<SecurityIncident> {
        const response = await apiClient.post<SecurityIncident>(`${this.BASE_URL}/incidents`, request);
        if (response.success) {
          return response.data;
        }
        throw new Error(extractErrorMessage(response.error, 'Failed to create security incident'));
      }

      /**
       * Format date for display
       */
      static formatDate(dateString: string): string {
        return new Date(dateString).toLocaleString('en-US', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'});
      }

      /**
       * Calculate remaining ban time
       */
      static calculateTimeRemaining(expiresAt?: string): string {
        if (!expiresAt) return 'Permanent';

        const now = new Date();
        const expires = new Date(expiresAt);
        const diff = expires.getTime() - now.getTime();

        if (diff <= 0) return 'Expired';

        const days = Math.floor(diff / (1000 * 60 * 60 * 24));
        const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));

        if (days > 0) return `${days}d ${hours}h ${minutes}m`;
        if (hours > 0) return `${hours}h ${minutes}m`;
        return `${minutes}m`;
      }

      /**
       * Get incident severity color
       */
      static getIncidentSeverityColor(incidentType: string): string {
        switch (incidentType) {
          case 'BRUTE_FORCE':
            return 'bg-orange-100 text-orange-800';
          case 'SUSPICIOUS_ACTIVITY':
            return 'bg-yellow-100 text-yellow-800';
          case 'MULTIPLE_DEVICES':
            return 'bg-blue-100 text-blue-800';
          case 'TOKEN_MANIPULATION':
            return 'bg-purple-100 text-purple-800';
          default:
            return 'bg-gray-100 text-gray-800';
        }
      }

      /**
       * Get ban severity color
       */
      static getBanSeverityColor(banLevel: number): string {
        switch (banLevel) {
          case 1:
            return 'bg-yellow-100 text-yellow-800';
          case 2:
            return 'bg-orange-100 text-orange-800';
          case 3:
            return 'bg-red-100 text-red-800';
          default:
            return 'bg-gray-100 text-gray-800';
        }
      }

      /**
       * Get a human-readable incident type description
       */
      static getIncidentTypeLabel(incidentType: string): string {
        const labels: Record<string, string> = {
          'BRUTE_FORCE': 'Brute Force Attack',
          'SUSPICIOUS_ACTIVITY': 'Suspicious Activity',
          'MULTIPLE_DEVICES': 'Multiple Devices',
          'TOKEN_MANIPULATION': 'Token Manipulation',
          'USER_UNBANNED': 'User Unbanned'};
        return labels[incidentType] || incidentType;
      }

      /**
       * Get ban level description
       */
      static getBanLevelLabel(banLevel: number): string {
        const labels: Record<number, string> = {
          1: 'Level 1 (20 minutes)',
          2: 'Level 2 (72 hours)',
          3: 'Level 3 (Permanent)'};
        return labels[banLevel] || `Level ${banLevel}`;
      }

      /**
       * Fetch blacklisted devices
       */
      static async getBlacklistedDevices(): Promise<{
        devices: Array<{
          user_id: number;
          username: string;
          device_id: string;
          blacklisted_at: string;
        }>;
        total: number;
        success: boolean;
      }> {
        const response = await apiClient.get<{
          devices: Array<{
            user_id: number;
            username: string;
            device_id: string;
            blacklisted_at: string;
          }>;
          total: number;
          success: boolean;
        }>(`${this.BASE_URL}/blacklisted-devices`);
        if (response.success) {
          return response.data;
        }
        throw new Error('Failed to fetch blacklisted devices');
      }

      /**
       * Remove a device from blacklist
       */
      static async removeDeviceFromBlacklist(userId: number, deviceId: string): Promise<{ success: boolean; message: string }> {
        const response = await apiClient.post<{ success: boolean; message: string }>(`${this.BASE_URL}/blacklisted-devices/remove`, {
          user_id: userId,
          device_id: deviceId
        });
        if (response.success) {
          return response.data;
        }
        throw new Error('Failed to remove device from blacklist');
      }
    }