import { Repository } from 'typeorm'; import { BaseAuthAudit, BaseUser } from '../entities'; import { IAuthAudit } from '../interfaces/entities.interface'; import { AuthAuditEventType } from '../enums/auth-audit-event-type.enum'; import { AuthAuditEventStatus } from '../entities/auth-audit.entity'; import { NAuthLogger } from '../utils/nauth-logger'; import { ClientInfoService } from './client-info.service'; import { RiskFactor } from '../enums/risk-factor.enum'; import { AdminGetUserAuthHistoryDTO, GetUserAuthHistoryResponseDTO } from '../dto/admin-get-user-auth-history.dto'; import { GetEventsByTypeDTO, GetEventsByTypeResponseDTO } from '../dto/get-events-by-type.dto'; import { GetSuspiciousActivityDTO, GetSuspiciousActivityResponseDTO } from '../dto/get-suspicious-activity.dto'; import { GetRiskAssessmentHistoryDTO, GetRiskAssessmentHistoryResponseDTO } from '../dto/get-risk-assessment-history.dto'; /** * DTO for creating audit events * * @internal * This DTO is only used by InternalAuthAuditService and should not be exposed * to consumer applications. */ export interface CreateAuthAuditEventDTO { userId?: number; sub?: string; eventType: AuthAuditEventType; eventStatus: AuthAuditEventStatus; riskFactor?: number | null; riskFactors?: RiskFactor[] | null; adaptiveMfaTriggered?: boolean | null; deviceId?: string | null; sessionId?: number | null; challengeSessionId?: number | null; authMethod?: string | null; performedBy?: string | null; reason?: string | null; description?: string | null; metadata?: Record | null; } /** * Authentication Audit Service (Base Class - Public API) * * Manages audit trail queries for authentication and security events. * Provides query capabilities for retrieving audit history. * * **Key Features:** * - Efficient queries using userId (internal integer ID) * - Pagination support for large datasets * - Query filtering by event type, status, date ranges * - User history queries (resolves sub to userId automatically) * * **Design Notes:** * - Only stores `userId` (integer) - no sub duplication * - All methods accepting sub resolve to userId before querying * - Risk tracking fields are infrastructure for future adaptive MFA (no business logic) * * **Note:** This is the public API class. Event recording is handled internally * by `InternalAuthAuditService` and is not exposed to consumer applications. * * @example * ```typescript * // Get user history (accepts sub, resolves to userId) * const history = await auditService.getUserAuthHistory({ * sub: 'user-uuid', * page: 1, * limit: 50, * startDate: new Date('2025-01-01'), * }); * ``` */ export declare class AuthAuditService { protected readonly auditRepository: Repository; protected readonly userRepository: Repository; protected readonly logger: NAuthLogger; protected readonly clientInfoService?: ClientInfoService | undefined; constructor(auditRepository: Repository, userRepository: Repository, logger: NAuthLogger, clientInfoService?: ClientInfoService | undefined); /** * Get paginated authentication history for a user * * Accepts sub (external identifier) and resolves to userId for efficient queries. * Supports filtering by event types, status, and date ranges. * * @param request - Request DTO containing sub and filtering options * @returns Response DTO with paginated audit records * @throws {NAuthException} If user not found * * @example * ```typescript * const history = await auditService.getUserAuthHistory({ * sub: 'user-uuid', * page: 1, * limit: 50, * eventTypes: [AuthAuditEventType.LOGIN_SUCCESS, AuthAuditEventType.LOGIN_FAILED], * startDate: new Date('2025-01-01'), * }); * ``` */ getUserAuthHistory(request: AdminGetUserAuthHistoryDTO): Promise; /** * Get events by type with pagination * * @param request - Request DTO containing eventType and pagination options * @returns Response DTO with paginated audit records * * @example * ```typescript * const events = await auditService.getEventsByType({ * eventType: AuthAuditEventType.SUSPICIOUS_ACTIVITY, * page: 1, * limit: 100, * }); * ``` */ getEventsByType(request: GetEventsByTypeDTO): Promise; /** * Get suspicious activity events * * Returns events with SUSPICIOUS status or SUSPICIOUS_ACTIVITY event type. * * @param request - Request DTO containing optional sub and limit * @returns Response DTO with array of suspicious audit events * * @example * ```typescript * // Get all suspicious activity * const suspicious = await auditService.getSuspiciousActivity({}); * * // Get suspicious activity for specific user * const userSuspicious = await auditService.getSuspiciousActivity({ * sub: 'user-uuid', * limit: 50, * }); * ``` */ getSuspiciousActivity(request: GetSuspiciousActivityDTO): Promise; /** * Get risk assessment history for adaptive MFA analysis * * Returns events where risk assessment was performed (ADAPTIVE_MFA_RISK_ASSESSED, * ADAPTIVE_MFA_TRIGGERED, ADAPTIVE_MFA_BYPASSED). * * @param request - Request DTO containing sub and limit * @returns Response DTO with array of risk assessment audit events * @throws {NAuthException} If user not found * * @example * ```typescript * const riskHistory = await auditService.getRiskAssessmentHistory({ * sub: 'user-uuid', * limit: 50, * }); * ``` */ getRiskAssessmentHistory(request: GetRiskAssessmentHistoryDTO): Promise; } /** * Internal Authentication Audit Service * * Extends the base AuthAuditService with event recording capabilities. * This service is only available via `@nauth-toolkit/core/internal` and should * NOT be used by consumer applications. * * **Event Recording:** * The `recordEvent()` method is internal-only and is used by nauth-toolkit * services to log authentication events. Consumer applications should use * the query methods from the base `AuthAuditService` class. * * @internal * This class is only exported from `@nauth-toolkit/core/internal` for use * by framework adapters. Consumer applications should use the base * `AuthAuditService` from `@nauth-toolkit/core`. * * @example * ```typescript * // Framework adapter usage * import { AuthAuditService } from '@nauth-toolkit/core/internal'; * * const auditService = new AuthAuditService(...); * // Can use recordEvent() here (internal only) * await auditService.recordEvent({ ... }); * ``` */ export declare class InternalAuthAuditService extends AuthAuditService { /** * Record an authentication audit event * * Creates an audit record for an authentication or security event. * Automatically extracts client information from request context when available. * This method is non-blocking - errors are logged but don't throw exceptions. * * **Automatic Client Info Extraction:** * When ClientInfoService is available, the following fields are automatically populated: * - ipAddress, ipCountry, ipCity (from request and geolocation) * - userAgent, platform, browser (from user agent parsing) * - deviceId, deviceName, deviceType (from request context) * * Note: These fields cannot be overridden via the DTO - they are always captured from the request context. * Only deviceId can be explicitly set for special cases (e.g., newly created device tokens). * Do not include ipAddress, ipCountry, ipCity, userAgent, platform, browser, deviceName, or deviceType * in the DTO - they will be automatically captured and attempts to include them will cause TypeScript errors. * * **Automatic performedBy Population:** * The `performedBy` field is automatically populated from the authenticated user's context: * - If userId is available from ClientInfoService (extracted from JWT token by interceptors/handlers), it is used as `performedBy` * - This captures who performed the action (e.g., admin performing action on another user) * - If no userId is found in client info, `performedBy` defaults to the event's `userId` (user performing action on themselves) * - Explicit `performedBy` in DTO overrides automatic population * * @internal * This method is only available in InternalAuthAuditService and should not * be exposed to consumer applications. * * @param data - Audit event data (only event-specific fields needed) * @param data.userId - Internal user ID (preferred, more efficient) * @param data.sub - External user identifier (will lookup userId if userId not provided) * @param data.eventType - Type of event * @param data.eventStatus - Event classification status * @returns Created audit record * * @example * ```typescript * // Simple recording - client info auto-populated * await auditService.recordEvent({ * userId: user.id, * eventType: AuthAuditEventType.LOGIN_SUCCESS, * eventStatus: 'SUCCESS', * authMethod: 'password', * // ipAddress, userAgent, deviceName, etc. automatically included! * }); * * // Override specific fields if needed * await auditService.recordEvent({ * userId: user.id, * eventType: AuthAuditEventType.LOGIN_SUCCESS, * eventStatus: 'SUCCESS', * // ipAddress, userAgent, etc. automatically captured from request context * }); * ``` */ recordEvent(data: CreateAuthAuditEventDTO): Promise; } //# sourceMappingURL=auth-audit.service.d.ts.map