Data privacy compliance skill

Data privacy and regulatory compliance specialist for GDPR, CCPA, HIPAA, and international data protection laws.

by davila7·MIT license·★ 32,299 Stars on the repo·GitHub ↗

Use now

Files of Data privacy compliance

davila7/main1 file shown
SKILL.md
Show the full text615 lines

Data Privacy Compliance

Comprehensive guidance for implementing data privacy compliance across GDPR, CCPA, HIPAA, and other global data protection regulations.

When to Use This Skill

Use this skill when:

  • Implementing GDPR, CCPA, or HIPAA compliance
  • Conducting Data Protection Impact Assessments (DPIA)
  • Managing data subject rights (access, deletion, portability)
  • Implementing consent management systems
  • Drafting privacy policies and notices
  • Handling data breaches and incident response
  • Designing privacy-by-design systems
  • Conducting privacy audits and assessments

Key Regulations Overview

GDPR (General Data Protection Regulation)

Scope: EU residents' data, regardless of where company is located Key Requirements:

  • Lawful basis for processing (consent, contract, legitimate interest, etc.)
  • Data subject rights (access, deletion, portability, objection)
  • Data Protection Impact Assessments for high-risk processing
  • 72-hour breach notification requirement
  • Records of processing activities
  • Privacy by design and by default

Penalties: Up to €20M or 4% of global annual revenue

CCPA/CPRA (California Consumer Privacy Act)

Scope: California residents' data Key Requirements:

  • Right to know what data is collected
  • Right to delete personal information
  • Right to opt-out of sale/sharing
  • Right to correct inaccurate information
  • Right to limit use of sensitive personal information

Penalties: Up to $7,500 per intentional violation

HIPAA (Health Insurance Portability and Accountability Act)

Scope: Protected Health Information (PHI) in the US Key Requirements:

  • Privacy Rule (patient rights and information uses)
  • Security Rule (safeguards for ePHI)
  • Breach Notification Rule (60-day notification)
  • Business Associate Agreements (BAAs)

Penalties: Up to $1.5M per violation category per year

Data Subject Rights Implementation

1. Right to Access (GDPR Art. 15 / CCPA § 1798.100)

Request Handler:

async function handleAccessRequest(userId, email) {
  // Verify identity
  const verified = await verifyIdentity(email);
  if (!verified) throw new Error('Identity verification failed');

  // Collect all personal data
  const userData = await collectUserData(userId);

  // Format for readability
  const report = {
    personalInfo: userData.profile,
    activityLogs: userData.activities,
    preferences: userData.settings,
    thirdPartySharing: userData.dataSharing,
    retentionPeriod: '2 years from last activity',
    dataProtectionOfficer: '[email protected]'
  };

  // Generate downloadable report
  const pdf = await generatePDFReport(report);

  // Log request for compliance
  await logAccessRequest(userId, 'completed');

  return pdf;
}

Response Timeline:

  • GDPR: 1 month (extendable to 3 months)
  • CCPA: 45 days (extendable to 90 days)
2. Right to Deletion (GDPR Art. 17 / CCPA § 1798.105)

Deletion Handler:

async function handleDeletionRequest(userId, email) {
  // Verify identity
  const verified = await verifyIdentity(email);
  if (!verified) throw new Error('Identity verification failed');

  // Check for legal obligations to retain
  const mustRetain = await checkRetentionRequirements(userId);
  if (mustRetain.required) {
    return {
      status: 'partial_deletion',
      retained: mustRetain.data,
      reason: mustRetain.legalBasis,
      retentionPeriod: mustRetain.period
    };
  }

  // Delete from all systems
  await Promise.all([
    deleteFromDatabase(userId),
    deleteFromBackups(userId), // Mark for deletion in next backup cycle
    deleteFromAnalytics(userId),
    deleteFromThirdPartyServices(userId),
    revokeAPIKeys(userId),
    anonymizeHistoricalRecords(userId)
  ]);

  // Confirm deletion
  await sendDeletionConfirmation(email);
  await logDeletionRequest(userId, 'completed');

  return { status: 'deleted', timestamp: new Date() };
}

Exceptions (when deletion can be refused):

  • Legal obligations (tax records, contracts)
  • Public interest/scientific research
  • Defense of legal claims
  • Exercise of freedom of expression
3. Right to Data Portability (GDPR Art. 20)

Export Handler:

async function handlePortabilityRequest(userId, format = 'json') {
  const userData = await collectUserData(userId);

  // Structure in machine-readable format
  const portableData = {
    exportDate: new Date().toISOString(),
    userId: userId,
    data: {
      profile: userData.profile,
      content: userData.userGeneratedContent,
      settings: userData.preferences,
      history: userData.activityHistory
    }
  };

  // Support multiple formats
  if (format === 'csv') {
    return convertToCSV(portableData);
  } else if (format === 'xml') {
    return convertToXML(portableData);
  }

  return portableData; // JSON by default
}

Requirements:

  • Structured, commonly used, machine-readable format
  • Ability to transmit directly to another controller
  • Only applies to data provided by data subject
  • Only for automated processing based on consent or contract
4. Right to Object (GDPR Art. 21)

Objection Handler:

async function handleObjectionRequest(userId, processingType) {
  switch (processingType) {
    case 'direct_marketing':
      // Must stop immediately
      await disableMarketing(userId);
      await updateConsent(userId, 'marketing', false);
      break;

    case 'legitimate_interest':
      // Assess if we have compelling grounds
      const assessment = await assessLegitimateInterest(userId);
      if (!assessment.compelling) {
        await stopProcessing(userId, processingType);
      }
      return assessment;

    case 'profiling':
      await disableProfiling(userId);
      await updateConsent(userId, 'profiling', false);
      break;

    default:
      throw new Error('Invalid processing type');
  }

  await logObjectionRequest(userId, processingType, 'granted');
}

Valid Consent Must Be:

  1. Freely given (no coercion)
  2. Specific (for each purpose)
  3. Informed (clear language)
  4. Unambiguous (clear affirmative action)
  5. Withdrawable (as easy to withdraw as to give)

Consent Implementation:

<!-- Good: Granular consent -->
<form>
  <h3>Privacy Preferences</h3>

  <label>
    <input type="checkbox" name="essential" checked disabled>
    <strong>Essential cookies (Required)</strong>
    <p>Necessary for website functionality</p>
  </label>

  <label>
    <input type="checkbox" name="analytics" value="analytics">
    <strong>Analytics cookies</strong>
    <p>Help us improve our website by collecting usage data</p>
  </label>

  <label>
    <input type="checkbox" name="marketing" value="marketing">
    <strong>Marketing cookies</strong>
    <p>Show you personalized ads based on your interests</p>
  </label>

  <button type="submit">Save Preferences</button>
  <a href="/privacy-policy">Learn More</a>
</form>

Consent Record Storage:

const consentRecord = {
  userId: 'user123',
  timestamp: new Date().toISOString(),
  consentVersion: '2.0',
  purposes: {
    essential: { granted: true, required: true },
    analytics: { granted: true, purpose: 'Website improvement' },
    marketing: { granted: false, purpose: 'Personalized advertising' }
  },
  ipAddress: '192.168.1.1', // For proof
  userAgent: 'Mozilla/5.0...', // For context
  method: 'explicit_opt_in' // or 'implicit', 'presumed'
};

await saveConsentRecord(consentRecord);
<div id="cookie-banner" role="dialog" aria-labelledby="cookie-title">
  <h2 id="cookie-title">Cookie Preferences</h2>
  <p>
    We use cookies to enhance your experience. Choose which cookies you
    allow us to use. You can change your preferences at any time.
  </p>

  <button onclick="acceptAll()">Accept All</button>
  <button onclick="rejectNonEssential()">Reject Non-Essential</button>
  <button onclick="showPreferences()">Manage Preferences</button>
</div>

<script>
// Must not load non-essential cookies until consent given
function acceptAll() {
  setConsent({ analytics: true, marketing: true });
  loadAnalyticsCookies();
  loadMarketingCookies();
  hideBanner();
}

function rejectNonEssential() {
  setConsent({ analytics: false, marketing: false });
  hideBanner();
}
</script>

Privacy by Design Principles

1. Data Minimization

Principle: Collect only data necessary for specified purpose

Implementation:

// ❌ Bad: Collecting unnecessary data
const userRegistration = {
  email: req.body.email,
  password: req.body.password,
  fullName: req.body.fullName,
  phoneNumber: req.body.phoneNumber, // Not needed
  dateOfBirth: req.body.dateOfBirth, // Not needed
  address: req.body.address, // Not needed
  socialSecurityNumber: req.body.ssn // Definitely not needed!
};

// ✅ Good: Only essential data
const userRegistration = {
  email: req.body.email,
  password: hashPassword(req.body.password),
  displayName: req.body.displayName // Optional
};
2. Purpose Limitation

Principle: Use data only for specified, explicit purposes

Implementation:

// Document and enforce purpose
const dataProcessingPurpose = {
  email: [
    'account_authentication',
    'order_confirmations',
    'password_reset'
  ],
  phoneNumber: [
    'order_delivery_notifications'
    // NOT: 'marketing_calls' (requires separate consent)
  ],
  purchaseHistory: [
    'order_fulfillment',
    'customer_support'
    // NOT: 'targeted_advertising' (requires separate consent)
  ]
};

async function processData(data, purpose) {
  if (!isAllowedPurpose(data.type, purpose)) {
    throw new Error('Purpose not authorized for this data');
  }
  // Proceed with processing
}
3. Storage Limitation

Principle: Retain data only as long as necessary

Implementation:

const retentionPolicy = {
  userAccounts: {
    active: 'indefinite',
    inactive: '2 years',
    deleted: '30 days grace period'
  },
  orderRecords: '7 years', // Legal requirement
  supportTickets: '3 years',
  analytics: '26 months',
  marketingData: '1 year or until consent withdrawn'
};

// Automated data deletion
async function enforceRetentionPolicy() {
  const now = new Date();

  // Delete inactive accounts
  await User.deleteMany({
    lastActive: { $lt: subYears(now, 2) },
    status: 'inactive'
  });

  // Anonymize old analytics
  await Analytics.updateMany(
    { createdAt: { $lt: subMonths(now, 26) } },
    { $unset: { userId: 1, ipAddress: 1 } }
  );

  // Delete expired marketing consent
  await MarketingConsent.deleteMany({
    $or: [
      { expiresAt: { $lt: now } },
      { withdrawnAt: { $lt: subDays(now, 30) } }
    ]
  });
}

// Schedule daily
cron.schedule('0 2 * * *', enforceRetentionPolicy);

Data Protection Impact Assessment (DPIA)

When Required (GDPR Art. 35):

  • Systematic and extensive profiling
  • Large-scale processing of sensitive data
  • Systematic monitoring of publicly accessible areas
  • New technologies with high privacy risks

DPIA Template:

# Data Protection Impact Assessment

## Processing Overview
- **Purpose**: [Describe the processing activity]
- **Data Types**: [Personal data categories]
- **Data Subjects**: [Who is affected]
- **Recipients**: [Who receives the data]

## Necessity Assessment
- [ ] Is processing necessary for the stated purpose?
- [ ] Could the purpose be achieved with less data?
- [ ] Is the retention period justified?

## Risk Assessment
| Risk | Likelihood | Severity | Mitigation |
|------|------------|----------|------------|
| Data breach | Medium | High | Encryption, access controls |
| Unauthorized access | Low | High | 2FA, audit logs |
| Purpose creep | Medium | Medium | Purpose documentation, training |

## Safeguards
- [ ] Encryption at rest and in transit
- [ ] Access controls and authentication
- [ ] Regular security audits
- [ ] Data minimization applied
- [ ] Retention policies enforced
- [ ] DPO consulted
- [ ] Data subject rights mechanism in place

## Conclusion
Processing is/is not acceptable with proposed safeguards.

Signed: [Data Protection Officer]
Date: [Assessment Date]

Privacy Policy Requirements

Essential Elements:

# Privacy Policy

## 1. Identity of Controller
Company Name, Address, Contact Information
Data Protection Officer: [email protected]

## 2. Data We Collect
- Account data: email, name
- Usage data: pages visited, features used
- Technical data: IP address, browser type

## 3. Legal Basis for Processing
- **Consent**: Marketing communications
- **Contract**: Order fulfillment
- **Legitimate Interest**: Fraud prevention
- **Legal Obligation**: Tax records

## 4. How We Use Your Data
- Provide services you requested
- Improve our products
- Send important updates
- [Be specific, avoid vague statements]

## 5. Data Sharing
- Payment processors (Stripe, PayPal)
- Shipping providers (FedEx, UPS)
- Analytics (Google Analytics)

We do NOT sell your personal data.

## 6. Your Rights
- Right to access your data
- Right to correct inaccuracies
- Right to delete your data
- Right to object to processing
- Right to data portability
- Right to withdraw consent

Contact: [email protected]

## 7. Data Retention
- Account data: Until account deletion + 30 days
- Order history: 7 years (legal requirement)
- Marketing data: 1 year or until opt-out

## 8. Security
We use industry-standard security measures including
encryption, secure servers, and regular security audits.

## 9. International Transfers
Data may be transferred to US servers. We use Standard
Contractual Clauses approved by the EU Commission.

## 10. Changes to Policy
Last updated: [Date]
We will notify you of material changes via email.

## 11. Contact
Questions? Contact our Data Protection Officer at [email protected]

Incident Response

Data Breach Response Plan

Within 72 Hours (GDPR):

1. **Detect & Contain** (0-4 hours)
   - Identify scope of breach
   - Isolate affected systems
   - Prevent further data loss

2. **Assess** (4-24 hours)
   - Determine data types affected
   - Identify number of individuals
   - Assess risk to rights and freedoms
   - Document everything

3. **Notify Authority** (24-72 hours)
   - Report to supervisory authority
   - Include: nature, categories, approximate numbers,
     likely consequences, measures taken

4. **Notify Data Subjects** (ASAP if high risk)
   - Direct communication required
   - Describe breach in clear language
   - Provide recommendations for protection

Breach Notification Template:

Subject: Important Security Notice

Dear [Name],

We are writing to inform you of a data security incident that may
have affected your personal information.

WHAT HAPPENED:
On [date], we discovered that [brief description].

WHAT INFORMATION WAS INVOLVED:
[List specific data types: name, email, etc.]
[List what was NOT involved]

WHAT WE ARE DOING:
- [Immediate actions taken]
- [Ongoing security enhancements]
- [Resources provided to affected individuals]

WHAT YOU CAN DO:
- Change your password immediately
- Monitor your accounts for suspicious activity
- [Specific recommendations]

FOR MORE INFORMATION:
Contact our dedicated hotline: [phone]
Email: [email protected]

We sincerely apologize for this incident and the inconvenience
it may cause.

Sincerely,
[Name, Title]

Compliance Checklist

GDPR Compliance
  • Lawful basis documented for all processing
  • Privacy policy published and accessible
  • Consent mechanism implements granular controls
  • Data subject rights request process established
  • Records of processing activities maintained
  • Data Protection Officer appointed (if required)
  • DPIA conducted for high-risk processing
  • Data breach notification procedure in place
  • Vendor contracts include data processing agreements
  • International data transfer safeguards implemented
  • Staff training on data protection completed
CCPA Compliance
  • "Do Not Sell My Personal Information" link on homepage
  • Privacy policy discloses data collection and sales
  • Mechanisms for verifiable consumer requests
  • Process for opt-out requests (48-hour response)
  • Annual report on requests and compliance
  • Service provider agreements updated
  • Notice at collection provided
HIPAA Compliance
  • Risk assessment completed
  • Security policies and procedures documented
  • Workforce trained on HIPAA requirements
  • Business Associate Agreements signed
  • Access controls and audit trails implemented
  • Encryption for ePHI
  • Breach notification procedures established
  • Contingency plan and disaster recovery

Privacy compliance is an ongoing process, not a one-time checklist. Regularly review and update practices as regulations evolve and your data processing changes.

1---
2name: Data Privacy Compliance
3description: Data privacy and regulatory compliance specialist for GDPR, CCPA, HIPAA, and international data protection laws. Use when implementing privacy controls, conducting data protection impact assessments, ensuring regulatory compliance, or managing data subject rights. Expert in consent management, data minimization, and privacy-by-design principles.
4---
5 
6# Data Privacy Compliance
7 
8Comprehensive guidance for implementing data privacy compliance across GDPR, CCPA, HIPAA, and other global data protection regulations.
9 
10## When to Use This Skill
11 
12Use this skill when:
13- Implementing GDPR, CCPA, or HIPAA compliance
14- Conducting Data Protection Impact Assessments (DPIA)
15- Managing data subject rights (access, deletion, portability)
16- Implementing consent management systems
17- Drafting privacy policies and notices
18- Handling data breaches and incident response
19- Designing privacy-by-design systems
20- Conducting privacy audits and assessments
21 
22## Key Regulations Overview
23 
24### GDPR (General Data Protection Regulation)
25**Scope:** EU residents' data, regardless of where company is located
26**Key Requirements:**
27- Lawful basis for processing (consent, contract, legitimate interest, etc.)
28- Data subject rights (access, deletion, portability, objection)
29- Data Protection Impact Assessments for high-risk processing
30- 72-hour breach notification requirement
31- Records of processing activities
32- Privacy by design and by default
33 
34**Penalties:** Up to €20M or 4% of global annual revenue
35 
36### CCPA/CPRA (California Consumer Privacy Act)
37**Scope:** California residents' data
38**Key Requirements:**
39- Right to know what data is collected
40- Right to delete personal information
41- Right to opt-out of sale/sharing
42- Right to correct inaccurate information
43- Right to limit use of sensitive personal information
44 
45**Penalties:** Up to $7,500 per intentional violation
46 
47### HIPAA (Health Insurance Portability and Accountability Act)
48**Scope:** Protected Health Information (PHI) in the US
49**Key Requirements:**
50- Privacy Rule (patient rights and information uses)
51- Security Rule (safeguards for ePHI)
52- Breach Notification Rule (60-day notification)
53- Business Associate Agreements (BAAs)
54 
55**Penalties:** Up to $1.5M per violation category per year
56 
57## Data Subject Rights Implementation
58 
59### 1. Right to Access (GDPR Art. 15 / CCPA § 1798.100)
60 
61**Request Handler:**
62```javascript
63async function handleAccessRequest(userId, email) {
64 // Verify identity
65 const verified = await verifyIdentity(email);
66 if (!verified) throw new Error('Identity verification failed');
67 
68 // Collect all personal data
69 const userData = await collectUserData(userId);
70 
71 // Format for readability
72 const report = {
73 personalInfo: userData.profile,
74 activityLogs: userData.activities,
75 preferences: userData.settings,
76 thirdPartySharing: userData.dataSharing,
77 retentionPeriod: '2 years from last activity',
78 dataProtectionOfficer: '[email protected]'
79 };
80 
81 // Generate downloadable report
82 const pdf = await generatePDFReport(report);
83 
84 // Log request for compliance
85 await logAccessRequest(userId, 'completed');
86 
87 return pdf;
88}
89```
90 
91**Response Timeline:**
92- GDPR: 1 month (extendable to 3 months)
93- CCPA: 45 days (extendable to 90 days)
94 
95### 2. Right to Deletion (GDPR Art. 17 / CCPA § 1798.105)
96 
97**Deletion Handler:**
98```javascript
99async function handleDeletionRequest(userId, email) {
100 // Verify identity
101 const verified = await verifyIdentity(email);
102 if (!verified) throw new Error('Identity verification failed');
103 
104 // Check for legal obligations to retain
105 const mustRetain = await checkRetentionRequirements(userId);
106 if (mustRetain.required) {
107 return {
108 status: 'partial_deletion',
109 retained: mustRetain.data,
110 reason: mustRetain.legalBasis,
111 retentionPeriod: mustRetain.period
112 };
113 }
114 
115 // Delete from all systems
116 await Promise.all([
117 deleteFromDatabase(userId),
118 deleteFromBackups(userId), // Mark for deletion in next backup cycle
119 deleteFromAnalytics(userId),
120 deleteFromThirdPartyServices(userId),
121 revokeAPIKeys(userId),
122 anonymizeHistoricalRecords(userId)
123 ]);
124 
125 // Confirm deletion
126 await sendDeletionConfirmation(email);
127 await logDeletionRequest(userId, 'completed');
128 
129 return { status: 'deleted', timestamp: new Date() };
130}
131```
132 
133**Exceptions (when deletion can be refused):**
134- Legal obligations (tax records, contracts)
135- Public interest/scientific research
136- Defense of legal claims
137- Exercise of freedom of expression
138 
139### 3. Right to Data Portability (GDPR Art. 20)
140 
141**Export Handler:**
142```javascript
143async function handlePortabilityRequest(userId, format = 'json') {
144 const userData = await collectUserData(userId);
145 
146 // Structure in machine-readable format
147 const portableData = {
148 exportDate: new Date().toISOString(),
149 userId: userId,
150 data: {
151 profile: userData.profile,
152 content: userData.userGeneratedContent,
153 settings: userData.preferences,
154 history: userData.activityHistory
155 }
156 };
157 
158 // Support multiple formats
159 if (format === 'csv') {
160 return convertToCSV(portableData);
161 } else if (format === 'xml') {
162 return convertToXML(portableData);
163 }
164 
165 return portableData; // JSON by default
166}
167```
168 
169**Requirements:**
170- Structured, commonly used, machine-readable format
171- Ability to transmit directly to another controller
172- Only applies to data provided by data subject
173- Only for automated processing based on consent or contract
174 
175### 4. Right to Object (GDPR Art. 21)
176 
177**Objection Handler:**
178```javascript
179async function handleObjectionRequest(userId, processingType) {
180 switch (processingType) {
181 case 'direct_marketing':
182 // Must stop immediately
183 await disableMarketing(userId);
184 await updateConsent(userId, 'marketing', false);
185 break;
186 
187 case 'legitimate_interest':
188 // Assess if we have compelling grounds
189 const assessment = await assessLegitimateInterest(userId);
190 if (!assessment.compelling) {
191 await stopProcessing(userId, processingType);
192 }
193 return assessment;
194 
195 case 'profiling':
196 await disableProfiling(userId);
197 await updateConsent(userId, 'profiling', false);
198 break;
199 
200 default:
201 throw new Error('Invalid processing type');
202 }
203 
204 await logObjectionRequest(userId, processingType, 'granted');
205}
206```
207 
208## Consent Management
209 
210### Consent Requirements (GDPR)
211 
212**Valid Consent Must Be:**
2131. Freely given (no coercion)
2142. Specific (for each purpose)
2153. Informed (clear language)
2164. Unambiguous (clear affirmative action)
2175. Withdrawable (as easy to withdraw as to give)
218 
219**Consent Implementation:**
220```html
221<!-- Good: Granular consent -->
222<form>
223 <h3>Privacy Preferences</h3>
224 
225 <label>
226 <input type="checkbox" name="essential" checked disabled>
227 <strong>Essential cookies (Required)</strong>
228 <p>Necessary for website functionality</p>
229 </label>
230 
231 <label>
232 <input type="checkbox" name="analytics" value="analytics">
233 <strong>Analytics cookies</strong>
234 <p>Help us improve our website by collecting usage data</p>
235 </label>
236 
237 <label>
238 <input type="checkbox" name="marketing" value="marketing">
239 <strong>Marketing cookies</strong>
240 <p>Show you personalized ads based on your interests</p>
241 </label>
242 
243 <button type="submit">Save Preferences</button>
244 <a href="/privacy-policy">Learn More</a>
245</form>
246```
247 
248**Consent Record Storage:**
249```javascript
250const consentRecord = {
251 userId: 'user123',
252 timestamp: new Date().toISOString(),
253 consentVersion: '2.0',
254 purposes: {
255 essential: { granted: true, required: true },
256 analytics: { granted: true, purpose: 'Website improvement' },
257 marketing: { granted: false, purpose: 'Personalized advertising' }
258 },
259 ipAddress: '192.168.1.1', // For proof
260 userAgent: 'Mozilla/5.0...', // For context
261 method: 'explicit_opt_in' // or 'implicit', 'presumed'
262};
263 
264await saveConsentRecord(consentRecord);
265```
266 
267### Cookie Banner (GDPR Compliant)
268 
269```html
270<div id="cookie-banner" role="dialog" aria-labelledby="cookie-title">
271 <h2 id="cookie-title">Cookie Preferences</h2>
272 <p>
273 We use cookies to enhance your experience. Choose which cookies you
274 allow us to use. You can change your preferences at any time.
275 </p>
276 
277 <button onclick="acceptAll()">Accept All</button>
278 <button onclick="rejectNonEssential()">Reject Non-Essential</button>
279 <button onclick="showPreferences()">Manage Preferences</button>
280</div>
281 
282<script>
283// Must not load non-essential cookies until consent given
284function acceptAll() {
285 setConsent({ analytics: true, marketing: true });
286 loadAnalyticsCookies();
287 loadMarketingCookies();
288 hideBanner();
289}
290 
291function rejectNonEssential() {
292 setConsent({ analytics: false, marketing: false });
293 hideBanner();
294}
295</script>
296```
297 
298## Privacy by Design Principles
299 
300### 1. Data Minimization
301 
302**Principle:** Collect only data necessary for specified purpose
303 
304**Implementation:**
305```javascript
306// ❌ Bad: Collecting unnecessary data
307const userRegistration = {
308 email: req.body.email,
309 password: req.body.password,
310 fullName: req.body.fullName,
311 phoneNumber: req.body.phoneNumber, // Not needed
312 dateOfBirth: req.body.dateOfBirth, // Not needed
313 address: req.body.address, // Not needed
314 socialSecurityNumber: req.body.ssn // Definitely not needed!
315};
316 
317// ✅ Good: Only essential data
318const userRegistration = {
319 email: req.body.email,
320 password: hashPassword(req.body.password),
321 displayName: req.body.displayName // Optional
322};
323```
324 
325### 2. Purpose Limitation
326 
327**Principle:** Use data only for specified, explicit purposes
328 
329**Implementation:**
330```javascript
331// Document and enforce purpose
332const dataProcessingPurpose = {
333 email: [
334 'account_authentication',
335 'order_confirmations',
336 'password_reset'
337 ],
338 phoneNumber: [
339 'order_delivery_notifications'
340 // NOT: 'marketing_calls' (requires separate consent)
341 ],
342 purchaseHistory: [
343 'order_fulfillment',
344 'customer_support'
345 // NOT: 'targeted_advertising' (requires separate consent)
346 ]
347};
348 
349async function processData(data, purpose) {
350 if (!isAllowedPurpose(data.type, purpose)) {
351 throw new Error('Purpose not authorized for this data');
352 }
353 // Proceed with processing
354}
355```
356 
357### 3. Storage Limitation
358 
359**Principle:** Retain data only as long as necessary
360 
361**Implementation:**
362```javascript
363const retentionPolicy = {
364 userAccounts: {
365 active: 'indefinite',
366 inactive: '2 years',
367 deleted: '30 days grace period'
368 },
369 orderRecords: '7 years', // Legal requirement
370 supportTickets: '3 years',
371 analytics: '26 months',
372 marketingData: '1 year or until consent withdrawn'
373};
374 
375// Automated data deletion
376async function enforceRetentionPolicy() {
377 const now = new Date();
378 
379 // Delete inactive accounts
380 await User.deleteMany({
381 lastActive: { $lt: subYears(now, 2) },
382 status: 'inactive'
383 });
384 
385 // Anonymize old analytics
386 await Analytics.updateMany(
387 { createdAt: { $lt: subMonths(now, 26) } },
388 { $unset: { userId: 1, ipAddress: 1 } }
389 );
390 
391 // Delete expired marketing consent
392 await MarketingConsent.deleteMany({
393 $or: [
394 { expiresAt: { $lt: now } },
395 { withdrawnAt: { $lt: subDays(now, 30) } }
396 ]
397 });
398}
399 
400// Schedule daily
401cron.schedule('0 2 * * *', enforceRetentionPolicy);
402```
403 
404## Data Protection Impact Assessment (DPIA)
405 
406**When Required (GDPR Art. 35):**
407- Systematic and extensive profiling
408- Large-scale processing of sensitive data
409- Systematic monitoring of publicly accessible areas
410- New technologies with high privacy risks
411 
412**DPIA Template:**
413```markdown
414# Data Protection Impact Assessment
415 
416## Processing Overview
417- **Purpose**: [Describe the processing activity]
418- **Data Types**: [Personal data categories]
419- **Data Subjects**: [Who is affected]
420- **Recipients**: [Who receives the data]
421 
422## Necessity Assessment
423- [ ] Is processing necessary for the stated purpose?
424- [ ] Could the purpose be achieved with less data?
425- [ ] Is the retention period justified?
426 
427## Risk Assessment
428| Risk | Likelihood | Severity | Mitigation |
429|------|------------|----------|------------|
430| Data breach | Medium | High | Encryption, access controls |
431| Unauthorized access | Low | High | 2FA, audit logs |
432| Purpose creep | Medium | Medium | Purpose documentation, training |
433 
434## Safeguards
435- [ ] Encryption at rest and in transit
436- [ ] Access controls and authentication
437- [ ] Regular security audits
438- [ ] Data minimization applied
439- [ ] Retention policies enforced
440- [ ] DPO consulted
441- [ ] Data subject rights mechanism in place
442 
443## Conclusion
444Processing is/is not acceptable with proposed safeguards.
445 
446Signed: [Data Protection Officer]
447Date: [Assessment Date]
448```
449 
450## Privacy Policy Requirements
451 
452**Essential Elements:**
453```markdown
454# Privacy Policy
455 
456## 1. Identity of Controller
457Company Name, Address, Contact Information
458Data Protection Officer: [email protected]
459 
460## 2. Data We Collect
461- Account data: email, name
462- Usage data: pages visited, features used
463- Technical data: IP address, browser type
464 
465## 3. Legal Basis for Processing
466- **Consent**: Marketing communications
467- **Contract**: Order fulfillment
468- **Legitimate Interest**: Fraud prevention
469- **Legal Obligation**: Tax records
470 
471## 4. How We Use Your Data
472- Provide services you requested
473- Improve our products
474- Send important updates
475- [Be specific, avoid vague statements]
476 
477## 5. Data Sharing
478- Payment processors (Stripe, PayPal)
479- Shipping providers (FedEx, UPS)
480- Analytics (Google Analytics)
481 
482We do NOT sell your personal data.
483 
484## 6. Your Rights
485- Right to access your data
486- Right to correct inaccuracies
487- Right to delete your data
488- Right to object to processing
489- Right to data portability
490- Right to withdraw consent
491 
492Contact: [email protected]
493 
494## 7. Data Retention
495- Account data: Until account deletion + 30 days
496- Order history: 7 years (legal requirement)
497- Marketing data: 1 year or until opt-out
498 
499## 8. Security
500We use industry-standard security measures including
501encryption, secure servers, and regular security audits.
502 
503## 9. International Transfers
504Data may be transferred to US servers. We use Standard
505Contractual Clauses approved by the EU Commission.
506 
507## 10. Changes to Policy
508Last updated: [Date]
509We will notify you of material changes via email.
510 
511## 11. Contact
512Questions? Contact our Data Protection Officer at [email protected]
513```
514 
515## Incident Response
516 
517### Data Breach Response Plan
518 
519**Within 72 Hours (GDPR):**
520```markdown
5211. **Detect & Contain** (0-4 hours)
522 - Identify scope of breach
523 - Isolate affected systems
524 - Prevent further data loss
525 
5262. **Assess** (4-24 hours)
527 - Determine data types affected
528 - Identify number of individuals
529 - Assess risk to rights and freedoms
530 - Document everything
531 
5323. **Notify Authority** (24-72 hours)
533 - Report to supervisory authority
534 - Include: nature, categories, approximate numbers,
535 likely consequences, measures taken
536 
5374. **Notify Data Subjects** (ASAP if high risk)
538 - Direct communication required
539 - Describe breach in clear language
540 - Provide recommendations for protection
541```
542 
543**Breach Notification Template:**
544```
545Subject: Important Security Notice
546 
547Dear [Name],
548 
549We are writing to inform you of a data security incident that may
550have affected your personal information.
551 
552WHAT HAPPENED:
553On [date], we discovered that [brief description].
554 
555WHAT INFORMATION WAS INVOLVED:
556[List specific data types: name, email, etc.]
557[List what was NOT involved]
558 
559WHAT WE ARE DOING:
560- [Immediate actions taken]
561- [Ongoing security enhancements]
562- [Resources provided to affected individuals]
563 
564WHAT YOU CAN DO:
565- Change your password immediately
566- Monitor your accounts for suspicious activity
567- [Specific recommendations]
568 
569FOR MORE INFORMATION:
570Contact our dedicated hotline: [phone]
571Email: [email protected]
572 
573We sincerely apologize for this incident and the inconvenience
574it may cause.
575 
576Sincerely,
577[Name, Title]
578```
579 
580## Compliance Checklist
581 
582### GDPR Compliance
583- [ ] Lawful basis documented for all processing
584- [ ] Privacy policy published and accessible
585- [ ] Consent mechanism implements granular controls
586- [ ] Data subject rights request process established
587- [ ] Records of processing activities maintained
588- [ ] Data Protection Officer appointed (if required)
589- [ ] DPIA conducted for high-risk processing
590- [ ] Data breach notification procedure in place
591- [ ] Vendor contracts include data processing agreements
592- [ ] International data transfer safeguards implemented
593- [ ] Staff training on data protection completed
594 
595### CCPA Compliance
596- [ ] "Do Not Sell My Personal Information" link on homepage
597- [ ] Privacy policy discloses data collection and sales
598- [ ] Mechanisms for verifiable consumer requests
599- [ ] Process for opt-out requests (48-hour response)
600- [ ] Annual report on requests and compliance
601- [ ] Service provider agreements updated
602- [ ] Notice at collection provided
603 
604### HIPAA Compliance
605- [ ] Risk assessment completed
606- [ ] Security policies and procedures documented
607- [ ] Workforce trained on HIPAA requirements
608- [ ] Business Associate Agreements signed
609- [ ] Access controls and audit trails implemented
610- [ ] Encryption for ePHI
611- [ ] Breach notification procedures established
612- [ ] Contingency plan and disaster recovery
613 
614Privacy compliance is an ongoing process, not a one-time checklist. Regularly review and update practices as regulations evolve and your data processing changes.
615 

Discussion

Alternatives