Compliance
Security compliance frameworks, standards, and regulatory requirements for the application.
Compliance
Maintaining compliance with security standards and regulations is crucial for protecting data and meeting legal requirements. This guide covers major compliance frameworks and implementation strategies.
Compliance Frameworks
SOC 2 (Service Organization Control 2)
SOC 2 focuses on five trust service criteria for service organizations.
// lib/compliance/soc2.ts
export class SOC2Compliance {
static async assessSecurityCriteria() {
return {
security: {
access_controls: await this.evaluateAccessControls(),
logical_physical_controls: await this.evaluateLogicalControls(),
system_operations: await this.evaluateSystemOperations(),
change_management: await this.evaluateChangeManagement(),
risk_mitigation: await this.evaluateRiskMitigation()
}
}
}
private static async evaluateAccessControls() {
// Check user access management
const userAccess = await supabase
.from('users')
.select('id, role, status, last_login, created_at')
// Check inactive users
const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)
const inactiveUsers = userAccess.data?.filter(user =>
new Date(user.last_login) < thirtyDaysAgo
) || []
// Check privileged access
const adminUsers = userAccess.data?.filter(user =>
user.role === 'admin' || user.role === 'super_admin'
) || []
return {
total_users: userAccess.data?.length || 0,
inactive_users: inactiveUsers.length,
privileged_users: adminUsers.length,
access_review_needed: inactiveUsers.length > 0,
compliance_score: this.calculateAccessControlScore(inactiveUsers.length, adminUsers.length)
}
}
private static async evaluateLogicalControls() {
// Check password policies
const passwordPolicy = await this.checkPasswordPolicy()
// Check MFA adoption
const mfaStats = await this.checkMFAAdoption()
// Check session management
const sessionSecurity = await this.checkSessionSecurity()
return {
password_policy: passwordPolicy,
mfa_adoption: mfaStats,
session_security: sessionSecurity,
compliance_score: this.calculateLogicalControlsScore(passwordPolicy, mfaStats, sessionSecurity)
}
}
private static async checkPasswordPolicy() {
// This would integrate with your authentication system
return {
minimum_length: 12,
complexity_required: true,
rotation_period_days: 90,
history_count: 12,
lockout_policy: true,
compliant: true
}
}
private static async checkMFAAdoption() {
const totalUsers = await supabase
.from('users')
.select('id', { count: 'exact', head: true })
const mfaUsers = await supabase
.from('user_mfa')
.select('user_id', { count: 'exact', head: true })
.eq('enabled', true)
const adoptionRate = (mfaUsers.count || 0) / (totalUsers.count || 1)
return {
total_users: totalUsers.count || 0,
mfa_enabled_users: mfaUsers.count || 0,
adoption_rate: Math.round(adoptionRate * 100),
target_rate: 100,
compliant: adoptionRate >= 0.95 // 95% minimum
}
}
static async generateSOC2Report() {
const assessment = await this.assessSecurityCriteria()
const auditTrail = await this.generateAuditTrail()
return {
report_type: 'SOC2_Type_II',
assessment_date: new Date().toISOString(),
assessment_period: '12_months',
criteria_assessment: assessment,
audit_trail: auditTrail,
exceptions: await this.identifyExceptions(),
remediation_plan: await this.generateRemediationPlan(),
compliance_score: this.calculateOverallScore(assessment)
}
}
}
ISO 27001 (Information Security Management)
// lib/compliance/iso27001.ts
export class ISO27001Compliance {
static async assessInformationSecurity() {
return {
context_of_organization: await this.assessContext(),
leadership: await this.assessLeadership(),
planning: await this.assessPlanning(),
support: await this.assessSupport(),
operation: await this.assessOperation(),
performance_evaluation: await this.assessPerformance(),
improvement: await this.assessImprovement()
}
}
private static async assessContext() {
return {
scope_definition: {
defined: true,
documented: true,
boundaries_clear: true
},
stakeholder_requirements: {
identified: true,
documented: true,
regularly_reviewed: true
},
isms_scope: {
appropriate: true,
justified: true,
maintained: true
}
}
}
private static async assessOperation() {
// Assess implementation of security controls
const controls = await this.assessSecurityControls()
return {
operational_planning: await this.checkOperationalPlanning(),
information_security_risk_management: await this.checkRiskManagement(),
security_controls: controls,
compliance_score: this.calculateOperationScore(controls)
}
}
private static async assessSecurityControls() {
const controls = {
'A.5': await this.assessPolicies(), // Information security policies
'A.6': await this.assessOrganization(), // Organization of information security
'A.7': await this.assessHumanResources(), // Human resource security
'A.8': await this.assessAssetManagement(), // Asset management
'A.9': await this.assessAccessControl(), // Access control
'A.10': await this.assessCryptography(), // Cryptography
'A.11': await this.assessPhysicalSecurity(), // Physical and environmental security
'A.12': await this.assessOperationsSecurity(), // Operations security
'A.13': await this.assessCommunicationsSecurity(), // Communications security
'A.14': await this.assessSystemDevelopment(), // System acquisition, development and maintenance
'A.15': await this.assessSupplierRelationships(), // Supplier relationships
'A.16': await this.assessIncidentManagement(), // Information security incident management
'A.17': await this.assessBusinessContinuity(), // Information security aspects of business continuity management
'A.18': await this.assessCompliance() // Compliance
}
return controls
}
static async generateISO27001Report() {
const assessment = await this.assessInformationSecurity()
return {
standard: 'ISO_27001_2022',
assessment_date: new Date().toISOString(),
organization_context: assessment.context_of_organization,
isms_assessment: assessment,
controls_assessment: await this.assessSecurityControls(),
risk_treatment_plan: await this.generateRiskTreatmentPlan(),
statement_of_applicability: await this.generateSoA(),
compliance_score: this.calculateISO27001Score(assessment)
}
}
}
GDPR (General Data Protection Regulation)
// lib/compliance/gdpr.ts
export class GDPRCompliance {
static async assessDataProtection() {
return {
lawfulness: await this.assessLawfulness(),
data_minimization: await this.assessDataMinimization(),
purpose_limitation: await this.assessPurposeLimitation(),
accuracy: await this.assessAccuracy(),
storage_limitation: await this.assessStorageLimitation(),
security: await this.assessSecurity(),
accountability: await this.assessAccountability()
}
}
private static async assessLawfulness() {
// Check legal basis for processing
const dataProcessing = await supabase
.from('data_processing_activities')
.select('*')
const withLegalBasis = dataProcessing.data?.filter(activity =>
activity.legal_basis && activity.legal_basis !== ''
) || []
return {
total_activities: dataProcessing.data?.length || 0,
with_legal_basis: withLegalBasis.length,
compliance_rate: withLegalBasis.length / (dataProcessing.data?.length || 1),
compliant: withLegalBasis.length === (dataProcessing.data?.length || 0)
}
}
private static async assessDataMinimization() {
// Check if only necessary data is collected
const dataFields = await supabase
.from('data_collection_points')
.select('*')
const necessaryFields = dataFields.data?.filter(field =>
field.necessity_justified === true
) || []
return {
total_fields: dataFields.data?.length || 0,
necessary_fields: necessaryFields.length,
minimization_score: necessaryFields.length / (dataFields.data?.length || 1),
compliant: necessaryFields.length === (dataFields.data?.length || 0)
}
}
private static async assessStorageLimitation() {
// Check data retention policies
const retentionPolicies = await supabase
.from('data_retention_policies')
.select('*')
const activeRetention = retentionPolicies.data?.filter(policy =>
policy.active === true && policy.retention_period
) || []
return {
total_data_types: retentionPolicies.data?.length || 0,
with_retention_policy: activeRetention.length,
policy_coverage: activeRetention.length / (retentionPolicies.data?.length || 1),
compliant: activeRetention.length === (retentionPolicies.data?.length || 0)
}
}
static async handleDataSubjectRights() {
return {
right_of_access: await this.implementRightOfAccess(),
right_of_rectification: await this.implementRightOfRectification(),
right_of_erasure: await this.implementRightOfErasure(),
right_of_portability: await this.implementRightOfPortability(),
right_to_object: await this.implementRightToObject()
}
}
private static async implementRightOfAccess() {
// Implementation for data subject access requests
return {
procedure_documented: true,
response_timeframe: '30_days',
automated_export: true,
format: 'structured_json',
compliant: true
}
}
private static async implementRightOfErasure() {
// Implementation for right to be forgotten
return {
procedure_documented: true,
automated_deletion: true,
cascade_deletion: true,
backup_handling: true,
third_party_notification: true,
compliant: true
}
}
static async generateGDPRReport() {
const assessment = await this.assessDataProtection()
const rightsImplementation = await this.handleDataSubjectRights()
return {
regulation: 'GDPR_2018',
assessment_date: new Date().toISOString(),
data_protection_principles: assessment,
data_subject_rights: rightsImplementation,
privacy_by_design: await this.assessPrivacyByDesign(),
data_protection_impact_assessments: await this.getDPIAStatus(),
data_breach_procedures: await this.assessBreachProcedures(),
international_transfers: await this.assessInternationalTransfers(),
compliance_score: this.calculateGDPRScore(assessment, rightsImplementation)
}
}
}
HIPAA (Health Insurance Portability and Accountability Act)
// lib/compliance/hipaa.ts
export class HIPAACompliance {
static async assessHIPAACompliance() {
return {
administrative_safeguards: await this.assessAdministrativeSafeguards(),
physical_safeguards: await this.assessPhysicalSafeguards(),
technical_safeguards: await this.assessTechnicalSafeguards()
}
}
private static async assessAdministrativeSafeguards() {
return {
security_officer: {
assigned: true,
documented: true,
responsibilities_defined: true
},
workforce_training: {
program_exists: true,
regular_updates: true,
completion_tracked: true
},
access_management: {
procedures_documented: true,
access_authorization: true,
access_establishment: true,
access_modification: true
},
incident_procedures: {
documented: true,
reporting_process: true,
response_procedures: true
}
}
}
private static async assessTechnicalSafeguards() {
return {
access_control: {
unique_user_identification: true,
automatic_logoff: true,
encryption_decryption: true
},
audit_controls: {
audit_logs: await this.checkAuditLogs(),
review_procedures: true,
reporting: true
},
integrity: {
phi_alteration_protection: true,
electronic_signature: true
},
transmission_security: {
end_to_end_encryption: true,
network_controls: true,
encryption_algorithms: true
}
}
}
private static async checkAuditLogs() {
const auditLogs = await supabase
.from('audit_logs')
.select('*')
.gte('timestamp', new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString())
return {
logging_enabled: true,
phi_access_logged: true,
modification_logged: true,
retention_period: '6_years',
log_count_30_days: auditLogs.data?.length || 0
}
}
static async generateHIPAAReport() {
const assessment = await this.assessHIPAACompliance()
return {
standard: 'HIPAA_Security_Rule',
assessment_date: new Date().toISOString(),
safeguards_assessment: assessment,
risk_assessment: await this.performRiskAssessment(),
policies_procedures: await this.assessPoliciesProcedures(),
business_associate_agreements: await this.assessBAAs(),
breach_notification: await this.assessBreachNotification(),
compliance_score: this.calculateHIPAAScore(assessment)
}
}
}
Compliance Monitoring
Automated Compliance Checks
// lib/compliance/monitoring.ts
export class ComplianceMonitor {
static async runDailyComplianceChecks() {
const results = await Promise.all([
this.checkAccessControls(),
this.checkDataRetention(),
this.checkEncryption(),
this.checkAuditLogs(),
this.checkBackupIntegrity()
])
const report = {
check_date: new Date().toISOString(),
results: results.reduce((acc, result) => ({ ...acc, ...result }), {}),
overall_status: results.every(r => Object.values(r)[0].compliant) ? 'compliant' : 'non_compliant'
}
// Store compliance check results
await supabase
.from('compliance_checks')
.insert(report)
// Alert on non-compliance
if (report.overall_status === 'non_compliant') {
await this.sendComplianceAlert(report)
}
return report
}
private static async checkAccessControls() {
const privilegedUsers = await supabase
.from('users')
.select('*')
.in('role', ['admin', 'super_admin'])
const mfaEnabled = await supabase
.from('user_mfa')
.select('user_id')
.eq('enabled', true)
.in('user_id', privilegedUsers.data?.map(u => u.id) || [])
const compliant = mfaEnabled.data?.length === privilegedUsers.data?.length
return {
access_controls: {
compliant,
privileged_users: privilegedUsers.data?.length || 0,
mfa_enabled: mfaEnabled.data?.length || 0,
issues: compliant ? [] : ['Privileged users without MFA detected']
}
}
}
private static async checkDataRetention() {
const retentionPolicies = await supabase
.from('data_retention_policies')
.select('*')
const expiredData = await this.findExpiredData()
return {
data_retention: {
compliant: expiredData.length === 0,
policies_count: retentionPolicies.data?.length || 0,
expired_records: expiredData.length,
issues: expiredData.length > 0 ? ['Expired data found that should be deleted'] : []
}
}
}
private static async findExpiredData() {
// Check for data that should be deleted based on retention policies
const policies = await supabase
.from('data_retention_policies')
.select('*')
const expiredData = []
for (const policy of policies.data || []) {
const cutoffDate = new Date(Date.now() - policy.retention_days * 24 * 60 * 60 * 1000)
const { data: expired } = await supabase
.from(policy.table_name)
.select('id')
.lt(policy.date_column, cutoffDate.toISOString())
if (expired && expired.length > 0) {
expiredData.push({
table: policy.table_name,
count: expired.length,
policy: policy.policy_name
})
}
}
return expiredData
}
static async generateComplianceReport(framework: string) {
switch (framework.toLowerCase()) {
case 'soc2':
return await SOC2Compliance.generateSOC2Report()
case 'iso27001':
return await ISO27001Compliance.generateISO27001Report()
case 'gdpr':
return await GDPRCompliance.generateGDPRReport()
case 'hipaa':
return await HIPAACompliance.generateHIPAAReport()
default:
throw new Error(`Unsupported compliance framework: ${framework}`)
}
}
}
Documentation and Evidence
Compliance Documentation
// lib/compliance/documentation.ts
export class ComplianceDocumentation {
static async generatePolicyDocuments() {
return {
information_security_policy: await this.generateInfoSecPolicy(),
data_protection_policy: await this.generateDataProtectionPolicy(),
incident_response_policy: await this.generateIncidentResponsePolicy(),
access_control_policy: await this.generateAccessControlPolicy(),
backup_recovery_policy: await this.generateBackupRecoveryPolicy()
}
}
static async generateEvidencePackage(framework: string, startDate: string, endDate: string) {
const evidence = {
audit_logs: await this.collectAuditLogs(startDate, endDate),
security_assessments: await this.collectSecurityAssessments(startDate, endDate),
compliance_checks: await this.collectComplianceChecks(startDate, endDate),
policies_procedures: await this.collectPoliciesProcedures(),
training_records: await this.collectTrainingRecords(startDate, endDate),
incident_reports: await this.collectIncidentReports(startDate, endDate)
}
return {
framework,
evidence_period: { start: startDate, end: endDate },
generated_at: new Date().toISOString(),
evidence_package: evidence,
integrity_hash: await this.calculateIntegrityHash(evidence)
}
}
private static async collectAuditLogs(startDate: string, endDate: string) {
const logs = await supabase
.from('audit_logs')
.select('*')
.gte('timestamp', startDate)
.lte('timestamp', endDate)
.order('timestamp', { ascending: true })
return {
total_events: logs.data?.length || 0,
categories: this.categorizeAuditLogs(logs.data || []),
sample_logs: logs.data?.slice(0, 100) || [] // Include sample for review
}
}
private static async collectSecurityAssessments(startDate: string, endDate: string) {
return await supabase
.from('security_assessments')
.select('*')
.gte('assessment_date', startDate)
.lte('assessment_date', endDate)
.order('assessment_date', { ascending: false })
}
private static async calculateIntegrityHash(evidence: any): Promise<string> {
const crypto = require('crypto')
const evidenceString = JSON.stringify(evidence)
return crypto.createHash('sha256').update(evidenceString).digest('hex')
}
}
Compliance Dashboard
Real-time Compliance Status
// components/ComplianceDashboard.tsx
export function ComplianceDashboard() {
const [complianceStatus, setComplianceStatus] = useState(null)
const [selectedFramework, setSelectedFramework] = useState('SOC2')
useEffect(() => {
loadComplianceStatus()
}, [selectedFramework])
const loadComplianceStatus = async () => {
try {
const response = await fetch(`/api/compliance/${selectedFramework.toLowerCase()}`)
const data = await response.json()
setComplianceStatus(data)
} catch (error) {
console.error('Failed to load compliance status:', error)
}
}
return (
<div className="compliance-dashboard">
<div className="framework-selector">
<select value={selectedFramework} onChange={(e) => setSelectedFramework(e.target.value)}>
<option value="SOC2">SOC 2</option>
<option value="ISO27001">ISO 27001</option>
<option value="GDPR">GDPR</option>
<option value="HIPAA">HIPAA</option>
</select>
</div>
{complianceStatus && (
<div className="compliance-metrics">
<div className="overall-score">
<h3>Overall Compliance Score</h3>
<div className={`score ${complianceStatus.overall_score >= 90 ? 'good' : 'needs-attention'}`}>
{complianceStatus.overall_score}%
</div>
</div>
<div className="controls-status">
<h3>Control Categories</h3>
{Object.entries(complianceStatus.controls || {}).map(([category, status]) => (
<div key={category} className="control-category">
<span className="category-name">{category}</span>
<span className={`status ${status.compliant ? 'compliant' : 'non-compliant'}`}>
{status.compliant ? '✓ Compliant' : '⚠ Needs Attention'}
</span>
</div>
))}
</div>
<div className="recent-assessments">
<h3>Recent Assessments</h3>
{complianceStatus.recent_assessments?.map((assessment, index) => (
<div key={index} className="assessment-item">
<span className="date">{new Date(assessment.date).toLocaleDateString()}</span>
<span className="type">{assessment.type}</span>
<span className={`result ${assessment.result}`}>{assessment.result}</span>
</div>
))}
</div>
</div>
)}
</div>
)
}
This comprehensive compliance system ensures adherence to major security standards and regulations while providing automated monitoring, documentation, and reporting capabilities.