import { Provide } from '@midwayjs/core'; import { BaseService } from '@cool-midway/core'; import * as crypto from 'crypto'; export interface GdprUserDataBundle { subjectId: string; exportedAt: string; complianceStandard: 'GDPR_ARTICLE_20' | 'CCPA'; dataPayload: Record; } export interface ErasureReceipt { subjectId: string; action: 'PURGED_AND_ANONYMIZED'; executedAt: string; certificateHash: string; } /** * IP 地址合规脱敏掩码 (GDPR 最小必要原则) */ export function maskIpAddress(ip?: string): string { if (!ip || typeof ip !== 'string') return 'unknown'; const clean = ip.trim(); // IPv4 掩码后 1 段 if (clean.includes('.')) { const parts = clean.split('.'); if (parts.length === 4) { return `${parts[0]}.${parts[1]}.${parts[2]}.xxx`; } } // IPv6 掩码后 5 段 if (clean.includes(':')) { const parts = clean.split(':'); if (parts.length >= 4) { return `${parts.slice(0, 3).join(':')}:xxxx:xxxx:xxxx:xxxx:xxxx`; } } return 'unknown'; } /** * 个人隐私数据 (PII) 彻底脱敏清洗 */ export function anonymizePiiData(rawRecord: { id: number; name?: string; email?: string; phone?: string; company?: string; notes?: string; [key: string]: any; }): Record { return { ...rawRecord, name: '[GDPR_DELETED]', email: `deleted-${rawRecord.id}@privacy.anonymized`, phone: '', notes: '', }; } /** * 海外合规 GDPR / CCPA 隐私治理服务 */ @Provide() export class ComplianceGdprService extends BaseService { /** * 打包主体全量便携数据 (GDPR Article 20) */ async exportPersonalDataBundle( subjectId: string, dataPayload: Record ): Promise { return { subjectId, exportedAt: new Date().toISOString(), complianceStandard: 'GDPR_ARTICLE_20', dataPayload, }; } /** * 执行被遗忘权销毁并签发销毁证书 (GDPR Article 17) */ async executeRightToBeForgotten(subjectId: string): Promise { const now = new Date().toISOString(); const certificateHash = crypto .createHash('sha256') .update(`ERASURE:${subjectId}:${now}`) .digest('hex'); return { subjectId, action: 'PURGED_AND_ANONYMIZED', executedAt: now, certificateHash, }; } }