安全与权限管理是低代码平台的核心组成部分,确保平台的安全性、数据保护和合规性。本章将详细介绍如何构建一个完整的安全与权限管理系统。

15.1 安全架构概览

// 安全管理器接口
interface SecurityManager {
  // 认证管理
  authenticate(credentials: AuthCredentials): Promise<AuthResult>;
  refreshToken(refreshToken: string): Promise<TokenPair>;
  logout(token: string): Promise<void>;
  
  // 授权管理
  authorize(token: string, resource: string, action: string): Promise<boolean>;
  checkPermission(userId: string, permission: Permission): Promise<boolean>;
  
  // 用户管理
  createUser(userInfo: CreateUserRequest): Promise<User>;
  updateUser(userId: string, updates: UpdateUserRequest): Promise<User>;
  deleteUser(userId: string): Promise<void>;
  getUser(userId: string): Promise<User>;
  getUsers(query?: UserQuery): Promise<User[]>;
  
  // 角色管理
  createRole(roleInfo: CreateRoleRequest): Promise<Role>;
  updateRole(roleId: string, updates: UpdateRoleRequest): Promise<Role>;
  deleteRole(roleId: string): Promise<void>;
  getRole(roleId: string): Promise<Role>;
  getRoles(query?: RoleQuery): Promise<Role[]>;
  assignRole(userId: string, roleId: string): Promise<void>;
  revokeRole(userId: string, roleId: string): Promise<void>;
  
  // 权限管理
  createPermission(permissionInfo: CreatePermissionRequest): Promise<Permission>;
  updatePermission(permissionId: string, updates: UpdatePermissionRequest): Promise<Permission>;
  deletePermission(permissionId: string): Promise<void>;
  getPermission(permissionId: string): Promise<Permission>;
  getPermissions(query?: PermissionQuery): Promise<Permission[]>;
  
  // 安全策略
  createSecurityPolicy(policy: SecurityPolicy): Promise<SecurityPolicy>;
  updateSecurityPolicy(policyId: string, updates: Partial<SecurityPolicy>): Promise<SecurityPolicy>;
  deleteSecurityPolicy(policyId: string): Promise<void>;
  getSecurityPolicies(): Promise<SecurityPolicy[]>;
  
  // 审计日志
  logSecurityEvent(event: SecurityEvent): Promise<void>;
  getSecurityEvents(query: SecurityEventQuery): Promise<SecurityEvent[]>;
  
  // 安全检查
  validatePassword(password: string): Promise<PasswordValidationResult>;
  checkSecurityCompliance(): Promise<ComplianceReport>;
}

// 低代码安全管理器实现
class LowCodeSecurityManager implements SecurityManager {
  private authProvider: AuthenticationProvider;
  private authzProvider: AuthorizationProvider;
  private userStore: UserStore;
  private roleStore: RoleStore;
  private permissionStore: PermissionStore;
  private auditLogger: AuditLogger;
  private passwordValidator: PasswordValidator;
  private tokenManager: TokenManager;
  private encryptionService: EncryptionService;
  
  constructor(
    authProvider: AuthenticationProvider,
    authzProvider: AuthorizationProvider,
    userStore: UserStore,
    roleStore: RoleStore,
    permissionStore: PermissionStore,
    auditLogger: AuditLogger,
    passwordValidator: PasswordValidator,
    tokenManager: TokenManager,
    encryptionService: EncryptionService
  ) {
    this.authProvider = authProvider;
    this.authzProvider = authzProvider;
    this.userStore = userStore;
    this.roleStore = roleStore;
    this.permissionStore = permissionStore;
    this.auditLogger = auditLogger;
    this.passwordValidator = passwordValidator;
    this.tokenManager = tokenManager;
    this.encryptionService = encryptionService;
  }
  
  async authenticate(credentials: AuthCredentials): Promise<AuthResult> {
    try {
      // 记录认证尝试
      await this.auditLogger.log({
        type: SecurityEventType.AUTHENTICATION_ATTEMPT,
        userId: credentials.username,
        timestamp: new Date(),
        details: { method: credentials.type }
      });
      
      // 执行认证
      const authResult = await this.authProvider.authenticate(credentials);
      
      if (authResult.success) {
        // 生成令牌
        const tokens = await this.tokenManager.generateTokens(authResult.user!);
        
        // 记录成功认证
        await this.auditLogger.log({
          type: SecurityEventType.AUTHENTICATION_SUCCESS,
          userId: authResult.user!.id,
          timestamp: new Date(),
          details: { method: credentials.type }
        });
        
        return {
          success: true,
          user: authResult.user,
          tokens
        };
      } else {
        // 记录认证失败
        await this.auditLogger.log({
          type: SecurityEventType.AUTHENTICATION_FAILURE,
          userId: credentials.username,
          timestamp: new Date(),
          details: { 
            method: credentials.type,
            reason: authResult.error
          }
        });
        
        return authResult;
      }
    } catch (error) {
      await this.auditLogger.log({
        type: SecurityEventType.AUTHENTICATION_ERROR,
        userId: credentials.username,
        timestamp: new Date(),
        details: { error: error.message }
      });
      
      throw error;
    }
  }
  
  async refreshToken(refreshToken: string): Promise<TokenPair> {
    const tokens = await this.tokenManager.refreshTokens(refreshToken);
    
    await this.auditLogger.log({
      type: SecurityEventType.TOKEN_REFRESH,
      timestamp: new Date(),
      details: { tokenId: tokens.accessToken.substring(0, 10) + '...' }
    });
    
    return tokens;
  }
  
  async logout(token: string): Promise<void> {
    const payload = await this.tokenManager.validateToken(token);
    
    await this.tokenManager.revokeToken(token);
    
    await this.auditLogger.log({
      type: SecurityEventType.LOGOUT,
      userId: payload.userId,
      timestamp: new Date()
    });
  }
  
  async authorize(token: string, resource: string, action: string): Promise<boolean> {
    try {
      const payload = await this.tokenManager.validateToken(token);
      const authorized = await this.authzProvider.authorize(payload.userId, resource, action);
      
      await this.auditLogger.log({
        type: SecurityEventType.AUTHORIZATION_CHECK,
        userId: payload.userId,
        timestamp: new Date(),
        details: {
          resource,
          action,
          result: authorized
        }
      });
      
      return authorized;
    } catch (error) {
      await this.auditLogger.log({
        type: SecurityEventType.AUTHORIZATION_ERROR,
        timestamp: new Date(),
        details: {
          resource,
          action,
          error: error.message
        }
      });
      
      return false;
    }
  }
  
  async checkPermission(userId: string, permission: Permission): Promise<boolean> {
    return await this.authzProvider.hasPermission(userId, permission);
  }
  
  async createUser(userInfo: CreateUserRequest): Promise<User> {
    // 验证密码强度
    const passwordValidation = await this.validatePassword(userInfo.password);
    if (!passwordValidation.valid) {
      throw new Error(`Password validation failed: ${passwordValidation.errors.join(', ')}`);
    }
    
    // 加密密码
    const hashedPassword = await this.encryptionService.hashPassword(userInfo.password);
    
    const user = await this.userStore.create({
      ...userInfo,
      password: hashedPassword,
      createdAt: new Date(),
      updatedAt: new Date(),
      status: UserStatus.ACTIVE
    });
    
    await this.auditLogger.log({
      type: SecurityEventType.USER_CREATED,
      userId: user.id,
      timestamp: new Date(),
      details: { username: user.username }
    });
    
    return user;
  }
  
  async updateUser(userId: string, updates: UpdateUserRequest): Promise<User> {
    if (updates.password) {
      const passwordValidation = await this.validatePassword(updates.password);
      if (!passwordValidation.valid) {
        throw new Error(`Password validation failed: ${passwordValidation.errors.join(', ')}`);
      }
      
      updates.password = await this.encryptionService.hashPassword(updates.password);
    }
    
    const user = await this.userStore.update(userId, {
      ...updates,
      updatedAt: new Date()
    });
    
    await this.auditLogger.log({
      type: SecurityEventType.USER_UPDATED,
      userId,
      timestamp: new Date(),
      details: { fields: Object.keys(updates) }
    });
    
    return user;
  }
  
  async deleteUser(userId: string): Promise<void> {
    await this.userStore.delete(userId);
    
    await this.auditLogger.log({
      type: SecurityEventType.USER_DELETED,
      userId,
      timestamp: new Date()
    });
  }
  
  async getUser(userId: string): Promise<User> {
    return await this.userStore.findById(userId);
  }
  
  async getUsers(query?: UserQuery): Promise<User[]> {
    return await this.userStore.find(query);
  }
  
  async createRole(roleInfo: CreateRoleRequest): Promise<Role> {
    const role = await this.roleStore.create({
      ...roleInfo,
      createdAt: new Date(),
      updatedAt: new Date()
    });
    
    await this.auditLogger.log({
      type: SecurityEventType.ROLE_CREATED,
      timestamp: new Date(),
      details: { roleId: role.id, roleName: role.name }
    });
    
    return role;
  }
  
  async updateRole(roleId: string, updates: UpdateRoleRequest): Promise<Role> {
    const role = await this.roleStore.update(roleId, {
      ...updates,
      updatedAt: new Date()
    });
    
    await this.auditLogger.log({
      type: SecurityEventType.ROLE_UPDATED,
      timestamp: new Date(),
      details: { roleId, fields: Object.keys(updates) }
    });
    
    return role;
  }
  
  async deleteRole(roleId: string): Promise<void> {
    await this.roleStore.delete(roleId);
    
    await this.auditLogger.log({
      type: SecurityEventType.ROLE_DELETED,
      timestamp: new Date(),
      details: { roleId }
    });
  }
  
  async getRole(roleId: string): Promise<Role> {
    return await this.roleStore.findById(roleId);
  }
  
  async getRoles(query?: RoleQuery): Promise<Role[]> {
    return await this.roleStore.find(query);
  }
  
  async assignRole(userId: string, roleId: string): Promise<void> {
    await this.userStore.assignRole(userId, roleId);
    
    await this.auditLogger.log({
      type: SecurityEventType.ROLE_ASSIGNED,
      userId,
      timestamp: new Date(),
      details: { roleId }
    });
  }
  
  async revokeRole(userId: string, roleId: string): Promise<void> {
    await this.userStore.revokeRole(userId, roleId);
    
    await this.auditLogger.log({
      type: SecurityEventType.ROLE_REVOKED,
      userId,
      timestamp: new Date(),
      details: { roleId }
    });
  }
  
  async createPermission(permissionInfo: CreatePermissionRequest): Promise<Permission> {
    const permission = await this.permissionStore.create({
      ...permissionInfo,
      createdAt: new Date(),
      updatedAt: new Date()
    });
    
    await this.auditLogger.log({
      type: SecurityEventType.PERMISSION_CREATED,
      timestamp: new Date(),
      details: { permissionId: permission.id, permissionName: permission.name }
    });
    
    return permission;
  }
  
  async updatePermission(permissionId: string, updates: UpdatePermissionRequest): Promise<Permission> {
    const permission = await this.permissionStore.update(permissionId, {
      ...updates,
      updatedAt: new Date()
    });
    
    await this.auditLogger.log({
      type: SecurityEventType.PERMISSION_UPDATED,
      timestamp: new Date(),
      details: { permissionId, fields: Object.keys(updates) }
    });
    
    return permission;
  }
  
  async deletePermission(permissionId: string): Promise<void> {
    await this.permissionStore.delete(permissionId);
    
    await this.auditLogger.log({
      type: SecurityEventType.PERMISSION_DELETED,
      timestamp: new Date(),
      details: { permissionId }
    });
  }
  
  async getPermission(permissionId: string): Promise<Permission> {
    return await this.permissionStore.findById(permissionId);
  }
  
  async getPermissions(query?: PermissionQuery): Promise<Permission[]> {
    return await this.permissionStore.find(query);
  }
  
  async createSecurityPolicy(policy: SecurityPolicy): Promise<SecurityPolicy> {
    const createdPolicy = await this.createSecurityPolicy({
      ...policy,
      id: this.generateId(),
      createdAt: new Date(),
      updatedAt: new Date()
    });
    
    await this.auditLogger.log({
      type: SecurityEventType.POLICY_CREATED,
      timestamp: new Date(),
      details: { policyId: createdPolicy.id, policyName: createdPolicy.name }
    });
    
    return createdPolicy;
  }
  
  async updateSecurityPolicy(policyId: string, updates: Partial<SecurityPolicy>): Promise<SecurityPolicy> {
    // 实现更新逻辑
    throw new Error('Method not implemented.');
  }
  
  async deleteSecurityPolicy(policyId: string): Promise<void> {
    // 实现删除逻辑
    throw new Error('Method not implemented.');
  }
  
  async getSecurityPolicies(): Promise<SecurityPolicy[]> {
    // 实现获取逻辑
    throw new Error('Method not implemented.');
  }
  
  async logSecurityEvent(event: SecurityEvent): Promise<void> {
    await this.auditLogger.log(event);
  }
  
  async getSecurityEvents(query: SecurityEventQuery): Promise<SecurityEvent[]> {
    return await this.auditLogger.getEvents(query);
  }
  
  async validatePassword(password: string): Promise<PasswordValidationResult> {
    return await this.passwordValidator.validate(password);
  }
  
  async checkSecurityCompliance(): Promise<ComplianceReport> {
    // 实现合规检查逻辑
    const report: ComplianceReport = {
      timestamp: new Date(),
      overallScore: 0,
      checks: [],
      recommendations: []
    };
    
    // 检查密码策略
    const passwordPolicyCheck = await this.checkPasswordPolicy();
    report.checks.push(passwordPolicyCheck);
    
    // 检查用户权限
    const permissionCheck = await this.checkUserPermissions();
    report.checks.push(permissionCheck);
    
    // 检查审计日志
    const auditCheck = await this.checkAuditLogs();
    report.checks.push(auditCheck);
    
    // 计算总分
    report.overallScore = report.checks.reduce((sum, check) => sum + check.score, 0) / report.checks.length;
    
    return report;
  }
  
  private async checkPasswordPolicy(): Promise<ComplianceCheck> {
    // 实现密码策略检查
    return {
      name: 'Password Policy',
      description: 'Check password strength requirements',
      score: 85,
      status: ComplianceStatus.COMPLIANT,
      details: 'Password policy meets security requirements'
    };
  }
  
  private async checkUserPermissions(): Promise<ComplianceCheck> {
    // 实现用户权限检查
    return {
      name: 'User Permissions',
      description: 'Check user permission assignments',
      score: 90,
      status: ComplianceStatus.COMPLIANT,
      details: 'User permissions are properly configured'
    };
  }
  
  private async checkAuditLogs(): Promise<ComplianceCheck> {
    // 实现审计日志检查
    return {
      name: 'Audit Logs',
      description: 'Check audit log completeness',
      score: 95,
      status: ComplianceStatus.COMPLIANT,
      details: 'Audit logs are comprehensive and complete'
    };
  }
  
  private generateId(): string {
    return Math.random().toString(36).substr(2, 9);
  }
}

15.2 核心数据结构

// 认证相关
interface AuthCredentials {
  type: AuthenticationType;
  username: string;
  password?: string;
  token?: string;
  certificate?: string;
  biometric?: BiometricData;
}

interface AuthResult {
  success: boolean;
  user?: User;
  tokens?: TokenPair;
  error?: string;
  requiresMFA?: boolean;
  mfaChallenge?: MFAChallenge;
}

interface TokenPair {
  accessToken: string;
  refreshToken: string;
  expiresIn: number;
  tokenType: string;
}

interface MFAChallenge {
  type: MFAType;
  challenge: string;
  expiresAt: Date;
}

interface BiometricData {
  type: BiometricType;
  data: string;
  quality: number;
}

// 用户相关
interface User {
  id: string;
  username: string;
  email: string;
  firstName: string;
  lastName: string;
  password: string;
  roles: string[];
  permissions: string[];
  status: UserStatus;
  lastLoginAt?: Date;
  createdAt: Date;
  updatedAt: Date;
  profile: UserProfile;
  preferences: UserPreferences;
  securitySettings: UserSecuritySettings;
}

interface UserProfile {
  avatar?: string;
  phone?: string;
  department?: string;
  title?: string;
  location?: string;
  timezone: string;
  language: string;
}

interface UserPreferences {
  theme: string;
  notifications: NotificationSettings;
  privacy: PrivacySettings;
}

interface UserSecuritySettings {
  mfaEnabled: boolean;
  mfaMethods: MFAMethod[];
  passwordExpiresAt?: Date;
  accountLockoutEnabled: boolean;
  sessionTimeout: number;
}

interface NotificationSettings {
  email: boolean;
  push: boolean;
  sms: boolean;
  inApp: boolean;
}

interface PrivacySettings {
  profileVisibility: VisibilityLevel;
  activityTracking: boolean;
  dataSharing: boolean;
}

interface MFAMethod {
  type: MFAType;
  enabled: boolean;
  verified: boolean;
  secret?: string;
  backupCodes?: string[];
}

// 角色相关
interface Role {
  id: string;
  name: string;
  description: string;
  permissions: string[];
  inherits: string[];
  metadata: RoleMetadata;
  createdAt: Date;
  updatedAt: Date;
}

interface RoleMetadata {
  category: string;
  level: number;
  scope: RoleScope;
  temporary: boolean;
  expiresAt?: Date;
}

// 权限相关
interface Permission {
  id: string;
  name: string;
  description: string;
  resource: string;
  action: string;
  conditions?: PermissionCondition[];
  metadata: PermissionMetadata;
  createdAt: Date;
  updatedAt: Date;
}

interface PermissionCondition {
  type: ConditionType;
  field: string;
  operator: ConditionOperator;
  value: any;
}

interface PermissionMetadata {
  category: string;
  severity: PermissionSeverity;
  auditable: boolean;
  delegatable: boolean;
}

// 安全策略
interface SecurityPolicy {
  id: string;
  name: string;
  description: string;
  type: PolicyType;
  rules: PolicyRule[];
  enabled: boolean;
  priority: number;
  createdAt: Date;
  updatedAt: Date;
}

interface PolicyRule {
  id: string;
  condition: string;
  action: PolicyAction;
  parameters: Record<string, any>;
}

// 安全事件
interface SecurityEvent {
  id?: string;
  type: SecurityEventType;
  userId?: string;
  sessionId?: string;
  ipAddress?: string;
  userAgent?: string;
  timestamp: Date;
  severity: EventSeverity;
  details: Record<string, any>;
  resolved?: boolean;
  resolvedAt?: Date;
  resolvedBy?: string;
}

// 审计日志
interface AuditLog {
  id: string;
  eventType: SecurityEventType;
  userId?: string;
  resource?: string;
  action?: string;
  timestamp: Date;
  ipAddress?: string;
  userAgent?: string;
  details: Record<string, any>;
  result: AuditResult;
}

// 合规报告
interface ComplianceReport {
  timestamp: Date;
  overallScore: number;
  checks: ComplianceCheck[];
  recommendations: ComplianceRecommendation[];
}

interface ComplianceCheck {
  name: string;
  description: string;
  score: number;
  status: ComplianceStatus;
  details: string;
}

interface ComplianceRecommendation {
  priority: RecommendationPriority;
  title: string;
  description: string;
  action: string;
}

// 密码验证
interface PasswordValidationResult {
  valid: boolean;
  score: number;
  errors: string[];
  warnings: string[];
  suggestions: string[];
}

// 查询接口
interface UserQuery {
  username?: string;
  email?: string;
  status?: UserStatus;
  role?: string;
  department?: string;
  createdAfter?: Date;
  createdBefore?: Date;
  lastLoginAfter?: Date;
  lastLoginBefore?: Date;
  limit?: number;
  offset?: number;
  sortBy?: string;
  sortOrder?: SortOrder;
}

interface RoleQuery {
  name?: string;
  category?: string;
  level?: number;
  scope?: RoleScope;
  limit?: number;
  offset?: number;
  sortBy?: string;
  sortOrder?: SortOrder;
}

interface PermissionQuery {
  name?: string;
  resource?: string;
  action?: string;
  category?: string;
  severity?: PermissionSeverity;
  limit?: number;
  offset?: number;
  sortBy?: string;
  sortOrder?: SortOrder;
}

interface SecurityEventQuery {
  type?: SecurityEventType;
  userId?: string;
  severity?: EventSeverity;
  startTime?: Date;
  endTime?: Date;
  resolved?: boolean;
  limit?: number;
  offset?: number;
  sortBy?: string;
  sortOrder?: SortOrder;
}

// 请求接口
interface CreateUserRequest {
  username: string;
  email: string;
  firstName: string;
  lastName: string;
  password: string;
  roles?: string[];
  profile?: Partial<UserProfile>;
  preferences?: Partial<UserPreferences>;
}

interface UpdateUserRequest {
  email?: string;
  firstName?: string;
  lastName?: string;
  password?: string;
  status?: UserStatus;
  profile?: Partial<UserProfile>;
  preferences?: Partial<UserPreferences>;
  securitySettings?: Partial<UserSecuritySettings>;
}

interface CreateRoleRequest {
  name: string;
  description: string;
  permissions: string[];
  inherits?: string[];
  metadata?: Partial<RoleMetadata>;
}

interface UpdateRoleRequest {
  name?: string;
  description?: string;
  permissions?: string[];
  inherits?: string[];
  metadata?: Partial<RoleMetadata>;
}

interface CreatePermissionRequest {
  name: string;
  description: string;
  resource: string;
  action: string;
  conditions?: PermissionCondition[];
  metadata?: Partial<PermissionMetadata>;
}

interface UpdatePermissionRequest {
  name?: string;
  description?: string;
  conditions?: PermissionCondition[];
  metadata?: Partial<PermissionMetadata>;
}

// 枚举类型
enum AuthenticationType {
  PASSWORD = 'password',
  TOKEN = 'token',
  CERTIFICATE = 'certificate',
  BIOMETRIC = 'biometric',
  SSO = 'sso',
  OAUTH = 'oauth'
}

enum MFAType {
  TOTP = 'totp',
  SMS = 'sms',
  EMAIL = 'email',
  PUSH = 'push',
  HARDWARE_TOKEN = 'hardware_token',
  BIOMETRIC = 'biometric'
}

enum BiometricType {
  FINGERPRINT = 'fingerprint',
  FACE = 'face',
  VOICE = 'voice',
  IRIS = 'iris'
}

enum UserStatus {
  ACTIVE = 'active',
  INACTIVE = 'inactive',
  SUSPENDED = 'suspended',
  LOCKED = 'locked',
  PENDING = 'pending'
}

enum VisibilityLevel {
  PUBLIC = 'public',
  INTERNAL = 'internal',
  PRIVATE = 'private'
}

enum RoleScope {
  GLOBAL = 'global',
  ORGANIZATION = 'organization',
  PROJECT = 'project',
  RESOURCE = 'resource'
}

enum ConditionType {
  TIME = 'time',
  LOCATION = 'location',
  IP_ADDRESS = 'ip_address',
  DEVICE = 'device',
  ATTRIBUTE = 'attribute'
}

enum ConditionOperator {
  EQUALS = 'equals',
  NOT_EQUALS = 'not_equals',
  CONTAINS = 'contains',
  NOT_CONTAINS = 'not_contains',
  GREATER_THAN = 'greater_than',
  LESS_THAN = 'less_than',
  IN = 'in',
  NOT_IN = 'not_in'
}

enum PermissionSeverity {
  LOW = 'low',
  MEDIUM = 'medium',
  HIGH = 'high',
  CRITICAL = 'critical'
}

enum PolicyType {
  ACCESS_CONTROL = 'access_control',
  PASSWORD_POLICY = 'password_policy',
  SESSION_POLICY = 'session_policy',
  AUDIT_POLICY = 'audit_policy',
  COMPLIANCE_POLICY = 'compliance_policy'
}

enum PolicyAction {
  ALLOW = 'allow',
  DENY = 'deny',
  REQUIRE_MFA = 'require_mfa',
  LOG = 'log',
  ALERT = 'alert',
  BLOCK = 'block'
}

enum SecurityEventType {
  AUTHENTICATION_ATTEMPT = 'authentication_attempt',
  AUTHENTICATION_SUCCESS = 'authentication_success',
  AUTHENTICATION_FAILURE = 'authentication_failure',
  AUTHENTICATION_ERROR = 'authentication_error',
  AUTHORIZATION_CHECK = 'authorization_check',
  AUTHORIZATION_ERROR = 'authorization_error',
  TOKEN_REFRESH = 'token_refresh',
  LOGOUT = 'logout',
  USER_CREATED = 'user_created',
  USER_UPDATED = 'user_updated',
  USER_DELETED = 'user_deleted',
  ROLE_CREATED = 'role_created',
  ROLE_UPDATED = 'role_updated',
  ROLE_DELETED = 'role_deleted',
  ROLE_ASSIGNED = 'role_assigned',
  ROLE_REVOKED = 'role_revoked',
  PERMISSION_CREATED = 'permission_created',
  PERMISSION_UPDATED = 'permission_updated',
  PERMISSION_DELETED = 'permission_deleted',
  POLICY_CREATED = 'policy_created',
  POLICY_UPDATED = 'policy_updated',
  POLICY_DELETED = 'policy_deleted',
  SECURITY_VIOLATION = 'security_violation',
  SUSPICIOUS_ACTIVITY = 'suspicious_activity'
}

enum EventSeverity {
  INFO = 'info',
  WARNING = 'warning',
  ERROR = 'error',
  CRITICAL = 'critical'
}

enum AuditResult {
  SUCCESS = 'success',
  FAILURE = 'failure',
  ERROR = 'error'
}

enum ComplianceStatus {
  COMPLIANT = 'compliant',
  NON_COMPLIANT = 'non_compliant',
  PARTIALLY_COMPLIANT = 'partially_compliant',
  UNKNOWN = 'unknown'
}

enum RecommendationPriority {
  LOW = 'low',
  MEDIUM = 'medium',
  HIGH = 'high',
  CRITICAL = 'critical'
}

enum SortOrder {
  ASC = 'asc',
  DESC = 'desc'
}

15.3 认证提供者

// 认证提供者接口
interface AuthenticationProvider {
  authenticate(credentials: AuthCredentials): Promise<AuthResult>;
  validateToken(token: string): Promise<TokenPayload>;
  refreshToken(refreshToken: string): Promise<TokenPair>;
  revokeToken(token: string): Promise<void>;
  generateMFAChallenge(userId: string, method: MFAType): Promise<MFAChallenge>;
  verifyMFAResponse(challenge: MFAChallenge, response: string): Promise<boolean>;
}

// 多因素认证提供者
class MultiFactorAuthProvider implements AuthenticationProvider {
  private passwordAuth: PasswordAuthenticator;
  private tokenAuth: TokenAuthenticator;
  private mfaProviders: Map<MFAType, MFAProvider>;
  private userStore: UserStore;
  
  constructor(
    passwordAuth: PasswordAuthenticator,
    tokenAuth: TokenAuthenticator,
    userStore: UserStore
  ) {
    this.passwordAuth = passwordAuth;
    this.tokenAuth = tokenAuth;
    this.userStore = userStore;
    this.mfaProviders = new Map();
    
    // 初始化MFA提供者
    this.mfaProviders.set(MFAType.TOTP, new TOTPProvider());
    this.mfaProviders.set(MFAType.SMS, new SMSProvider());
    this.mfaProviders.set(MFAType.EMAIL, new EmailProvider());
  }
  
  async authenticate(credentials: AuthCredentials): Promise<AuthResult> {
    switch (credentials.type) {
      case AuthenticationType.PASSWORD:
        return await this.authenticateWithPassword(credentials);
      case AuthenticationType.TOKEN:
        return await this.authenticateWithToken(credentials);
      case AuthenticationType.SSO:
        return await this.authenticateWithSSO(credentials);
      default:
        return {
          success: false,
          error: 'Unsupported authentication type'
        };
    }
  }
  
  private async authenticateWithPassword(credentials: AuthCredentials): Promise<AuthResult> {
    const result = await this.passwordAuth.authenticate(credentials.username, credentials.password!);
    
    if (!result.success) {
      return result;
    }
    
    const user = result.user!;
    
    // 检查是否需要MFA
    if (user.securitySettings.mfaEnabled) {
      const enabledMethods = user.securitySettings.mfaMethods.filter(m => m.enabled);
      
      if (enabledMethods.length > 0) {
        const method = enabledMethods[0]; // 使用第一个启用的方法
        const challenge = await this.generateMFAChallenge(user.id, method.type);
        
        return {
          success: false,
          requiresMFA: true,
          mfaChallenge: challenge,
          user
        };
      }
    }
    
    return result;
  }
  
  private async authenticateWithToken(credentials: AuthCredentials): Promise<AuthResult> {
    try {
      const payload = await this.tokenAuth.validateToken(credentials.token!);
      const user = await this.userStore.findById(payload.userId);
      
      return {
        success: true,
        user
      };
    } catch (error) {
      return {
        success: false,
        error: 'Invalid token'
      };
    }
  }
  
  private async authenticateWithSSO(credentials: AuthCredentials): Promise<AuthResult> {
    // 实现SSO认证逻辑
    throw new Error('SSO authentication not implemented');
  }
  
  async validateToken(token: string): Promise<TokenPayload> {
    return await this.tokenAuth.validateToken(token);
  }
  
  async refreshToken(refreshToken: string): Promise<TokenPair> {
    return await this.tokenAuth.refreshToken(refreshToken);
  }
  
  async revokeToken(token: string): Promise<void> {
    await this.tokenAuth.revokeToken(token);
  }
  
  async generateMFAChallenge(userId: string, method: MFAType): Promise<MFAChallenge> {
    const provider = this.mfaProviders.get(method);
    if (!provider) {
      throw new Error(`MFA provider not found for method: ${method}`);
    }
    
    return await provider.generateChallenge(userId);
  }
  
  async verifyMFAResponse(challenge: MFAChallenge, response: string): Promise<boolean> {
    const provider = this.mfaProviders.get(challenge.type);
    if (!provider) {
      throw new Error(`MFA provider not found for method: ${challenge.type}`);
    }
    
    return await provider.verifyResponse(challenge, response);
  }
}

// 密码认证器
class PasswordAuthenticator {
  private userStore: UserStore;
  private encryptionService: EncryptionService;
  private lockoutManager: AccountLockoutManager;
  
  constructor(
    userStore: UserStore,
    encryptionService: EncryptionService,
    lockoutManager: AccountLockoutManager
  ) {
    this.userStore = userStore;
    this.encryptionService = encryptionService;
    this.lockoutManager = lockoutManager;
  }
  
  async authenticate(username: string, password: string): Promise<AuthResult> {
    // 检查账户锁定状态
    const isLocked = await this.lockoutManager.isAccountLocked(username);
    if (isLocked) {
      return {
        success: false,
        error: 'Account is locked due to too many failed attempts'
      };
    }
    
    try {
      const user = await this.userStore.findByUsername(username);
      
      if (!user) {
        await this.lockoutManager.recordFailedAttempt(username);
        return {
          success: false,
          error: 'Invalid username or password'
        };
      }
      
      if (user.status !== UserStatus.ACTIVE) {
        return {
          success: false,
          error: `Account is ${user.status}`
        };
      }
      
      const isValidPassword = await this.encryptionService.verifyPassword(password, user.password);
      
      if (!isValidPassword) {
        await this.lockoutManager.recordFailedAttempt(username);
        return {
          success: false,
          error: 'Invalid username or password'
        };
      }
      
      // 重置失败尝试计数
      await this.lockoutManager.resetFailedAttempts(username);
      
      // 更新最后登录时间
      await this.userStore.updateLastLogin(user.id);
      
      return {
        success: true,
        user
      };
    } catch (error) {
      return {
        success: false,
        error: 'Authentication failed'
      };
    }
  }
}

// 令牌认证器
class TokenAuthenticator {
  private jwtService: JWTService;
  private tokenStore: TokenStore;
  
  constructor(jwtService: JWTService, tokenStore: TokenStore) {
    this.jwtService = jwtService;
    this.tokenStore = tokenStore;
  }
  
  async validateToken(token: string): Promise<TokenPayload> {
    // 检查令牌是否被撤销
    const isRevoked = await this.tokenStore.isTokenRevoked(token);
    if (isRevoked) {
      throw new Error('Token has been revoked');
    }
    
    // 验证JWT令牌
    const payload = await this.jwtService.verify(token);
    
    return payload;
  }
  
  async refreshToken(refreshToken: string): Promise<TokenPair> {
    const payload = await this.jwtService.verify(refreshToken);
    
    if (payload.type !== 'refresh') {
      throw new Error('Invalid refresh token');
    }
    
    // 生成新的令牌对
    const accessToken = await this.jwtService.sign({
      userId: payload.userId,
      type: 'access',
      permissions: payload.permissions
    }, { expiresIn: '15m' });
    
    const newRefreshToken = await this.jwtService.sign({
      userId: payload.userId,
      type: 'refresh'
    }, { expiresIn: '7d' });
    
    // 撤销旧的刷新令牌
    await this.tokenStore.revokeToken(refreshToken);
    
    return {
      accessToken,
      refreshToken: newRefreshToken,
      expiresIn: 15 * 60, // 15分钟
      tokenType: 'Bearer'
    };
  }
  
  async revokeToken(token: string): Promise<void> {
    await this.tokenStore.revokeToken(token);
  }
}

// MFA提供者接口
interface MFAProvider {
  generateChallenge(userId: string): Promise<MFAChallenge>;
  verifyResponse(challenge: MFAChallenge, response: string): Promise<boolean>;
}

// TOTP提供者
class TOTPProvider implements MFAProvider {
  private totpService: TOTPService;
  private userStore: UserStore;
  
  constructor(totpService: TOTPService, userStore: UserStore) {
    this.totpService = totpService;
    this.userStore = userStore;
  }
  
  async generateChallenge(userId: string): Promise<MFAChallenge> {
    return {
      type: MFAType.TOTP,
      challenge: 'Enter your TOTP code',
      expiresAt: new Date(Date.now() + 5 * 60 * 1000) // 5分钟
    };
  }
  
  async verifyResponse(challenge: MFAChallenge, response: string): Promise<boolean> {
    // 实现TOTP验证逻辑
    return await this.totpService.verify(response);
  }
}

// SMS提供者
class SMSProvider implements MFAProvider {
  private smsService: SMSService;
  private codeStore: VerificationCodeStore;
  
  constructor(smsService: SMSService, codeStore: VerificationCodeStore) {
    this.smsService = smsService;
    this.codeStore = codeStore;
  }
  
  async generateChallenge(userId: string): Promise<MFAChallenge> {
    const code = this.generateVerificationCode();
    const challenge = `SMS-${userId}-${Date.now()}`;
    
    // 存储验证码
    await this.codeStore.store(challenge, code, 5 * 60); // 5分钟过期
    
    // 发送SMS
    await this.smsService.sendCode(userId, code);
    
    return {
      type: MFAType.SMS,
      challenge,
      expiresAt: new Date(Date.now() + 5 * 60 * 1000)
    };
  }
  
  async verifyResponse(challenge: MFAChallenge, response: string): Promise<boolean> {
    const storedCode = await this.codeStore.get(challenge.challenge);
    return storedCode === response;
  }
  
  private generateVerificationCode(): string {
    return Math.floor(100000 + Math.random() * 900000).toString();
  }
}

// 账户锁定管理器
class AccountLockoutManager {
  private lockoutStore: LockoutStore;
  private maxAttempts: number;
  private lockoutDuration: number;
  
  constructor(lockoutStore: LockoutStore, maxAttempts = 5, lockoutDuration = 30 * 60 * 1000) {
    this.lockoutStore = lockoutStore;
    this.maxAttempts = maxAttempts;
    this.lockoutDuration = lockoutDuration;
  }
  
  async isAccountLocked(username: string): Promise<boolean> {
    const lockout = await this.lockoutStore.getLockout(username);
    
    if (!lockout) {
      return false;
    }
    
    if (lockout.lockedUntil && lockout.lockedUntil > new Date()) {
      return true;
    }
    
    return false;
  }
  
  async recordFailedAttempt(username: string): Promise<void> {
    const lockout = await this.lockoutStore.getLockout(username) || {
      username,
      failedAttempts: 0,
      lastAttempt: new Date(),
      lockedUntil: null
    };
    
    lockout.failedAttempts++;
    lockout.lastAttempt = new Date();
    
    if (lockout.failedAttempts >= this.maxAttempts) {
      lockout.lockedUntil = new Date(Date.now() + this.lockoutDuration);
    }
    
    await this.lockoutStore.saveLockout(lockout);
  }
  
  async resetFailedAttempts(username: string): Promise<void> {
    await this.lockoutStore.deleteLockout(username);
  }
}

interface TokenPayload {
  userId: string;
  type: string;
  permissions?: string[];
  iat: number;
  exp: number;
}

interface LockoutInfo {
  username: string;
  failedAttempts: number;
  lastAttempt: Date;
  lockedUntil: Date | null;
}

15.4 授权提供者

// 授权提供者接口
interface AuthorizationProvider {
  authorize(userId: string, resource: string, action: string): Promise<boolean>;
  hasPermission(userId: string, permission: Permission): Promise<boolean>;
  getUserPermissions(userId: string): Promise<Permission[]>;
  getUserRoles(userId: string): Promise<Role[]>;
  evaluatePolicy(userId: string, context: AuthorizationContext): Promise<PolicyDecision>;
}

// 基于角色的访问控制(RBAC)提供者
class RBACAuthorizationProvider implements AuthorizationProvider {
  private userStore: UserStore;
  private roleStore: RoleStore;
  private permissionStore: PermissionStore;
  private policyEngine: PolicyEngine;
  private permissionCache: PermissionCache;
  
  constructor(
    userStore: UserStore,
    roleStore: RoleStore,
    permissionStore: PermissionStore,
    policyEngine: PolicyEngine,
    permissionCache: PermissionCache
  ) {
    this.userStore = userStore;
    this.roleStore = roleStore;
    this.permissionStore = permissionStore;
    this.policyEngine = policyEngine;
    this.permissionCache = permissionCache;
  }
  
  async authorize(userId: string, resource: string, action: string): Promise<boolean> {
    try {
      // 检查缓存
      const cacheKey = `${userId}:${resource}:${action}`;
      const cachedResult = await this.permissionCache.get(cacheKey);
      if (cachedResult !== null) {
        return cachedResult;
      }
      
      // 获取用户权限
      const permissions = await this.getUserPermissions(userId);
      
      // 检查直接权限
      const hasDirectPermission = permissions.some(p => 
        p.resource === resource && p.action === action
      );
      
      if (hasDirectPermission) {
        await this.permissionCache.set(cacheKey, true, 300); // 缓存5分钟
        return true;
      }
      
      // 检查通配符权限
      const hasWildcardPermission = permissions.some(p => 
        (p.resource === '*' || p.resource === resource) &&
        (p.action === '*' || p.action === action)
      );
      
      if (hasWildcardPermission) {
        await this.permissionCache.set(cacheKey, true, 300);
        return true;
      }
      
      // 评估条件权限
      for (const permission of permissions) {
        if (permission.resource === resource && permission.action === action) {
          if (permission.conditions && permission.conditions.length > 0) {
            const context: AuthorizationContext = {
              userId,
              resource,
              action,
              timestamp: new Date()
            };
            
            const conditionsMet = await this.evaluateConditions(permission.conditions, context);
            if (conditionsMet) {
              await this.permissionCache.set(cacheKey, true, 300);
              return true;
            }
          }
        }
      }
      
      await this.permissionCache.set(cacheKey, false, 300);
      return false;
    } catch (error) {
      console.error('Authorization error:', error);
      return false;
    }
  }
  
  async hasPermission(userId: string, permission: Permission): Promise<boolean> {
    return await this.authorize(userId, permission.resource, permission.action);
  }
  
  async getUserPermissions(userId: string): Promise<Permission[]> {
    const cacheKey = `user_permissions:${userId}`;
    const cachedPermissions = await this.permissionCache.get(cacheKey);
    if (cachedPermissions) {
      return cachedPermissions;
    }
    
    const user = await this.userStore.findById(userId);
    if (!user) {
      return [];
    }
    
    const allPermissions: Permission[] = [];
    
    // 获取直接分配的权限
    for (const permissionId of user.permissions) {
      const permission = await this.permissionStore.findById(permissionId);
      if (permission) {
        allPermissions.push(permission);
      }
    }
    
    // 获取角色权限
    const roles = await this.getUserRoles(userId);
    for (const role of roles) {
      for (const permissionId of role.permissions) {
        const permission = await this.permissionStore.findById(permissionId);
        if (permission && !allPermissions.find(p => p.id === permission.id)) {
          allPermissions.push(permission);
        }
      }
    }
    
    await this.permissionCache.set(cacheKey, allPermissions, 600); // 缓存10分钟
    return allPermissions;
  }
  
  async getUserRoles(userId: string): Promise<Role[]> {
    const user = await this.userStore.findById(userId);
    if (!user) {
      return [];
    }
    
    const roles: Role[] = [];
    
    for (const roleId of user.roles) {
      const role = await this.roleStore.findById(roleId);
      if (role) {
        roles.push(role);
        
        // 递归获取继承的角色
        const inheritedRoles = await this.getInheritedRoles(role);
        roles.push(...inheritedRoles);
      }
    }
    
    // 去重
    const uniqueRoles = roles.filter((role, index, self) => 
      index === self.findIndex(r => r.id === role.id)
    );
    
    return uniqueRoles;
  }
  
  private async getInheritedRoles(role: Role): Promise<Role[]> {
    const inheritedRoles: Role[] = [];
    
    for (const inheritedRoleId of role.inherits) {
      const inheritedRole = await this.roleStore.findById(inheritedRoleId);
      if (inheritedRole) {
        inheritedRoles.push(inheritedRole);
        
        // 递归获取继承的角色
        const nestedInheritedRoles = await this.getInheritedRoles(inheritedRole);
        inheritedRoles.push(...nestedInheritedRoles);
      }
    }
    
    return inheritedRoles;
  }
  
  async evaluatePolicy(userId: string, context: AuthorizationContext): Promise<PolicyDecision> {
    return await this.policyEngine.evaluate(userId, context);
  }
  
  private async evaluateConditions(
    conditions: PermissionCondition[],
    context: AuthorizationContext
  ): Promise<boolean> {
    for (const condition of conditions) {
      const result = await this.evaluateCondition(condition, context);
      if (!result) {
        return false;
      }
    }
    return true;
  }
  
  private async evaluateCondition(
    condition: PermissionCondition,
    context: AuthorizationContext
  ): Promise<boolean> {
    switch (condition.type) {
      case ConditionType.TIME:
        return this.evaluateTimeCondition(condition, context);
      case ConditionType.LOCATION:
        return this.evaluateLocationCondition(condition, context);
      case ConditionType.IP_ADDRESS:
        return this.evaluateIPCondition(condition, context);
      case ConditionType.DEVICE:
        return this.evaluateDeviceCondition(condition, context);
      case ConditionType.ATTRIBUTE:
        return this.evaluateAttributeCondition(condition, context);
      default:
        return false;
    }
  }
  
  private evaluateTimeCondition(
    condition: PermissionCondition,
    context: AuthorizationContext
  ): boolean {
    const currentTime = context.timestamp.getHours() * 60 + context.timestamp.getMinutes();
    const allowedTime = parseInt(condition.value);
    
    switch (condition.operator) {
      case ConditionOperator.GREATER_THAN:
        return currentTime > allowedTime;
      case ConditionOperator.LESS_THAN:
        return currentTime < allowedTime;
      default:
        return false;
    }
  }
  
  private evaluateLocationCondition(
    condition: PermissionCondition,
    context: AuthorizationContext
  ): boolean {
    // 实现位置条件评估
    return true;
  }
  
  private evaluateIPCondition(
    condition: PermissionCondition,
    context: AuthorizationContext
  ): boolean {
    // 实现IP地址条件评估
    return true;
  }
  
  private evaluateDeviceCondition(
    condition: PermissionCondition,
    context: AuthorizationContext
  ): boolean {
    // 实现设备条件评估
    return true;
  }
  
  private evaluateAttributeCondition(
    condition: PermissionCondition,
    context: AuthorizationContext
  ): boolean {
    // 实现属性条件评估
    return true;
  }
}

// 策略引擎
class PolicyEngine {
  private policyStore: PolicyStore;
  
  constructor(policyStore: PolicyStore) {
    this.policyStore = policyStore;
  }
  
  async evaluate(userId: string, context: AuthorizationContext): Promise<PolicyDecision> {
    const policies = await this.policyStore.getActivePolicies();
    
    // 按优先级排序
    policies.sort((a, b) => b.priority - a.priority);
    
    for (const policy of policies) {
      const decision = await this.evaluatePolicy(policy, userId, context);
      if (decision.decision !== PolicyDecisionType.NOT_APPLICABLE) {
        return decision;
      }
    }
    
    return {
      decision: PolicyDecisionType.DENY,
      reason: 'No applicable policy found',
      policy: null
    };
  }
  
  private async evaluatePolicy(
    policy: SecurityPolicy,
    userId: string,
    context: AuthorizationContext
  ): Promise<PolicyDecision> {
    for (const rule of policy.rules) {
      const ruleResult = await this.evaluateRule(rule, userId, context);
      if (ruleResult) {
        return {
          decision: this.mapActionToDecision(rule.action),
          reason: `Policy '${policy.name}' rule '${rule.id}' matched`,
          policy
        };
      }
    }
    
    return {
      decision: PolicyDecisionType.NOT_APPLICABLE,
      reason: 'No rules matched',
      policy
    };
  }
  
  private async evaluateRule(
    rule: PolicyRule,
    userId: string,
    context: AuthorizationContext
  ): Promise<boolean> {
    // 简化的规则评估逻辑
    // 实际实现应该支持复杂的条件表达式
    return true;
  }
  
  private mapActionToDecision(action: PolicyAction): PolicyDecisionType {
    switch (action) {
      case PolicyAction.ALLOW:
        return PolicyDecisionType.PERMIT;
      case PolicyAction.DENY:
        return PolicyDecisionType.DENY;
      case PolicyAction.REQUIRE_MFA:
        return PolicyDecisionType.REQUIRE_MFA;
      default:
        return PolicyDecisionType.DENY;
    }
  }
}

// 权限缓存
interface PermissionCache {
  get(key: string): Promise<any>;
  set(key: string, value: any, ttl: number): Promise<void>;
  delete(key: string): Promise<void>;
  clear(): Promise<void>;
}

class RedisPermissionCache implements PermissionCache {
  private redis: any; // Redis客户端
  
  constructor(redis: any) {
    this.redis = redis;
  }
  
  async get(key: string): Promise<any> {
    const value = await this.redis.get(key);
    return value ? JSON.parse(value) : null;
  }
  
  async set(key: string, value: any, ttl: number): Promise<void> {
    await this.redis.setex(key, ttl, JSON.stringify(value));
  }
  
  async delete(key: string): Promise<void> {
    await this.redis.del(key);
  }
  
  async clear(): Promise<void> {
    await this.redis.flushall();
  }
}

// 授权上下文
interface AuthorizationContext {
  userId: string;
  resource: string;
  action: string;
  timestamp: Date;
  ipAddress?: string;
  userAgent?: string;
  location?: string;
  device?: string;
  attributes?: Record<string, any>;
}

// 策略决策
interface PolicyDecision {
  decision: PolicyDecisionType;
  reason: string;
  policy: SecurityPolicy | null;
}

enum PolicyDecisionType {
  PERMIT = 'permit',
  DENY = 'deny',
  NOT_APPLICABLE = 'not_applicable',
  REQUIRE_MFA = 'require_mfa'
}

15.5 数据存储

// 用户存储接口
interface UserStore {
  create(user: Omit<User, 'id'>): Promise<User>;
  update(userId: string, updates: Partial<User>): Promise<User>;
  delete(userId: string): Promise<void>;
  findById(userId: string): Promise<User | null>;
  findByUsername(username: string): Promise<User | null>;
  findByEmail(email: string): Promise<User | null>;
  find(query?: UserQuery): Promise<User[]>;
  assignRole(userId: string, roleId: string): Promise<void>;
  revokeRole(userId: string, roleId: string): Promise<void>;
  updateLastLogin(userId: string): Promise<void>;
}

// 内存用户存储实现
class MemoryUserStore implements UserStore {
  private users: Map<string, User> = new Map();
  private usernameIndex: Map<string, string> = new Map();
  private emailIndex: Map<string, string> = new Map();
  
  async create(userData: Omit<User, 'id'>): Promise<User> {
    const user: User = {
      id: this.generateId(),
      ...userData
    };
    
    this.users.set(user.id, user);
    this.usernameIndex.set(user.username, user.id);
    this.emailIndex.set(user.email, user.id);
    
    return user;
  }
  
  async update(userId: string, updates: Partial<User>): Promise<User> {
    const user = this.users.get(userId);
    if (!user) {
      throw new Error('User not found');
    }
    
    const updatedUser = { ...user, ...updates };
    this.users.set(userId, updatedUser);
    
    // 更新索引
    if (updates.username && updates.username !== user.username) {
      this.usernameIndex.delete(user.username);
      this.usernameIndex.set(updates.username, userId);
    }
    
    if (updates.email && updates.email !== user.email) {
      this.emailIndex.delete(user.email);
      this.emailIndex.set(updates.email, userId);
    }
    
    return updatedUser;
  }
  
  async delete(userId: string): Promise<void> {
    const user = this.users.get(userId);
    if (user) {
      this.users.delete(userId);
      this.usernameIndex.delete(user.username);
      this.emailIndex.delete(user.email);
    }
  }
  
  async findById(userId: string): Promise<User | null> {
    return this.users.get(userId) || null;
  }
  
  async findByUsername(username: string): Promise<User | null> {
    const userId = this.usernameIndex.get(username);
    return userId ? this.users.get(userId) || null : null;
  }
  
  async findByEmail(email: string): Promise<User | null> {
    const userId = this.emailIndex.get(email);
    return userId ? this.users.get(userId) || null : null;
  }
  
  async find(query?: UserQuery): Promise<User[]> {
    let users = Array.from(this.users.values());
    
    if (query) {
      if (query.username) {
        users = users.filter(u => u.username.includes(query.username!));
      }
      if (query.email) {
        users = users.filter(u => u.email.includes(query.email!));
      }
      if (query.status) {
        users = users.filter(u => u.status === query.status);
      }
      if (query.role) {
        users = users.filter(u => u.roles.includes(query.role!));
      }
      if (query.department) {
        users = users.filter(u => u.profile.department === query.department);
      }
      if (query.createdAfter) {
        users = users.filter(u => u.createdAt >= query.createdAfter!);
      }
      if (query.createdBefore) {
        users = users.filter(u => u.createdAt <= query.createdBefore!);
      }
      
      // 排序
      if (query.sortBy) {
        users.sort((a, b) => {
          const aValue = this.getNestedValue(a, query.sortBy!);
          const bValue = this.getNestedValue(b, query.sortBy!);
          
          if (query.sortOrder === SortOrder.DESC) {
            return bValue > aValue ? 1 : -1;
          } else {
            return aValue > bValue ? 1 : -1;
          }
        });
      }
      
      // 分页
      if (query.offset) {
        users = users.slice(query.offset);
      }
      if (query.limit) {
        users = users.slice(0, query.limit);
      }
    }
    
    return users;
  }
  
  async assignRole(userId: string, roleId: string): Promise<void> {
    const user = this.users.get(userId);
    if (!user) {
      throw new Error('User not found');
    }
    
    if (!user.roles.includes(roleId)) {
      user.roles.push(roleId);
      this.users.set(userId, user);
    }
  }
  
  async revokeRole(userId: string, roleId: string): Promise<void> {
    const user = this.users.get(userId);
    if (!user) {
      throw new Error('User not found');
    }
    
    user.roles = user.roles.filter(r => r !== roleId);
    this.users.set(userId, user);
  }
  
  async updateLastLogin(userId: string): Promise<void> {
    const user = this.users.get(userId);
    if (user) {
      user.lastLoginAt = new Date();
      this.users.set(userId, user);
    }
  }
  
  private getNestedValue(obj: any, path: string): any {
    return path.split('.').reduce((current, key) => current?.[key], obj);
  }
  
  private generateId(): string {
    return Math.random().toString(36).substr(2, 9);
  }
}

// 角色存储接口
interface RoleStore {
  create(role: Omit<Role, 'id'>): Promise<Role>;
  update(roleId: string, updates: Partial<Role>): Promise<Role>;
  delete(roleId: string): Promise<void>;
  findById(roleId: string): Promise<Role | null>;
  find(query?: RoleQuery): Promise<Role[]>;
}

// 内存角色存储实现
class MemoryRoleStore implements RoleStore {
  private roles: Map<string, Role> = new Map();
  
  async create(roleData: Omit<Role, 'id'>): Promise<Role> {
    const role: Role = {
      id: this.generateId(),
      ...roleData
    };
    
    this.roles.set(role.id, role);
    return role;
  }
  
  async update(roleId: string, updates: Partial<Role>): Promise<Role> {
    const role = this.roles.get(roleId);
    if (!role) {
      throw new Error('Role not found');
    }
    
    const updatedRole = { ...role, ...updates };
    this.roles.set(roleId, updatedRole);
    return updatedRole;
  }
  
  async delete(roleId: string): Promise<void> {
    this.roles.delete(roleId);
  }
  
  async findById(roleId: string): Promise<Role | null> {
    return this.roles.get(roleId) || null;
  }
  
  async find(query?: RoleQuery): Promise<Role[]> {
    let roles = Array.from(this.roles.values());
    
    if (query) {
      if (query.name) {
        roles = roles.filter(r => r.name.includes(query.name!));
      }
      if (query.category) {
        roles = roles.filter(r => r.metadata.category === query.category);
      }
      if (query.level !== undefined) {
        roles = roles.filter(r => r.metadata.level === query.level);
      }
      if (query.scope) {
        roles = roles.filter(r => r.metadata.scope === query.scope);
      }
      
      // 排序和分页逻辑类似用户存储
    }
    
    return roles;
  }
  
  private generateId(): string {
    return Math.random().toString(36).substr(2, 9);
  }
}

// 权限存储接口
interface PermissionStore {
  create(permission: Omit<Permission, 'id'>): Promise<Permission>;
  update(permissionId: string, updates: Partial<Permission>): Promise<Permission>;
  delete(permissionId: string): Promise<void>;
  findById(permissionId: string): Promise<Permission | null>;
  find(query?: PermissionQuery): Promise<Permission[]>;
}

// 内存权限存储实现
class MemoryPermissionStore implements PermissionStore {
  private permissions: Map<string, Permission> = new Map();
  
  async create(permissionData: Omit<Permission, 'id'>): Promise<Permission> {
    const permission: Permission = {
      id: this.generateId(),
      ...permissionData
    };
    
    this.permissions.set(permission.id, permission);
    return permission;
  }
  
  async update(permissionId: string, updates: Partial<Permission>): Promise<Permission> {
    const permission = this.permissions.get(permissionId);
    if (!permission) {
      throw new Error('Permission not found');
    }
    
    const updatedPermission = { ...permission, ...updates };
    this.permissions.set(permissionId, updatedPermission);
    return updatedPermission;
  }
  
  async delete(permissionId: string): Promise<void> {
    this.permissions.delete(permissionId);
  }
  
  async findById(permissionId: string): Promise<Permission | null> {
    return this.permissions.get(permissionId) || null;
  }
  
  async find(query?: PermissionQuery): Promise<Permission[]> {
    let permissions = Array.from(this.permissions.values());
    
    if (query) {
      if (query.name) {
        permissions = permissions.filter(p => p.name.includes(query.name!));
      }
      if (query.resource) {
        permissions = permissions.filter(p => p.resource === query.resource);
      }
      if (query.action) {
        permissions = permissions.filter(p => p.action === query.action);
      }
      if (query.category) {
        permissions = permissions.filter(p => p.metadata.category === query.category);
      }
      if (query.severity) {
        permissions = permissions.filter(p => p.metadata.severity === query.severity);
      }
      
      // 排序和分页逻辑类似用户存储
    }
    
    return permissions;
  }
  
  private generateId(): string {
    return Math.random().toString(36).substr(2, 9);
  }
}

// 策略存储接口
interface PolicyStore {
  create(policy: SecurityPolicy): Promise<SecurityPolicy>;
  update(policyId: string, updates: Partial<SecurityPolicy>): Promise<SecurityPolicy>;
  delete(policyId: string): Promise<void>;
  findById(policyId: string): Promise<SecurityPolicy | null>;
  getActivePolicies(): Promise<SecurityPolicy[]>;
}

// 令牌存储接口
interface TokenStore {
  revokeToken(token: string): Promise<void>;
  isTokenRevoked(token: string): Promise<boolean>;
  cleanupExpiredTokens(): Promise<void>;
}

// 锁定存储接口
interface LockoutStore {
  getLockout(username: string): Promise<LockoutInfo | null>;
  saveLockout(lockout: LockoutInfo): Promise<void>;
  deleteLockout(username: string): Promise<void>;
}

// 验证码存储接口
interface VerificationCodeStore {
  store(key: string, code: string, ttl: number): Promise<void>;
  get(key: string): Promise<string | null>;
  delete(key: string): Promise<void>;
}

15.6 加密服务

// 加密服务接口
interface EncryptionService {
  hashPassword(password: string): Promise<string>;
  verifyPassword(password: string, hash: string): Promise<boolean>;
  encrypt(data: string, key?: string): Promise<string>;
  decrypt(encryptedData: string, key?: string): Promise<string>;
  generateSalt(): string;
  generateKey(): string;
  generateHash(data: string): string;
  verifyHash(data: string, hash: string): boolean;
}

// 加密服务实现
class CryptoEncryptionService implements EncryptionService {
  private readonly algorithm = 'aes-256-gcm';
  private readonly keyLength = 32;
  private readonly ivLength = 16;
  private readonly saltLength = 16;
  private readonly tagLength = 16;
  private readonly iterations = 100000;
  
  async hashPassword(password: string): Promise<string> {
    const salt = this.generateSalt();
    const hash = await this.pbkdf2(password, salt, this.iterations, 64);
    return `${salt}:${hash}`;
  }
  
  async verifyPassword(password: string, hash: string): Promise<boolean> {
    const [salt, storedHash] = hash.split(':');
    const computedHash = await this.pbkdf2(password, salt, this.iterations, 64);
    return this.constantTimeCompare(computedHash, storedHash);
  }
  
  async encrypt(data: string, key?: string): Promise<string> {
    const encryptionKey = key ? Buffer.from(key, 'hex') : this.generateKeyBuffer();
    const iv = this.generateIV();
    
    const cipher = require('crypto').createCipher(this.algorithm, encryptionKey);
    cipher.setAAD(Buffer.from('lowcode-platform'));
    
    let encrypted = cipher.update(data, 'utf8', 'hex');
    encrypted += cipher.final('hex');
    
    const tag = cipher.getAuthTag();
    
    return `${iv.toString('hex')}:${encrypted}:${tag.toString('hex')}`;
  }
  
  async decrypt(encryptedData: string, key?: string): Promise<string> {
    const [ivHex, encrypted, tagHex] = encryptedData.split(':');
    const encryptionKey = key ? Buffer.from(key, 'hex') : this.generateKeyBuffer();
    const iv = Buffer.from(ivHex, 'hex');
    const tag = Buffer.from(tagHex, 'hex');
    
    const decipher = require('crypto').createDecipher(this.algorithm, encryptionKey);
    decipher.setAAD(Buffer.from('lowcode-platform'));
    decipher.setAuthTag(tag);
    
    let decrypted = decipher.update(encrypted, 'hex', 'utf8');
    decrypted += decipher.final('utf8');
    
    return decrypted;
  }
  
  generateSalt(): string {
    return require('crypto').randomBytes(this.saltLength).toString('hex');
  }
  
  generateKey(): string {
    return require('crypto').randomBytes(this.keyLength).toString('hex');
  }
  
  generateHash(data: string): string {
    return require('crypto').createHash('sha256').update(data).digest('hex');
  }
  
  verifyHash(data: string, hash: string): boolean {
    const computedHash = this.generateHash(data);
    return this.constantTimeCompare(computedHash, hash);
  }
  
  private generateKeyBuffer(): Buffer {
    return require('crypto').randomBytes(this.keyLength);
  }
  
  private generateIV(): Buffer {
    return require('crypto').randomBytes(this.ivLength);
  }
  
  private async pbkdf2(password: string, salt: string, iterations: number, keyLength: number): Promise<string> {
    return new Promise((resolve, reject) => {
      require('crypto').pbkdf2(password, salt, iterations, keyLength, 'sha512', (err: any, derivedKey: Buffer) => {
        if (err) reject(err);
        else resolve(derivedKey.toString('hex'));
      });
    });
  }
  
  private constantTimeCompare(a: string, b: string): boolean {
    if (a.length !== b.length) {
      return false;
    }
    
    let result = 0;
    for (let i = 0; i < a.length; i++) {
      result |= a.charCodeAt(i) ^ b.charCodeAt(i);
    }
    
    return result === 0;
  }
}

15.7 审计日志

// 审计日志接口
interface AuditLogger {
  log(event: SecurityEvent): Promise<void>;
  getEvents(query: SecurityEventQuery): Promise<SecurityEvent[]>;
  getEventById(eventId: string): Promise<SecurityEvent | null>;
  deleteOldEvents(olderThan: Date): Promise<number>;
  exportEvents(query: SecurityEventQuery, format: ExportFormat): Promise<string>;
}

// 审计日志实现
class DatabaseAuditLogger implements AuditLogger {
  private eventStore: SecurityEventStore;
  private encryptionService: EncryptionService;
  
  constructor(eventStore: SecurityEventStore, encryptionService: EncryptionService) {
    this.eventStore = eventStore;
    this.encryptionService = encryptionService;
  }
  
  async log(event: SecurityEvent): Promise<void> {
    // 生成事件ID
    const eventWithId: SecurityEvent = {
      ...event,
      id: this.generateEventId(),
      timestamp: event.timestamp || new Date()
    };
    
    // 加密敏感信息
    if (eventWithId.details) {
      eventWithId.details = await this.encryptSensitiveData(eventWithId.details);
    }
    
    // 存储事件
    await this.eventStore.store(eventWithId);
    
    // 检查是否需要触发告警
    await this.checkAlertConditions(eventWithId);
  }
  
  async getEvents(query: SecurityEventQuery): Promise<SecurityEvent[]> {
    const events = await this.eventStore.find(query);
    
    // 解密敏感信息
    for (const event of events) {
      if (event.details) {
        event.details = await this.decryptSensitiveData(event.details);
      }
    }
    
    return events;
  }
  
  async getEventById(eventId: string): Promise<SecurityEvent | null> {
    const event = await this.eventStore.findById(eventId);
    
    if (event && event.details) {
      event.details = await this.decryptSensitiveData(event.details);
    }
    
    return event;
  }
  
  async deleteOldEvents(olderThan: Date): Promise<number> {
    return await this.eventStore.deleteOlderThan(olderThan);
  }
  
  async exportEvents(query: SecurityEventQuery, format: ExportFormat): Promise<string> {
    const events = await this.getEvents(query);
    
    switch (format) {
      case ExportFormat.JSON:
        return JSON.stringify(events, null, 2);
      case ExportFormat.CSV:
        return this.convertToCSV(events);
      case ExportFormat.XML:
        return this.convertToXML(events);
      default:
        throw new Error(`Unsupported export format: ${format}`);
    }
  }
  
  private async encryptSensitiveData(details: Record<string, any>): Promise<Record<string, any>> {
    const sensitiveFields = ['password', 'token', 'secret', 'key'];
    const encrypted = { ...details };
    
    for (const field of sensitiveFields) {
      if (encrypted[field]) {
        encrypted[field] = await this.encryptionService.encrypt(encrypted[field]);
      }
    }
    
    return encrypted;
  }
  
  private async decryptSensitiveData(details: Record<string, any>): Promise<Record<string, any>> {
    const sensitiveFields = ['password', 'token', 'secret', 'key'];
    const decrypted = { ...details };
    
    for (const field of sensitiveFields) {
      if (decrypted[field] && typeof decrypted[field] === 'string' && decrypted[field].includes(':')) {
        try {
          decrypted[field] = await this.encryptionService.decrypt(decrypted[field]);
        } catch (error) {
          // 如果解密失败,保持原值
        }
      }
    }
    
    return decrypted;
  }
  
  private async checkAlertConditions(event: SecurityEvent): Promise<void> {
    // 检查是否需要触发安全告警
    if (event.severity === EventSeverity.CRITICAL) {
      await this.triggerAlert(event, 'Critical security event detected');
    }
    
    if (event.type === SecurityEventType.AUTHENTICATION_FAILURE) {
      await this.checkFailedLoginAttempts(event);
    }
    
    if (event.type === SecurityEventType.SUSPICIOUS_ACTIVITY) {
      await this.triggerAlert(event, 'Suspicious activity detected');
    }
  }
  
  private async checkFailedLoginAttempts(event: SecurityEvent): Promise<void> {
    if (!event.userId) return;
    
    const recentFailures = await this.eventStore.find({
      type: SecurityEventType.AUTHENTICATION_FAILURE,
      userId: event.userId,
      startTime: new Date(Date.now() - 15 * 60 * 1000), // 最近15分钟
      limit: 10
    });
    
    if (recentFailures.length >= 5) {
      await this.triggerAlert(event, `Multiple failed login attempts for user ${event.userId}`);
    }
  }
  
  private async triggerAlert(event: SecurityEvent, message: string): Promise<void> {
    // 实现告警逻辑,例如发送邮件、短信或推送通知
    console.warn(`SECURITY ALERT: ${message}`, event);
  }
  
  private convertToCSV(events: SecurityEvent[]): string {
    if (events.length === 0) return '';
    
    const headers = ['id', 'type', 'userId', 'timestamp', 'severity', 'details'];
    const csvRows = [headers.join(',')];
    
    for (const event of events) {
      const row = [
        event.id || '',
        event.type,
        event.userId || '',
        event.timestamp.toISOString(),
        event.severity,
        JSON.stringify(event.details || {})
      ];
      csvRows.push(row.map(field => `"${field}"`).join(','));
    }
    
    return csvRows.join('\n');
  }
  
  private convertToXML(events: SecurityEvent[]): string {
    let xml = '<?xml version="1.0" encoding="UTF-8"?>\n<events>\n';
    
    for (const event of events) {
      xml += '  <event>\n';
      xml += `    <id>${event.id || ''}</id>\n`;
      xml += `    <type>${event.type}</type>\n`;
      xml += `    <userId>${event.userId || ''}</userId>\n`;
      xml += `    <timestamp>${event.timestamp.toISOString()}</timestamp>\n`;
      xml += `    <severity>${event.severity}</severity>\n`;
      xml += `    <details>${JSON.stringify(event.details || {})}</details>\n`;
      xml += '  </event>\n';
    }
    
    xml += '</events>';
    return xml;
  }
  
  private generateEventId(): string {
    return `evt_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }
}

// 安全事件存储接口
interface SecurityEventStore {
  store(event: SecurityEvent): Promise<void>;
  findById(eventId: string): Promise<SecurityEvent | null>;
  find(query: SecurityEventQuery): Promise<SecurityEvent[]>;
  deleteOlderThan(date: Date): Promise<number>;
}

// 导出格式
enum ExportFormat {
  JSON = 'json',
  CSV = 'csv',
  XML = 'xml'
}

15.8 密码验证器

// 密码验证器接口
interface PasswordValidator {
  validate(password: string): Promise<PasswordValidationResult>;
  getPolicy(): PasswordPolicy;
  updatePolicy(policy: Partial<PasswordPolicy>): Promise<void>;
}

// 密码策略
interface PasswordPolicy {
  minLength: number;
  maxLength: number;
  requireUppercase: boolean;
  requireLowercase: boolean;
  requireNumbers: boolean;
  requireSpecialChars: boolean;
  forbiddenPasswords: string[];
  forbiddenPatterns: string[];
  maxRepeatingChars: number;
  maxSequentialChars: number;
  historySize: number;
  expirationDays: number;
}

// 密码验证器实现
class ComprehensivePasswordValidator implements PasswordValidator {
  private policy: PasswordPolicy;
  private commonPasswords: Set<string>;
  
  constructor(policy?: Partial<PasswordPolicy>) {
    this.policy = {
      minLength: 8,
      maxLength: 128,
      requireUppercase: true,
      requireLowercase: true,
      requireNumbers: true,
      requireSpecialChars: true,
      forbiddenPasswords: [],
      forbiddenPatterns: [],
      maxRepeatingChars: 3,
      maxSequentialChars: 3,
      historySize: 5,
      expirationDays: 90,
      ...policy
    };
    
    this.commonPasswords = new Set([
      'password', '123456', '123456789', 'qwerty', 'abc123',
      'password123', 'admin', 'letmein', 'welcome', 'monkey',
      'dragon', 'master', 'shadow', 'superman', 'michael'
    ]);
  }
  
  async validate(password: string): Promise<PasswordValidationResult> {
    const errors: string[] = [];
    const warnings: string[] = [];
    const suggestions: string[] = [];
    let score = 0;
    
    // 长度检查
    if (password.length < this.policy.minLength) {
      errors.push(`Password must be at least ${this.policy.minLength} characters long`);
    } else if (password.length >= this.policy.minLength) {
      score += 10;
    }
    
    if (password.length > this.policy.maxLength) {
      errors.push(`Password must not exceed ${this.policy.maxLength} characters`);
    }
    
    // 字符类型检查
    const hasUppercase = /[A-Z]/.test(password);
    const hasLowercase = /[a-z]/.test(password);
    const hasNumbers = /[0-9]/.test(password);
    const hasSpecialChars = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(password);
    
    if (this.policy.requireUppercase && !hasUppercase) {
      errors.push('Password must contain at least one uppercase letter');
    } else if (hasUppercase) {
      score += 15;
    }
    
    if (this.policy.requireLowercase && !hasLowercase) {
      errors.push('Password must contain at least one lowercase letter');
    } else if (hasLowercase) {
      score += 15;
    }
    
    if (this.policy.requireNumbers && !hasNumbers) {
      errors.push('Password must contain at least one number');
    } else if (hasNumbers) {
      score += 15;
    }
    
    if (this.policy.requireSpecialChars && !hasSpecialChars) {
      errors.push('Password must contain at least one special character');
    } else if (hasSpecialChars) {
      score += 20;
    }
    
    // 常见密码检查
    if (this.commonPasswords.has(password.toLowerCase())) {
      errors.push('Password is too common');
      suggestions.push('Use a unique password that is not commonly used');
    }
    
    // 禁用密码检查
    if (this.policy.forbiddenPasswords.includes(password.toLowerCase())) {
      errors.push('Password is forbidden');
    }
    
    // 禁用模式检查
    for (const pattern of this.policy.forbiddenPatterns) {
      if (new RegExp(pattern, 'i').test(password)) {
        errors.push('Password contains forbidden pattern');
        break;
      }
    }
    
    // 重复字符检查
    const repeatingChars = this.findRepeatingChars(password);
    if (repeatingChars > this.policy.maxRepeatingChars) {
      warnings.push(`Password contains ${repeatingChars} repeating characters (max: ${this.policy.maxRepeatingChars})`);
      suggestions.push('Avoid using too many repeating characters');
      score -= 10;
    }
    
    // 连续字符检查
    const sequentialChars = this.findSequentialChars(password);
    if (sequentialChars > this.policy.maxSequentialChars) {
      warnings.push(`Password contains ${sequentialChars} sequential characters (max: ${this.policy.maxSequentialChars})`);
      suggestions.push('Avoid using sequential characters like "123" or "abc"');
      score -= 10;
    }
    
    // 字典词汇检查
    const dictionaryWords = this.findDictionaryWords(password);
    if (dictionaryWords.length > 0) {
      warnings.push('Password contains dictionary words');
      suggestions.push('Consider using a mix of random characters instead of dictionary words');
      score -= 5;
    }
    
    // 熵计算
    const entropy = this.calculateEntropy(password);
    if (entropy < 30) {
      warnings.push('Password has low entropy (randomness)');
      suggestions.push('Use a more random combination of characters');
    } else if (entropy > 60) {
      score += 10;
    }
    
    // 确保分数在0-100范围内
    score = Math.max(0, Math.min(100, score));
    
    // 生成建议
    if (score < 50) {
      suggestions.push('Consider using a longer password with a mix of character types');
    }
    
    if (!hasSpecialChars && this.policy.requireSpecialChars) {
      suggestions.push('Add special characters like !@#$%^&* to strengthen your password');
    }
    
    return {
      valid: errors.length === 0,
      score,
      errors,
      warnings,
      suggestions
    };
  }
  
  getPolicy(): PasswordPolicy {
    return { ...this.policy };
  }
  
  async updatePolicy(policy: Partial<PasswordPolicy>): Promise<void> {
    this.policy = { ...this.policy, ...policy };
  }
  
  private findRepeatingChars(password: string): number {
    let maxRepeating = 0;
    let currentRepeating = 1;
    
    for (let i = 1; i < password.length; i++) {
      if (password[i] === password[i - 1]) {
        currentRepeating++;
      } else {
        maxRepeating = Math.max(maxRepeating, currentRepeating);
        currentRepeating = 1;
      }
    }
    
    return Math.max(maxRepeating, currentRepeating);
  }
  
  private findSequentialChars(password: string): number {
    let maxSequential = 0;
    let currentSequential = 1;
    
    for (let i = 1; i < password.length; i++) {
      const current = password.charCodeAt(i);
      const previous = password.charCodeAt(i - 1);
      
      if (current === previous + 1 || current === previous - 1) {
        currentSequential++;
      } else {
        maxSequential = Math.max(maxSequential, currentSequential);
        currentSequential = 1;
      }
    }
    
    return Math.max(maxSequential, currentSequential);
  }
  
  private findDictionaryWords(password: string): string[] {
    const commonWords = [
      'password', 'admin', 'user', 'login', 'welcome', 'hello',
      'world', 'test', 'demo', 'sample', 'example', 'default'
    ];
    
    const foundWords: string[] = [];
    const lowerPassword = password.toLowerCase();
    
    for (const word of commonWords) {
      if (lowerPassword.includes(word)) {
        foundWords.push(word);
      }
    }
    
    return foundWords;
  }
  
  private calculateEntropy(password: string): number {
    const charSets = {
      lowercase: /[a-z]/.test(password) ? 26 : 0,
      uppercase: /[A-Z]/.test(password) ? 26 : 0,
      numbers: /[0-9]/.test(password) ? 10 : 0,
      special: /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(password) ? 32 : 0
    };
    
    const charsetSize = Object.values(charSets).reduce((sum, size) => sum + size, 0);
    
    if (charsetSize === 0) return 0;
    
    return password.length * Math.log2(charsetSize);
  }
}

15.9 完整示例

// 低代码安全管理演示
class LowCodeSecurityDemo {
  private securityManager: SecurityManager;
  private authProvider: AuthenticationProvider;
  private auditLogger: AuditLogger;
  private passwordValidator: PasswordValidator;
  private encryptionService: EncryptionService;
  
  constructor() {
    this.initializeServices();
  }
  
  private initializeServices(): void {
    // 初始化加密服务
    this.encryptionService = new CryptoEncryptionService();
    
    // 初始化密码验证器
    this.passwordValidator = new ComprehensivePasswordValidator({
      minLength: 12,
      requireSpecialChars: true,
      maxRepeatingChars: 2
    });
    
    // 初始化认证提供者
    this.authProvider = new MultiFactorAuthProvider(
      new PasswordAuthenticator(this.encryptionService),
      new TokenAuthenticator(),
      new TOTPProvider(),
      new SMSProvider()
    );
    
    // 初始化审计日志
    const eventStore = new MemorySecurityEventStore();
    this.auditLogger = new DatabaseAuditLogger(eventStore, this.encryptionService);
    
    // 初始化安全管理器
    this.securityManager = new LowCodeSecurityManager(
      this.authProvider,
      new MemoryUserStore(),
      new MemoryRoleStore(),
      new MemoryPermissionStore(),
      this.auditLogger,
      this.passwordValidator
    );
  }
  
  async demonstrateUserManagement(): Promise<void> {
    console.log('=== 用户管理演示 ===');
    
    // 创建用户
    const user: CreateUserRequest = {
      username: 'john_doe',
      email: 'john@example.com',
      password: 'SecureP@ssw0rd123!',
      profile: {
        firstName: 'John',
        lastName: 'Doe',
        department: 'Engineering'
      }
    };
    
    const createdUser = await this.securityManager.createUser(user);
    console.log('Created user:', createdUser.username);
    
    // 创建角色
    const role: CreateRoleRequest = {
      name: 'developer',
      description: 'Software Developer',
      permissions: ['read:code', 'write:code', 'deploy:staging']
    };
    
    const createdRole = await this.securityManager.createRole(role);
    console.log('Created role:', createdRole.name);
    
    // 分配角色
    await this.securityManager.assignRole(createdUser.id, createdRole.id);
    console.log('Assigned role to user');
    
    // 验证权限
    const hasPermission = await this.securityManager.checkPermission(
      createdUser.id,
      'read:code',
      { resource: 'project-1' }
    );
    console.log('User has read:code permission:', hasPermission);
  }
  
  async demonstrateAuthentication(): Promise<void> {
    console.log('\n=== 认证演示 ===');
    
    // 密码认证
    const authResult = await this.securityManager.authenticate({
      type: AuthenticationType.PASSWORD,
      credentials: {
        username: 'john_doe',
        password: 'SecureP@ssw0rd123!'
      }
    });
    
    if (authResult.success) {
      console.log('Password authentication successful');
      console.log('Access token:', authResult.accessToken?.substring(0, 20) + '...');
      
      // 多因素认证
      const mfaResult = await this.securityManager.authenticate({
        type: AuthenticationType.TOTP,
        credentials: {
          userId: authResult.user?.id,
          code: '123456' // 模拟TOTP代码
        }
      });
      
      console.log('MFA authentication result:', mfaResult.success);
    }
  }
  
  async demonstratePasswordValidation(): Promise<void> {
    console.log('\n=== 密码验证演示 ===');
    
    const passwords = [
      'weak',
      'password123',
      'SecureP@ssw0rd123!',
      'VeryStr0ng&C0mpl3xP@ssw0rd!'
    ];
    
    for (const password of passwords) {
      const result = await this.passwordValidator.validate(password);
      console.log(`\nPassword: ${password}`);
      console.log(`Valid: ${result.valid}`);
      console.log(`Score: ${result.score}/100`);
      
      if (result.errors.length > 0) {
        console.log('Errors:', result.errors);
      }
      
      if (result.warnings.length > 0) {
        console.log('Warnings:', result.warnings);
      }
      
      if (result.suggestions.length > 0) {
        console.log('Suggestions:', result.suggestions);
      }
    }
  }
  
  async demonstrateAuditLogging(): Promise<void> {
    console.log('\n=== 审计日志演示 ===');
    
    // 记录安全事件
    await this.auditLogger.log({
      type: SecurityEventType.AUTHENTICATION_SUCCESS,
      userId: 'user_123',
      timestamp: new Date(),
      severity: EventSeverity.INFO,
      details: {
        method: 'password',
        ipAddress: '192.168.1.100',
        userAgent: 'Mozilla/5.0...'
      }
    });
    
    await this.auditLogger.log({
      type: SecurityEventType.PERMISSION_DENIED,
      userId: 'user_456',
      timestamp: new Date(),
      severity: EventSeverity.WARNING,
      details: {
        resource: 'sensitive-data',
        action: 'delete',
        reason: 'insufficient permissions'
      }
    });
    
    // 查询事件
    const events = await this.auditLogger.getEvents({
      startTime: new Date(Date.now() - 24 * 60 * 60 * 1000), // 最近24小时
      limit: 10
    });
    
    console.log(`Found ${events.length} security events`);
    events.forEach(event => {
      console.log(`- ${event.type} (${event.severity}) at ${event.timestamp.toISOString()}`);
    });
    
    // 导出事件
    const exportData = await this.auditLogger.exportEvents(
      { limit: 100 },
      ExportFormat.JSON
    );
    console.log('Exported events length:', exportData.length);
  }
  
  async demonstrateEncryption(): Promise<void> {
    console.log('\n=== 加密服务演示 ===');
    
    const sensitiveData = 'This is sensitive information';
    
    // 加密数据
    const encrypted = await this.encryptionService.encrypt(sensitiveData);
    console.log('Encrypted data:', encrypted.substring(0, 50) + '...');
    
    // 解密数据
    const decrypted = await this.encryptionService.decrypt(encrypted);
    console.log('Decrypted data:', decrypted);
    console.log('Encryption/Decryption successful:', sensitiveData === decrypted);
    
    // 密码哈希
    const password = 'MySecurePassword123!';
    const hashedPassword = await this.encryptionService.hashPassword(password);
    console.log('Hashed password:', hashedPassword);
    
    // 密码验证
    const isValid = await this.encryptionService.verifyPassword(password, hashedPassword);
    console.log('Password verification:', isValid);
  }
  
  async demonstrateSecurityPolicies(): Promise<void> {
    console.log('\n=== 安全策略演示 ===');
    
    // 创建安全策略
    const policy: CreateSecurityPolicyRequest = {
      name: 'data-access-policy',
      description: 'Controls access to sensitive data',
      rules: [
        {
          condition: 'user.department == "Finance"',
          action: PolicyAction.ALLOW,
          resources: ['financial-data']
        },
        {
          condition: 'time.hour >= 9 && time.hour <= 17',
          action: PolicyAction.ALLOW,
          resources: ['*']
        },
        {
          condition: 'request.ipAddress.startsWith("192.168.1."))',
          action: PolicyAction.ALLOW,
          resources: ['*']
        }
      ]
    };
    
    const createdPolicy = await this.securityManager.createSecurityPolicy(policy);
    console.log('Created security policy:', createdPolicy.name);
    
    // 评估策略
    const context: AuthorizationContext = {
      user: {
        id: 'user_123',
        department: 'Finance'
      },
      resource: 'financial-data',
      action: 'read',
      environment: {
        time: new Date(),
        ipAddress: '192.168.1.100'
      }
    };
    
    const decision = await this.securityManager.evaluatePolicy(createdPolicy.id, context);
    console.log('Policy decision:', decision);
  }
  
  async run(): Promise<void> {
    try {
      await this.demonstrateUserManagement();
      await this.demonstrateAuthentication();
      await this.demonstratePasswordValidation();
      await this.demonstrateAuditLogging();
      await this.demonstrateEncryption();
      await this.demonstrateSecurityPolicies();
      
      console.log('\n=== 安全管理演示完成 ===');
    } catch (error) {
      console.error('演示过程中发生错误:', error);
    }
  }
}

// 内存实现的安全事件存储
class MemorySecurityEventStore implements SecurityEventStore {
  private events: Map<string, SecurityEvent> = new Map();
  
  async store(event: SecurityEvent): Promise<void> {
    if (event.id) {
      this.events.set(event.id, event);
    }
  }
  
  async findById(eventId: string): Promise<SecurityEvent | null> {
    return this.events.get(eventId) || null;
  }
  
  async find(query: SecurityEventQuery): Promise<SecurityEvent[]> {
    let results = Array.from(this.events.values());
    
    if (query.type) {
      results = results.filter(event => event.type === query.type);
    }
    
    if (query.userId) {
      results = results.filter(event => event.userId === query.userId);
    }
    
    if (query.severity) {
      results = results.filter(event => event.severity === query.severity);
    }
    
    if (query.startTime) {
      results = results.filter(event => event.timestamp >= query.startTime!);
    }
    
    if (query.endTime) {
      results = results.filter(event => event.timestamp <= query.endTime!);
    }
    
    // 按时间倒序排序
    results.sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime());
    
    if (query.limit) {
      results = results.slice(0, query.limit);
    }
    
    return results;
  }
  
  async deleteOlderThan(date: Date): Promise<number> {
    let deletedCount = 0;
    
    for (const [id, event] of this.events.entries()) {
      if (event.timestamp < date) {
        this.events.delete(id);
        deletedCount++;
      }
    }
    
    return deletedCount;
  }
}

// 运行演示
const demo = new LowCodeSecurityDemo();
demo.run();

15.10 Web API 集成

// Express.js 安全管理 API
import express from 'express';
import { SecurityManager } from './security-manager';
import { AuthenticationMiddleware } from './auth-middleware';

const app = express();
app.use(express.json());

// 安全管理器实例
const securityManager = new SecurityManager(/* ... */);
const authMiddleware = new AuthenticationMiddleware(securityManager);

// 认证相关 API
app.post('/api/auth/login', async (req, res) => {
  try {
    const { username, password } = req.body;
    
    const result = await securityManager.authenticate({
      type: AuthenticationType.PASSWORD,
      credentials: { username, password }
    });
    
    if (result.success) {
      res.json({
        success: true,
        accessToken: result.accessToken,
        refreshToken: result.refreshToken,
        user: result.user
      });
    } else {
      res.status(401).json({
        success: false,
        message: 'Authentication failed'
      });
    }
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.post('/api/auth/mfa/verify', authMiddleware.authenticate, async (req, res) => {
  try {
    const { code, method } = req.body;
    const userId = req.user.id;
    
    const result = await securityManager.authenticate({
      type: method === 'totp' ? AuthenticationType.TOTP : AuthenticationType.SMS,
      credentials: { userId, code }
    });
    
    res.json({ success: result.success });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 用户管理 API
app.post('/api/users', authMiddleware.requirePermission('create:users'), async (req, res) => {
  try {
    const user = await securityManager.createUser(req.body);
    res.status(201).json(user);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.get('/api/users', authMiddleware.requirePermission('read:users'), async (req, res) => {
  try {
    const users = await securityManager.getUsers(req.query);
    res.json(users);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.put('/api/users/:id', authMiddleware.requirePermission('update:users'), async (req, res) => {
  try {
    const user = await securityManager.updateUser(req.params.id, req.body);
    res.json(user);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 角色管理 API
app.post('/api/roles', authMiddleware.requirePermission('create:roles'), async (req, res) => {
  try {
    const role = await securityManager.createRole(req.body);
    res.status(201).json(role);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.get('/api/roles', authMiddleware.requirePermission('read:roles'), async (req, res) => {
  try {
    const roles = await securityManager.getRoles(req.query);
    res.json(roles);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 权限管理 API
app.post('/api/permissions', authMiddleware.requirePermission('create:permissions'), async (req, res) => {
  try {
    const permission = await securityManager.createPermission(req.body);
    res.status(201).json(permission);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.post('/api/users/:userId/roles/:roleId', authMiddleware.requirePermission('assign:roles'), async (req, res) => {
  try {
    await securityManager.assignRole(req.params.userId, req.params.roleId);
    res.json({ success: true });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 安全策略 API
app.post('/api/security-policies', authMiddleware.requirePermission('create:policies'), async (req, res) => {
  try {
    const policy = await securityManager.createSecurityPolicy(req.body);
    res.status(201).json(policy);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.get('/api/security-policies', authMiddleware.requirePermission('read:policies'), async (req, res) => {
  try {
    const policies = await securityManager.getSecurityPolicies(req.query);
    res.json(policies);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 审计日志 API
app.get('/api/audit-logs', authMiddleware.requirePermission('read:audit'), async (req, res) => {
  try {
    const events = await securityManager.getAuditEvents(req.query);
    res.json(events);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.get('/api/audit-logs/export', authMiddleware.requirePermission('export:audit'), async (req, res) => {
  try {
    const { format = 'json' } = req.query;
    const data = await securityManager.exportAuditEvents(req.query, format as ExportFormat);
    
    res.setHeader('Content-Type', format === 'csv' ? 'text/csv' : 'application/json');
    res.setHeader('Content-Disposition', `attachment; filename=audit-logs.${format}`);
    res.send(data);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 密码验证 API
app.post('/api/password/validate', async (req, res) => {
  try {
    const { password } = req.body;
    const result = await securityManager.validatePassword(password);
    res.json(result);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 合规报告 API
app.get('/api/compliance/report', authMiddleware.requirePermission('read:compliance'), async (req, res) => {
  try {
    const report = await securityManager.generateComplianceReport(req.query);
    res.json(report);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.listen(3000, () => {
  console.log('Security API server running on port 3000');
});

15.11 小结

本章详细介绍了低代码平台的安全与权限管理系统,涵盖了以下核心功能:

核心功能

  1. 认证管理

    • 多种认证方式(密码、令牌、多因素认证)
    • 账户锁定和安全策略
    • 认证提供者架构
  2. 授权控制

    • 基于角色的访问控制(RBAC)
    • 细粒度权限管理
    • 动态权限检查
  3. 用户管理

    • 用户生命周期管理
    • 用户资料和偏好设置
    • 用户状态管理
  4. 角色权限

    • 角色定义和管理
    • 权限分配和继承
    • 角色层次结构
  5. 安全策略

    • 策略定义和评估
    • 条件化访问控制
    • 策略规则引擎
  6. 审计日志

    • 安全事件记录
    • 日志加密和保护
    • 事件查询和导出
  7. 加密服务

    • 数据加密和解密
    • 密码哈希和验证
    • 密钥管理
  8. 密码安全

    • 密码强度验证
    • 密码策略管理
    • 密码历史和过期

技术特色

  1. 多层安全防护

    • 认证、授权、审计三重保障
    • 深度防御策略
    • 安全事件监控
  2. 灵活的权限模型

    • 支持复杂的权限继承
    • 动态权限评估
    • 上下文感知的访问控制
  3. 强加密保护

    • 行业标准加密算法
    • 安全的密钥管理
    • 数据传输和存储加密
  4. 全面的审计能力

    • 完整的操作记录
    • 安全事件分析
    • 合规报告生成
  5. 高性能设计

    • 缓存优化的权限检查
    • 异步处理机制
    • 可扩展的存储架构
  6. 易于集成

    • 标准化的API接口
    • 插件化的认证提供者
    • 灵活的配置选项

下一章我们将学习低代码平台的性能优化与监控,了解如何确保平台的高性能运行和实时监控。