[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7FESBE044Y7CKYN2NZCBZ1Q":3,"skill-same:01M7FESBE044Y7CKYN2NZCBZ1Q":46},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":6,"ownerDescription":30,"updatedAt":31,"install":32,"resources":45},"01M7FESBE044Y7CKYN2NZCBZ1Q","gdpr-data-handling",null,"Implement GDPR-compliant data handling with consent management, data subject rights, and privacy by design. Use when building systems that process EU personal data, implementing privacy controls, or conducting GDPR compliance reviews.","lza6\u002FArmor-piercing-system-prompts","lza6","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F128880206?v=4","01M7EB3K7WPX5T28EJ2NVHE6EG","Chinese-tingfeng","01M7EB3K97E1KQ16QWKJMFNGX8",11,"MIT","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fgdpr-data-handling-agents-main\u002FSKILL.md",[],[],"2026-11-16 10:05:34",false,"---\nname: gdpr-data-handling\ndescription: Implement GDPR-compliant data handling with consent management, data subject rights, and privacy by design. Use when building systems that process EU personal data, implementing privacy controls, or conducting GDPR compliance reviews.\n---\n\n# GDPR Data Handling\n\nPractical implementation guide for GDPR-compliant data processing, consent management, and privacy controls.\n\n## When to Use This Skill\n\n- Building systems that process EU personal data\n- Implementing consent management\n- Handling data subject requests (DSRs)\n- Conducting GDPR compliance reviews\n- Designing privacy-first architectures\n- Creating data processing agreements\n\n## Core Concepts\n\n### 1. Personal Data Categories\n\n| Category               | Examples                    | Protection Level   |\n| ---------------------- | --------------------------- | ------------------ |\n| **Basic**              | Name, email, phone          | Standard           |\n| **Sensitive (Art. 9)** | Health, religion, ethnicity | Explicit consent   |\n| **Criminal (Art. 10)** | Convictions, offenses       | Official authority |\n| **Children's**         | Under 16 data               | Parental consent   |\n\n### 2. Legal Bases for Processing\n\n```\nArticle 6 - Lawful Bases:\n├── Consent: Freely given, specific, informed\n├── Contract: Necessary for contract performance\n├── Legal Obligation: Required by law\n├── Vital Interests: Protecting someone's life\n├── Public Interest: Official functions\n└── Legitimate Interest: Balanced against rights\n```\n\n### 3. Data Subject Rights\n\n```\nRight to Access (Art. 15)      ─┐\nRight to Rectification (Art. 16) │\nRight to Erasure (Art. 17)       │ Must respond\nRight to Restrict (Art. 18)      │ within 1 month\nRight to Portability (Art. 20)   │\nRight to Object (Art. 21)       ─┘\n```\n\n## Implementation Patterns\n\n### Pattern 1: Consent Management\n\n```javascript\n\u002F\u002F Consent data model\nconst consentSchema = {\n  userId: String,\n  consents: [\n    {\n      purpose: String, \u002F\u002F 'marketing', 'analytics', etc.\n      granted: Boolean,\n      timestamp: Date,\n      source: String, \u002F\u002F 'web_form', 'api', etc.\n      version: String, \u002F\u002F Privacy policy version\n      ipAddress: String, \u002F\u002F For proof\n      userAgent: String, \u002F\u002F For proof\n    },\n  ],\n  auditLog: [\n    {\n      action: String, \u002F\u002F 'granted', 'withdrawn', 'updated'\n      purpose: String,\n      timestamp: Date,\n      source: String,\n    },\n  ],\n};\n\n\u002F\u002F Consent service\nclass ConsentManager {\n  async recordConsent(userId, purpose, granted, metadata) {\n    const consent = {\n      purpose,\n      granted,\n      timestamp: new Date(),\n      source: metadata.source,\n      version: await this.getCurrentPolicyVersion(),\n      ipAddress: metadata.ipAddress,\n      userAgent: metadata.userAgent,\n    };\n\n    \u002F\u002F Store consent\n    await this.db.consents.updateOne(\n      { userId },\n      {\n        $push: {\n          consents: consent,\n          auditLog: {\n            action: granted ? \"granted\" : \"withdrawn\",\n            purpose,\n            timestamp: consent.timestamp,\n            source: metadata.source,\n          },\n        },\n      },\n      { upsert: true },\n    );\n\n    \u002F\u002F Emit event for downstream systems\n    await this.eventBus.emit(\"consent.changed\", {\n      userId,\n      purpose,\n      granted,\n      timestamp: consent.timestamp,\n    });\n  }\n\n  async hasConsent(userId, purpose) {\n    const record = await this.db.consents.findOne({ userId });\n    if (!record) return false;\n\n    const latestConsent = record.consents\n      .filter((c) => c.purpose === purpose)\n      .sort((a, b) => b.timestamp - a.timestamp)[0];\n\n    return latestConsent?.granted === true;\n  }\n\n  async getConsentHistory(userId) {\n    const record = await this.db.consents.findOne({ userId });\n    return record?.auditLog || [];\n  }\n}\n```\n\n```html\n\u003C!-- GDPR-compliant consent UI -->\n\u003Cdiv class=\"consent-banner\" role=\"dialog\" aria-labelledby=\"consent-title\">\n  \u003Ch2 id=\"consent-title\">Cookie Preferences\u003C\u002Fh2>\n\n  \u003Cp>\n    We use cookies to improve your experience. Select your preferences below.\n  \u003C\u002Fp>\n\n  \u003Cform id=\"consent-form\">\n    \u003C!-- Necessary - always on, no consent needed -->\n    \u003Cdiv class=\"consent-category\">\n      \u003Cinput type=\"checkbox\" id=\"necessary\" checked disabled \u002F>\n      \u003Clabel for=\"necessary\">\n        \u003Cstrong>Necessary\u003C\u002Fstrong>\n        \u003Cspan>Required for the website to function. Cannot be disabled.\u003C\u002Fspan>\n      \u003C\u002Flabel>\n    \u003C\u002Fdiv>\n\n    \u003C!-- Analytics - requires consent -->\n    \u003Cdiv class=\"consent-category\">\n      \u003Cinput type=\"checkbox\" id=\"analytics\" name=\"analytics\" \u002F>\n      \u003Clabel for=\"analytics\">\n        \u003Cstrong>Analytics\u003C\u002Fstrong>\n        \u003Cspan>Help us understand how you use our site.\u003C\u002Fspan>\n      \u003C\u002Flabel>\n    \u003C\u002Fdiv>\n\n    \u003C!-- Marketing - requires consent -->\n    \u003Cdiv class=\"consent-category\">\n      \u003Cinput type=\"checkbox\" id=\"marketing\" name=\"marketing\" \u002F>\n      \u003Clabel for=\"marketing\">\n        \u003Cstrong>Marketing\u003C\u002Fstrong>\n        \u003Cspan>Personalized ads based on your interests.\u003C\u002Fspan>\n      \u003C\u002Flabel>\n    \u003C\u002Fdiv>\n\n    \u003Cdiv class=\"consent-actions\">\n      \u003Cbutton type=\"button\" id=\"accept-all\">Accept All\u003C\u002Fbutton>\n      \u003Cbutton type=\"button\" id=\"reject-all\">Reject All\u003C\u002Fbutton>\n      \u003Cbutton type=\"submit\">Save Preferences\u003C\u002Fbutton>\n    \u003C\u002Fdiv>\n\n    \u003Cp class=\"consent-links\">\n      \u003Ca href=\"\u002Fprivacy-policy\">Privacy Policy\u003C\u002Fa> |\n      \u003Ca href=\"\u002Fcookie-policy\">Cookie Policy\u003C\u002Fa>\n    \u003C\u002Fp>\n  \u003C\u002Fform>\n\u003C\u002Fdiv>\n```\n\n### Pattern 2: Data Subject Access Request (DSAR)\n\n```python\nfrom datetime import datetime, timedelta\nfrom typing import Dict, List, Optional\nimport json\n\nclass DSARHandler:\n    \"\"\"Handle Data Subject Access Requests.\"\"\"\n\n    RESPONSE_DEADLINE_DAYS = 30\n    EXTENSION_ALLOWED_DAYS = 60  # For complex requests\n\n    def __init__(self, data_sources: List['DataSource']):\n        self.data_sources = data_sources\n\n    async def submit_request(\n        self,\n        request_type: str,  # 'access', 'erasure', 'rectification', 'portability'\n        user_id: str,\n        verified: bool,\n        details: Optional[Dict] = None\n    ) -> str:\n        \"\"\"Submit a new DSAR.\"\"\"\n        request = {\n            'id': self.generate_request_id(),\n            'type': request_type,\n            'user_id': user_id,\n            'status': 'pending_verification' if not verified else 'processing',\n            'submitted_at': datetime.utcnow(),\n            'deadline': datetime.utcnow() + timedelta(days=self.RESPONSE_DEADLINE_DAYS),\n            'details': details or {},\n            'audit_log': [{\n                'action': 'submitted',\n                'timestamp': datetime.utcnow(),\n                'details': 'Request received'\n            }]\n        }\n\n        await self.db.dsar_requests.insert_one(request)\n        await self.notify_dpo(request)\n\n        return request['id']\n\n    async def process_access_request(self, request_id: str) -> Dict:\n        \"\"\"Process a data access request.\"\"\"\n        request = await self.get_request(request_id)\n\n        if request['type'] != 'access':\n            raise ValueError(\"Not an access request\")\n\n        # Collect data from all sources\n        user_data = {}\n        for source in self.data_sources:\n            try:\n                data = await source.get_user_data(request['user_id'])\n                user_data[source.name] = data\n            except Exception as e:\n                user_data[source.name] = {'error': str(e)}\n\n        # Format response\n        response = {\n            'request_id': request_id,\n            'generated_at': datetime.utcnow().isoformat(),\n            'data_categories': list(user_data.keys()),\n            'data': user_data,\n            'retention_info': await self.get_retention_info(),\n            'processing_purposes': await self.get_processing_purposes(),\n            'third_party_recipients': await self.get_recipients()\n        }\n\n        # Update request status\n        await self.update_request(request_id, 'completed', response)\n\n        return response\n\n    async def process_erasure_request(self, request_id: str) -> Dict:\n        \"\"\"Process a right to erasure request.\"\"\"\n        request = await self.get_request(request_id)\n\n        if request['type'] != 'erasure':\n            raise ValueError(\"Not an erasure request\")\n\n        results = {}\n        exceptions = []\n\n        for source in self.data_sources:\n            try:\n                # Check for legal exceptions\n                can_delete, reason = await source.can_delete(request['user_id'])\n\n                if can_delete:\n                    await source.delete_user_data(request['user_id'])\n                    results[source.name] = 'deleted'\n                else:\n                    exceptions.append({\n                        'source': source.name,\n                        'reason': reason  # e.g., 'legal retention requirement'\n                    })\n                    results[source.name] = f'retained: {reason}'\n            except Exception as e:\n                results[source.name] = f'error: {str(e)}'\n\n        response = {\n            'request_id': request_id,\n            'completed_at': datetime.utcnow().isoformat(),\n            'results': results,\n            'exceptions': exceptions\n        }\n\n        await self.update_request(request_id, 'completed', response)\n\n        return response\n\n    async def process_portability_request(self, request_id: str) -> bytes:\n        \"\"\"Generate portable data export.\"\"\"\n        request = await self.get_request(request_id)\n        user_data = await self.process_access_request(request_id)\n\n        # Convert to machine-readable format (JSON)\n        portable_data = {\n            'export_date': datetime.utcnow().isoformat(),\n            'format_version': '1.0',\n            'data': user_data['data']\n        }\n\n        return json.dumps(portable_data, indent=2, default=str).encode()\n```\n\n### Pattern 3: Data Retention\n\n```python\nfrom datetime import datetime, timedelta\nfrom enum import Enum\n\nclass RetentionBasis(Enum):\n    CONSENT = \"consent\"\n    CONTRACT = \"contract\"\n    LEGAL_OBLIGATION = \"legal_obligation\"\n    LEGITIMATE_INTEREST = \"legitimate_interest\"\n\nclass DataRetentionPolicy:\n    \"\"\"Define and enforce data retention policies.\"\"\"\n\n    POLICIES = {\n        'user_account': {\n            'retention_period_days': 365 * 3,  # 3 years after last activity\n            'basis': RetentionBasis.CONTRACT,\n            'trigger': 'last_activity_date',\n            'archive_before_delete': True\n        },\n        'transaction_records': {\n            'retention_period_days': 365 * 7,  # 7 years for tax\n            'basis': RetentionBasis.LEGAL_OBLIGATION,\n            'trigger': 'transaction_date',\n            'archive_before_delete': True,\n            'legal_reference': 'Tax regulations require 7 year retention'\n        },\n        'marketing_consent': {\n            'retention_period_days': 365 * 2,  # 2 years\n            'basis': RetentionBasis.CONSENT,\n            'trigger': 'consent_date',\n            'archive_before_delete': False\n        },\n        'support_tickets': {\n            'retention_period_days': 365 * 2,\n            'basis': RetentionBasis.LEGITIMATE_INTEREST,\n            'trigger': 'ticket_closed_date',\n            'archive_before_delete': True\n        },\n        'analytics_data': {\n            'retention_period_days': 365,  # 1 year\n            'basis': RetentionBasis.CONSENT,\n            'trigger': 'collection_date',\n            'archive_before_delete': False,\n            'anonymize_instead': True\n        }\n    }\n\n    async def apply_retention_policies(self):\n        \"\"\"Run retention policy enforcement.\"\"\"\n        for data_type, policy in self.POLICIES.items():\n            cutoff_date = datetime.utcnow() - timedelta(\n                days=policy['retention_period_days']\n            )\n\n            if policy.get('anonymize_instead'):\n                await self.anonymize_old_data(data_type, cutoff_date)\n            else:\n                if policy.get('archive_before_delete'):\n                    await self.archive_data(data_type, cutoff_date)\n                await self.delete_old_data(data_type, cutoff_date)\n\n            await self.log_retention_action(data_type, cutoff_date)\n\n    async def anonymize_old_data(self, data_type: str, before_date: datetime):\n        \"\"\"Anonymize data instead of deleting.\"\"\"\n        # Example: Replace identifying fields with hashes\n        if data_type == 'analytics_data':\n            await self.db.analytics.update_many(\n                {'collection_date': {'$lt': before_date}},\n                {'$set': {\n                    'user_id': None,\n                    'ip_address': None,\n                    'device_id': None,\n                    'anonymized': True,\n                    'anonymized_date': datetime.utcnow()\n                }}\n            )\n```\n\n### Pattern 4: Privacy by Design\n\n```python\nclass PrivacyFirstDataModel:\n    \"\"\"Example of privacy-by-design data model.\"\"\"\n\n    # Separate PII from behavioral data\n    user_profile_schema = {\n        'user_id': str,  # UUID, not sequential\n        'email_hash': str,  # Hashed for lookups\n        'created_at': datetime,\n        # Minimal data collection\n        'preferences': {\n            'language': str,\n            'timezone': str\n        }\n    }\n\n    # Encrypted at rest\n    user_pii_schema = {\n        'user_id': str,\n        'email': str,  # Encrypted\n        'name': str,   # Encrypted\n        'phone': str,  # Encrypted (optional)\n        'address': dict,  # Encrypted (optional)\n        'encryption_key_id': str\n    }\n\n    # Pseudonymized behavioral data\n    analytics_schema = {\n        'session_id': str,  # Not linked to user_id\n        'pseudonym_id': str,  # Rotating pseudonym\n        'events': list,\n        'device_category': str,  # Generalized, not specific\n        'country': str,  # Not city-level\n    }\n\nclass DataMinimization:\n    \"\"\"Implement data minimization principles.\"\"\"\n\n    @staticmethod\n    def collect_only_needed(form_data: dict, purpose: str) -> dict:\n        \"\"\"Filter form data to only fields needed for purpose.\"\"\"\n        REQUIRED_FIELDS = {\n            'account_creation': ['email', 'password'],\n            'newsletter': ['email'],\n            'purchase': ['email', 'name', 'address', 'payment'],\n            'support': ['email', 'message']\n        }\n\n        allowed = REQUIRED_FIELDS.get(purpose, [])\n        return {k: v for k, v in form_data.items() if k in allowed}\n\n    @staticmethod\n    def generalize_location(ip_address: str) -> str:\n        \"\"\"Generalize IP to country level only.\"\"\"\n        import geoip2.database\n        reader = geoip2.database.Reader('GeoLite2-Country.mmdb')\n        try:\n            response = reader.country(ip_address)\n            return response.country.iso_code\n        except:\n            return 'UNKNOWN'\n```\n\n### Pattern 5: Breach Notification\n\n```python\nfrom datetime import datetime\nfrom enum import Enum\n\nclass BreachSeverity(Enum):\n    LOW = \"low\"\n    MEDIUM = \"medium\"\n    HIGH = \"high\"\n    CRITICAL = \"critical\"\n\nclass BreachNotificationHandler:\n    \"\"\"Handle GDPR breach notification requirements.\"\"\"\n\n    AUTHORITY_NOTIFICATION_HOURS = 72\n    AFFECTED_NOTIFICATION_REQUIRED_SEVERITY = BreachSeverity.HIGH\n\n    async def report_breach(\n        self,\n        description: str,\n        data_types: List[str],\n        affected_count: int,\n        severity: BreachSeverity\n    ) -> dict:\n        \"\"\"Report and handle a data breach.\"\"\"\n        breach = {\n            'id': self.generate_breach_id(),\n            'reported_at': datetime.utcnow(),\n            'description': description,\n            'data_types_affected': data_types,\n            'affected_individuals_count': affected_count,\n            'severity': severity.value,\n            'status': 'investigating',\n            'timeline': [{\n                'event': 'breach_reported',\n                'timestamp': datetime.utcnow(),\n                'details': description\n            }]\n        }\n\n        await self.db.breaches.insert_one(breach)\n\n        # Immediate notifications\n        await self.notify_dpo(breach)\n        await self.notify_security_team(breach)\n\n        # Authority notification required within 72 hours\n        if self.requires_authority_notification(severity, data_types):\n            breach['authority_notification_deadline'] = (\n                datetime.utcnow() + timedelta(hours=self.AUTHORITY_NOTIFICATION_HOURS)\n            )\n            await self.schedule_authority_notification(breach)\n\n        # Affected individuals notification\n        if severity.value in [BreachSeverity.HIGH.value, BreachSeverity.CRITICAL.value]:\n            await self.schedule_individual_notifications(breach)\n\n        return breach\n\n    def requires_authority_notification(\n        self,\n        severity: BreachSeverity,\n        data_types: List[str]\n    ) -> bool:\n        \"\"\"Determine if supervisory authority must be notified.\"\"\"\n        # Always notify for sensitive data\n        sensitive_types = ['health', 'financial', 'credentials', 'biometric']\n        if any(t in sensitive_types for t in data_types):\n            return True\n\n        # Notify for medium+ severity\n        return severity in [BreachSeverity.MEDIUM, BreachSeverity.HIGH, BreachSeverity.CRITICAL]\n\n    async def generate_authority_report(self, breach_id: str) -> dict:\n        \"\"\"Generate report for supervisory authority.\"\"\"\n        breach = await self.get_breach(breach_id)\n\n        return {\n            'organization': {\n                'name': self.config.org_name,\n                'contact': self.config.dpo_contact,\n                'registration': self.config.registration_number\n            },\n            'breach': {\n                'nature': breach['description'],\n                'categories_affected': breach['data_types_affected'],\n                'approximate_number_affected': breach['affected_individuals_count'],\n                'likely_consequences': self.assess_consequences(breach),\n                'measures_taken': await self.get_remediation_measures(breach_id),\n                'measures_proposed': await self.get_proposed_measures(breach_id)\n            },\n            'timeline': breach['timeline'],\n            'submitted_at': datetime.utcnow().isoformat()\n        }\n```\n\n## Compliance Checklist\n\n```markdown\n## GDPR Implementation Checklist\n\n### Legal Basis\n\n- [ ] Documented legal basis for each processing activity\n- [ ] Consent mechanisms meet GDPR requirements\n- [ ] Legitimate interest assessments completed\n\n### Transparency\n\n- [ ] Privacy policy is clear and accessible\n- [ ] Processing purposes clearly stated\n- [ ] Data retention periods documented\n\n### Data Subject Rights\n\n- [ ] Access request process implemented\n- [ ] Erasure request process implemented\n- [ ] Portability export available\n- [ ] Rectification process available\n- [ ] Response within 30-day deadline\n\n### Security\n\n- [ ] Encryption at rest implemented\n- [ ] Encryption in transit (TLS)\n- [ ] Access controls in place\n- [ ] Audit logging enabled\n\n### Breach Response\n\n- [ ] Breach detection mechanisms\n- [ ] 72-hour notification process\n- [ ] Breach documentation system\n\n### Documentation\n\n- [ ] Records of processing activities (Art. 30)\n- [ ] Data protection impact assessments\n- [ ] Data processing agreements with vendors\n```\n\n## Best Practices\n\n### Do's\n\n- **Minimize data collection** - Only collect what's needed\n- **Document everything** - Processing activities, legal bases\n- **Encrypt PII** - At rest and in transit\n- **Implement access controls** - Need-to-know basis\n- **Regular audits** - Verify compliance continuously\n\n### Don'ts\n\n- **Don't pre-check consent boxes** - Must be opt-in\n- **Don't bundle consent** - Separate purposes separately\n- **Don't retain indefinitely** - Define and enforce retention\n- **Don't ignore DSARs** - 30-day response required\n- **Don't transfer without safeguards** - SCCs or adequacy decisions\n","# GDPR Data Handling\n\nPractical implementation guide for GDPR-compliant data processing, consent management, and privacy controls.\n\n## When to Use This Skill\n\n- Building systems that process EU personal data\n- Implementing consent management\n- Handling data subject requests (DSRs)\n- Conducting GDPR compliance reviews\n- Designing privacy-first architectures\n- Creating data processing agreements\n\n## Core Concepts\n\n### 1. Personal Data Categories\n\n| Category               | Examples                    | Protection Level   |\n| ---------------------- | --------------------------- | ------------------ |\n| **Basic**              | Name, email, phone          | Standard           |\n| **Sensitive (Art. 9)** | Health, religion, ethnicity | Explicit consent   |\n| **Criminal (Art. 10)** | Convictions, offenses       | Official authority |\n| **Children's**         | Under 16 data               | Parental consent   |\n\n### 2. Legal Bases for Processing\n\n```\nArticle 6 - Lawful Bases:\n├── Consent: Freely given, specific, informed\n├── Contract: Necessary for contract performance\n├── Legal Obligation: Required by law\n├── Vital Interests: Protecting someone's life\n├── Public Interest: Official functions\n└── Legitimate Interest: Balanced against rights\n```\n\n### 3. Data Subject Rights\n\n```\nRight to Access (Art. 15)      ─┐\nRight to Rectification (Art. 16) │\nRight to Erasure (Art. 17)       │ Must respond\nRight to Restrict (Art. 18)      │ within 1 month\nRight to Portability (Art. 20)   │\nRight to Object (Art. 21)       ─┘\n```\n\n## Implementation Patterns\n\n### Pattern 1: Consent Management\n\n```javascript\n\u002F\u002F Consent data model\nconst consentSchema = {\n  userId: String,\n  consents: [\n    {\n      purpose: String, \u002F\u002F 'marketing', 'analytics', etc.\n      granted: Boolean,\n      timestamp: Date,\n      source: String, \u002F\u002F 'web_form', 'api', etc.\n      version: String, \u002F\u002F Privacy policy version\n      ipAddress: String, \u002F\u002F For proof\n      userAgent: String, \u002F\u002F For proof\n    },\n  ],\n  auditLog: [\n    {\n      action: String, \u002F\u002F 'granted', 'withdrawn', 'updated'\n      purpose: String,\n      timestamp: Date,\n      source: String,\n    },\n  ],\n};\n\n\u002F\u002F Consent service\nclass ConsentManager {\n  async recordConsent(userId, purpose, granted, metadata) {\n    const consent = {\n      purpose,\n      granted,\n      timestamp: new Date(),\n      source: metadata.source,\n      version: await this.getCurrentPolicyVersion(),\n      ipAddress: metadata.ipAddress,\n      userAgent: metadata.userAgent,\n    };\n\n    \u002F\u002F Store consent\n    await this.db.consents.updateOne(\n      { userId },\n      {\n        $push: {\n          consents: consent,\n          auditLog: {\n            action: granted ? \"granted\" : \"withdrawn\",\n            purpose,\n            timestamp: consent.timestamp,\n            source: metadata.source,\n          },\n        },\n      },\n      { upsert: true },\n    );\n\n    \u002F\u002F Emit event for downstream systems\n    await this.eventBus.emit(\"consent.changed\", {\n      userId,\n      purpose,\n      granted,\n      timestamp: consent.timestamp,\n    });\n  }\n\n  async hasConsent(userId, purpose) {\n    const record = await this.db.consents.findOne({ userId });\n    if (!record) return false;\n\n    const latestConsent = record.consents\n      .filter((c) => c.purpose === purpose)\n      .sort((a, b) => b.timestamp - a.timestamp)[0];\n\n    return latestConsent?.granted === true;\n  }\n\n  async getConsentHistory(userId) {\n    const record = await this.db.consents.findOne({ userId });\n    return record?.auditLog || [];\n  }\n}\n```\n\n```html\n\u003C!-- GDPR-compliant consent UI -->\n\u003Cdiv class=\"consent-banner\" role=\"dialog\" aria-labelledby=\"consent-title\">\n  \u003Ch2 id=\"consent-title\">Cookie Preferences\u003C\u002Fh2>\n\n  \u003Cp>\n    We use cookies to improve your experience. Select your preferences below.\n  \u003C\u002Fp>\n\n  \u003Cform id=\"consent-form\">\n    \u003C!-- Necessary - always on, no consent needed -->\n    \u003Cdiv class=\"consent-category\">\n      \u003Cinput type=\"checkbox\" id=\"necessary\" checked disabled \u002F>\n      \u003Clabel for=\"necessary\">\n        \u003Cstrong>Necessary\u003C\u002Fstrong>\n        \u003Cspan>Required for the website to function. Cannot be disabled.\u003C\u002Fspan>\n      \u003C\u002Flabel>\n    \u003C\u002Fdiv>\n\n    \u003C!-- Analytics - requires consent -->\n    \u003Cdiv class=\"consent-category\">\n      \u003Cinput type=\"checkbox\" id=\"analytics\" name=\"analytics\" \u002F>\n      \u003Clabel for=\"analytics\">\n        \u003Cstrong>Analytics\u003C\u002Fstrong>\n        \u003Cspan>Help us understand how you use our site.\u003C\u002Fspan>\n      \u003C\u002Flabel>\n    \u003C\u002Fdiv>\n\n    \u003C!-- Marketing - requires consent -->\n    \u003Cdiv class=\"consent-category\">\n      \u003Cinput type=\"checkbox\" id=\"marketing\" name=\"marketing\" \u002F>\n      \u003Clabel for=\"marketing\">\n        \u003Cstrong>Marketing\u003C\u002Fstrong>\n        \u003Cspan>Personalized ads based on your interests.\u003C\u002Fspan>\n      \u003C\u002Flabel>\n    \u003C\u002Fdiv>\n\n    \u003Cdiv class=\"consent-actions\">\n      \u003Cbutton type=\"button\" id=\"accept-all\">Accept All\u003C\u002Fbutton>\n      \u003Cbutton type=\"button\" id=\"reject-all\">Reject All\u003C\u002Fbutton>\n      \u003Cbutton type=\"submit\">Save Preferences\u003C\u002Fbutton>\n    \u003C\u002Fdiv>\n\n    \u003Cp class=\"consent-links\">\n      \u003Ca href=\"\u002Fprivacy-policy\">Privacy Policy\u003C\u002Fa> |\n      \u003Ca href=\"\u002Fcookie-policy\">Cookie Policy\u003C\u002Fa>\n    \u003C\u002Fp>\n  \u003C\u002Fform>\n\u003C\u002Fdiv>\n```\n\n### Pattern 2: Data Subject Access Request (DSAR)\n\n```python\nfrom datetime import datetime, timedelta\nfrom typing import Dict, List, Optional\nimport json\n\nclass DSARHandler:\n    \"\"\"Handle Data Subject Access Requests.\"\"\"\n\n    RESPONSE_DEADLINE_DAYS = 30\n    EXTENSION_ALLOWED_DAYS = 60  # For complex requests\n\n    def __init__(self, data_sources: List['DataSource']):\n        self.data_sources = data_sources\n\n    async def submit_request(\n        self,\n        request_type: str,  # 'access', 'erasure', 'rectification', 'portability'\n        user_id: str,\n        verified: bool,\n        details: Optional[Dict] = None\n    ) -> str:\n        \"\"\"Submit a new DSAR.\"\"\"\n        request = {\n            'id': self.generate_request_id(),\n            'type': request_type,\n            'user_id': user_id,\n            'status': 'pending_verification' if not verified else 'processing',\n            'submitted_at': datetime.utcnow(),\n            'deadline': datetime.utcnow() + timedelta(days=self.RESPONSE_DEADLINE_DAYS),\n            'details': details or {},\n            'audit_log': [{\n                'action': 'submitted',\n                'timestamp': datetime.utcnow(),\n                'details': 'Request received'\n            }]\n        }\n\n        await self.db.dsar_requests.insert_one(request)\n        await self.notify_dpo(request)\n\n        return request['id']\n\n    async def process_access_request(self, request_id: str) -> Dict:\n        \"\"\"Process a data access request.\"\"\"\n        request = await self.get_request(request_id)\n\n        if request['type'] != 'access':\n            raise ValueError(\"Not an access request\")\n\n        # Collect data from all sources\n        user_data = {}\n        for source in self.data_sources:\n            try:\n                data = await source.get_user_data(request['user_id'])\n                user_data[source.name] = data\n            except Exception as e:\n                user_data[source.name] = {'error': str(e)}\n\n        # Format response\n        response = {\n            'request_id': request_id,\n            'generated_at': datetime.utcnow().isoformat(),\n            'data_categories': list(user_data.keys()),\n            'data': user_data,\n            'retention_info': await self.get_retention_info(),\n            'processing_purposes': await self.get_processing_purposes(),\n            'third_party_recipients': await self.get_recipients()\n        }\n\n        # Update request status\n        await self.update_request(request_id, 'completed', response)\n\n        return response\n\n    async def process_erasure_request(self, request_id: str) -> Dict:\n        \"\"\"Process a right to erasure request.\"\"\"\n        request = await self.get_request(request_id)\n\n        if request['type'] != 'erasure':\n            raise ValueError(\"Not an erasure request\")\n\n        results = {}\n        exceptions = []\n\n        for source in self.data_sources:\n            try:\n                # Check for legal exceptions\n                can_delete, reason = await source.can_delete(request['user_id'])\n\n                if can_delete:\n                    await source.delete_user_data(request['user_id'])\n                    results[source.name] = 'deleted'\n                else:\n                    exceptions.append({\n                        'source': source.name,\n                        'reason': reason  # e.g., 'legal retention requirement'\n                    })\n                    results[source.name] = f'retained: {reason}'\n            except Exception as e:\n                results[source.name] = f'error: {str(e)}'\n\n        response = {\n            'request_id': request_id,\n            'completed_at': datetime.utcnow().isoformat(),\n            'results': results,\n            'exceptions': exceptions\n        }\n\n        await self.update_request(request_id, 'completed', response)\n\n        return response\n\n    async def process_portability_request(self, request_id: str) -> bytes:\n        \"\"\"Generate portable data export.\"\"\"\n        request = await self.get_request(request_id)\n        user_data = await self.process_access_request(request_id)\n\n        # Convert to machine-readable format (JSON)\n        portable_data = {\n            'export_date': datetime.utcnow().isoformat(),\n            'format_version': '1.0',\n            'data': user_data['data']\n        }\n\n        return json.dumps(portable_data, indent=2, default=str).encode()\n```\n\n### Pattern 3: Data Retention\n\n```python\nfrom datetime import datetime, timedelta\nfrom enum import Enum\n\nclass RetentionBasis(Enum):\n    CONSENT = \"consent\"\n    CONTRACT = \"contract\"\n    LEGAL_OBLIGATION = \"legal_obligation\"\n    LEGITIMATE_INTEREST = \"legitimate_interest\"\n\nclass DataRetentionPolicy:\n    \"\"\"Define and enforce data retention policies.\"\"\"\n\n    POLICIES = {\n        'user_account': {\n            'retention_period_days': 365 * 3,  # 3 years after last activity\n            'basis': RetentionBasis.CONTRACT,\n            'trigger': 'last_activity_date',\n            'archive_before_delete': True\n        },\n        'transaction_records': {\n            'retention_period_days': 365 * 7,  # 7 years for tax\n            'basis': RetentionBasis.LEGAL_OBLIGATION,\n            'trigger': 'transaction_date',\n            'archive_before_delete': True,\n            'legal_reference': 'Tax regulations require 7 year retention'\n        },\n        'marketing_consent': {\n            'retention_period_days': 365 * 2,  # 2 years\n            'basis': RetentionBasis.CONSENT,\n            'trigger': 'consent_date',\n            'archive_before_delete': False\n        },\n        'support_tickets': {\n            'retention_period_days': 365 * 2,\n            'basis': RetentionBasis.LEGITIMATE_INTEREST,\n            'trigger': 'ticket_closed_date',\n            'archive_before_delete': True\n        },\n        'analytics_data': {\n            'retention_period_days': 365,  # 1 year\n            'basis': RetentionBasis.CONSENT,\n            'trigger': 'collection_date',\n            'archive_before_delete': False,\n            'anonymize_instead': True\n        }\n    }\n\n    async def apply_retention_policies(self):\n        \"\"\"Run retention policy enforcement.\"\"\"\n        for data_type, policy in self.POLICIES.items():\n            cutoff_date = datetime.utcnow() - timedelta(\n                days=policy['retention_period_days']\n            )\n\n            if policy.get('anonymize_instead'):\n                await self.anonymize_old_data(data_type, cutoff_date)\n            else:\n                if policy.get('archive_before_delete'):\n                    await self.archive_data(data_type, cutoff_date)\n                await self.delete_old_data(data_type, cutoff_date)\n\n            await self.log_retention_action(data_type, cutoff_date)\n\n    async def anonymize_old_data(self, data_type: str, before_date: datetime):\n        \"\"\"Anonymize data instead of deleting.\"\"\"\n        # Example: Replace identifying fields with hashes\n        if data_type == 'analytics_data':\n            await self.db.analytics.update_many(\n                {'collection_date': {'$lt': before_date}},\n                {'$set': {\n                    'user_id': None,\n                    'ip_address': None,\n                    'device_id': None,\n                    'anonymized': True,\n                    'anonymized_date': datetime.utcnow()\n                }}\n            )\n```\n\n### Pattern 4: Privacy by Design\n\n```python\nclass PrivacyFirstDataModel:\n    \"\"\"Example of privacy-by-design data model.\"\"\"\n\n    # Separate PII from behavioral data\n    user_profile_schema = {\n        'user_id': str,  # UUID, not sequential\n        'email_hash': str,  # Hashed for lookups\n        'created_at': datetime,\n        # Minimal data collection\n        'preferences': {\n            'language': str,\n            'timezone': str\n        }\n    }\n\n    # Encrypted at rest\n    user_pii_schema = {\n        'user_id': str,\n        'email': str,  # Encrypted\n        'name': str,   # Encrypted\n        'phone': str,  # Encrypted (optional)\n        'address': dict,  # Encrypted (optional)\n        'encryption_key_id': str\n    }\n\n    # Pseudonymized behavioral data\n    analytics_schema = {\n        'session_id': str,  # Not linked to user_id\n        'pseudonym_id': str,  # Rotating pseudonym\n        'events': list,\n        'device_category': str,  # Generalized, not specific\n        'country': str,  # Not city-level\n    }\n\nclass DataMinimization:\n    \"\"\"Implement data minimization principles.\"\"\"\n\n    @staticmethod\n    def collect_only_needed(form_data: dict, purpose: str) -> dict:\n        \"\"\"Filter form data to only fields needed for purpose.\"\"\"\n        REQUIRED_FIELDS = {\n            'account_creation': ['email', 'password'],\n            'newsletter': ['email'],\n            'purchase': ['email', 'name', 'address', 'payment'],\n            'support': ['email', 'message']\n        }\n\n        allowed = REQUIRED_FIELDS.get(purpose, [])\n        return {k: v for k, v in form_data.items() if k in allowed}\n\n    @staticmethod\n    def generalize_location(ip_address: str) -> str:\n        \"\"\"Generalize IP to country level only.\"\"\"\n        import geoip2.database\n        reader = geoip2.database.Reader('GeoLite2-Country.mmdb')\n        try:\n            response = reader.country(ip_address)\n            return response.country.iso_code\n        except:\n            return 'UNKNOWN'\n```\n\n### Pattern 5: Breach Notification\n\n```python\nfrom datetime import datetime\nfrom enum import Enum\n\nclass BreachSeverity(Enum):\n    LOW = \"low\"\n    MEDIUM = \"medium\"\n    HIGH = \"high\"\n    CRITICAL = \"critical\"\n\nclass BreachNotificationHandler:\n    \"\"\"Handle GDPR breach notification requirements.\"\"\"\n\n    AUTHORITY_NOTIFICATION_HOURS = 72\n    AFFECTED_NOTIFICATION_REQUIRED_SEVERITY = BreachSeverity.HIGH\n\n    async def report_breach(\n        self,\n        description: str,\n        data_types: List[str],\n        affected_count: int,\n        severity: BreachSeverity\n    ) -> dict:\n        \"\"\"Report and handle a data breach.\"\"\"\n        breach = {\n            'id': self.generate_breach_id(),\n            'reported_at': datetime.utcnow(),\n            'description': description,\n            'data_types_affected': data_types,\n            'affected_individuals_count': affected_count,\n            'severity': severity.value,\n            'status': 'investigating',\n            'timeline': [{\n                'event': 'breach_reported',\n                'timestamp': datetime.utcnow(),\n                'details': description\n            }]\n        }\n\n        await self.db.breaches.insert_one(breach)\n\n        # Immediate notifications\n        await self.notify_dpo(breach)\n        await self.notify_security_team(breach)\n\n        # Authority notification required within 72 hours\n        if self.requires_authority_notification(severity, data_types):\n            breach['authority_notification_deadline'] = (\n                datetime.utcnow() + timedelta(hours=self.AUTHORITY_NOTIFICATION_HOURS)\n            )\n            await self.schedule_authority_notification(breach)\n\n        # Affected individuals notification\n        if severity.value in [BreachSeverity.HIGH.value, BreachSeverity.CRITICAL.value]:\n            await self.schedule_individual_notifications(breach)\n\n        return breach\n\n    def requires_authority_notification(\n        self,\n        severity: BreachSeverity,\n        data_types: List[str]\n    ) -> bool:\n        \"\"\"Determine if supervisory authority must be notified.\"\"\"\n        # Always notify for sensitive data\n        sensitive_types = ['health', 'financial', 'credentials', 'biometric']\n        if any(t in sensitive_types for t in data_types):\n            return True\n\n        # Notify for medium+ severity\n        return severity in [BreachSeverity.MEDIUM, BreachSeverity.HIGH, BreachSeverity.CRITICAL]\n\n    async def generate_authority_report(self, breach_id: str) -> dict:\n        \"\"\"Generate report for supervisory authority.\"\"\"\n        breach = await self.get_breach(breach_id)\n\n        return {\n            'organization': {\n                'name': self.config.org_name,\n                'contact': self.config.dpo_contact,\n                'registration': self.config.registration_number\n            },\n            'breach': {\n                'nature': breach['description'],\n                'categories_affected': breach['data_types_affected'],\n                'approximate_number_affected': breach['affected_individuals_count'],\n                'likely_consequences': self.assess_consequences(breach),\n                'measures_taken': await self.get_remediation_measures(breach_id),\n                'measures_proposed': await self.get_proposed_measures(breach_id)\n            },\n            'timeline': breach['timeline'],\n            'submitted_at': datetime.utcnow().isoformat()\n        }\n```\n\n## Compliance Checklist\n\n```markdown\n## GDPR Implementation Checklist\n\n### Legal Basis\n\n- [ ] Documented legal basis for each processing activity\n- [ ] Consent mechanisms meet GDPR requirements\n- [ ] Legitimate interest assessments completed\n\n### Transparency\n\n- [ ] Privacy policy is clear and accessible\n- [ ] Processing purposes clearly stated\n- [ ] Data retention periods documented\n\n### Data Subject Rights\n\n- [ ] Access request process implemented\n- [ ] Erasure request process implemented\n- [ ] Portability export available\n- [ ] Rectification process available\n- [ ] Response within 30-day deadline\n\n### Security\n\n- [ ] Encryption at rest implemented\n- [ ] Encryption in transit (TLS)\n- [ ] Access controls in place\n- [ ] Audit logging enabled\n\n### Breach Response\n\n- [ ] Breach detection mechanisms\n- [ ] 72-hour notification process\n- [ ] Breach documentation system\n\n### Documentation\n\n- [ ] Records of processing activities (Art. 30)\n- [ ] Data protection impact assessments\n- [ ] Data processing agreements with vendors\n```\n\n## Best Practices\n\n### Do's\n\n- **Minimize data collection** - Only collect what's needed\n- **Document everything** - Processing activities, legal bases\n- **Encrypt PII** - At rest and in transit\n- **Implement access controls** - Need-to-know basis\n- **Regular audits** - Verify compliance continuously\n\n### Don'ts\n\n- **Don't pre-check consent boxes** - Must be opt-in\n- **Don't bundle consent** - Separate purposes separately\n- **Don't retain indefinitely** - Define and enforce retention\n- **Don't ignore DSARs** - 30-day response required\n- **Don't transfer without safeguards** - SCCs or adequacy decisions\n",{"name":5,"description":7},"main","d69096e239f2a89aabc2cd078c47664a9d3b1e11","07-后端与架构\u002Fgdpr-data-handling-agents-main",3,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts","https:\u002F\u002Fgithub.com\u002Flza6","个人vx：Tf00798\r\n个人✈：@TFGY999","2026-10-08 14:29:22",{"source":8,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add lza6\u002FArmor-piercing-system-prompts --skill gdpr-data-handling",{"tool":38,"command":39},"bunx","bunx skills add lza6\u002FArmor-piercing-system-prompts --skill gdpr-data-handling",{"tool":41,"command":42},"pnpm","pnpm dlx skills add lza6\u002FArmor-piercing-system-prompts --skill gdpr-data-handling","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fgdpr-data-handling-agents-main\u002FSKILL.md",true,[],[47,54,59,66,73,80],{"skillNo":48,"name":49,"nameZh":6,"description":50,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":51,"categories":52,"keywords":53,"publishedAt":19},"01M7FFG485KY83TD6HSC4YPCMC","obsidian-clipper-template-creator","Guide for creating templates for the Obsidian Web Clipper. Use when you want to create a new clipping template, understand available variables, or format clipped content.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator\u002FSKILL.md",[],[],{"skillNo":55,"name":49,"nameZh":6,"description":50,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":56,"categories":57,"keywords":58,"publishedAt":19},"01M7FFG0T6AZ0STEJPSB3CX84K","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator-antigravity-awesome-skills-main\u002FSKILL.md",[],[],{"skillNo":60,"name":61,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":65,"publishedAt":19},"01M7FFFY0QEM14SKWPDYGMXM2P","python-api","Programmatic Object-Detection-Metrics API guidance for BoundingBox, BoundingBoxes, Evaluator, enums, coordinate conversion, AP\u002FmAP semantics, and source-style import diagnostics.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Fpython-api\u002FSKILL.md",[],[],{"skillNo":67,"name":68,"nameZh":6,"description":69,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":19},"01M7FFFVZQZ2GJ0C0TGP7JHD20","file-evaluation","Folder-based PASCAL VOC AP\u002FmAP evaluation from ground-truth and detection text files.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Ffile-evaluation\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":19},"01M7FFFSFNYSE77SJ6PE1CK2DA","object-detection-metrics","Guides legacy Object-Detection-Metrics PASCAL VOC AP\u002FmAP evaluation from detection text folders and direct Python API classes.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":19},"01M7FFFP0GCK1RVXBCPQ8APBMT","nx-workspace-patterns","Configure and optimize Nx monorepo workspaces. Use when setting up Nx, configuring project boundaries, optimizing build caching, or implementing affected commands.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fnx-workspace-patterns\u002FSKILL.md",[],[]]