Built for developers, by XinhND

v2.1.0

Ready

Security Cheat Sheet

Complete reference guide for Security with interactive examples and live playground links

Web Security Vulnerabilities

Cross-Site Scripting (XSS)

XSS allows attackers to inject client-side scripts into web pages viewed by other users. Proper input sanitization and output encoding are essential defenses.

Security
// Vulnerable code
const displayUserInput = (input) => {
  document.getElementById('output').innerHTML = input; // Unsafe!
};

// Secure approach
const safeDisplay = (input) => {
  // Encode HTML entities
  const encoded = input
    .replace(/&/g, '&')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#039;');
  
  document.getElementById('output').innerHTML = encoded;
  
  // Or use textContent instead (automatically escapes HTML)
  document.getElementById('output').textContent = input;
};

// React approach (automatically sanitizes)
function SafeComponent({ userInput }) {
  return <div>{userInput}</div>;  // React escapes content by default
}

SQL Injection

SQL Injection occurs when untrusted data is inserted into SQL queries. Use prepared statements, parameterized queries, or ORMs to prevent this.

Security
// Vulnerable SQL query (PHP example)
$username = $_POST['username'];
$query = "SELECT * FROM users WHERE username = '$username'";
// Attacker input: ' OR '1'='1 will bypass authentication

// Secure approach with prepared statements (PHP)
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();

// Node.js with prepared statements
const { Client } = require('pg');
const client = new Client();
await client.connect();

const query = 'SELECT * FROM users WHERE username = $1';
const values = [username];
const result = await client.query(query, values);

// ORM approach (Sequelize)
const user = await User.findOne({
  where: { username: username }
});

Cross-Site Request Forgery (CSRF)

CSRF tricks users into performing unwanted actions on sites they're authenticated to. Implement anti-CSRF tokens, SameSite cookies, and verify request origins.

Security
// Express.js CSRF protection
const csrf = require('csurf');
const csrfProtection = csrf({ cookie: true });

app.get('/form', csrfProtection, (req, res) => {
  res.render('form', { csrfToken: req.csrfToken() });
});

app.post('/process', csrfProtection, (req, res) => {
  // Process the form submission
});

<!-- Form with CSRF token -->
<form action="/process" method="POST">
  <input type="hidden" name="_csrf" value="{{csrfToken}}">
  <!-- form fields -->
  <button type="submit">Submit</button>
</form>

// SPA approach with custom header (Angular example)
// In HTTP interceptor
request = request.clone({
  setHeaders: {
    'X-CSRF-Token': this.csrfService.getToken()
  }
});

Cross-Origin Resource Sharing (CORS)

CORS is a security mechanism that allows or restricts resource requests from other domains. Configure it to allow only trusted origins.

Security
// Node.js CORS configuration
const cors = require('cors');

// Allow all origins (not recommended for production)
app.use(cors());

// Allow specific origin
app.use(cors({
  origin: 'https://trusted-site.com',
  methods: ['GET', 'POST'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true
}));

// Multiple origins
app.use(cors({
  origin: [
    'https://trusted-site.com',
    'https://another-trusted-site.com'
  ],
  credentials: true
}));

// Dynamic CORS configuration
app.use(cors({
  origin: function(origin, callback) {
    const allowlist = ['https://trusted-site.com', 'https://dev-site.com'];
    if (!origin || allowlist.indexOf(origin) !== -1) {
      callback(null, true);
    } else {
      callback(new Error('CORS policy violation'));
    }
  }
}));

Content Security Policy (CSP)

CSP helps prevent XSS and injection attacks by controlling which resources can be loaded. Implement it to limit resource origins and script execution.

Security
// CSP HTTP Header
Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted-cdn.com; 
  style-src 'self' https://trusted-cdn.com; img-src 'self' data: https://trusted-cdn.com;
  connect-src 'self' https://api.trusted-site.com; font-src 'self';
  object-src 'none'; media-src 'self'; frame-src https://trusted-site.com;
  
// Setting CSP in HTML
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' https://trusted-cdn.com">

// Setting CSP in Express.js
const helmet = require('helmet');
app.use(
  helmet.contentSecurityPolicy({
    directives: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'", "https://trusted-cdn.com"],
      styleSrc: ["'self'", "https://trusted-cdn.com"],
      imgSrc: ["'self'", "data:", "https://trusted-cdn.com"],
      connectSrc: ["'self'", "https://api.trusted-site.com"],
      fontSrc: ["'self'"],
      objectSrc: ["'none'"],
      mediaSrc: ["'self'"],
      frameSrc: ["https://trusted-site.com"],
    },
  })
);

API Security

Authentication & Authorization

Implement proper authentication and authorization to protect API endpoints. Use JWTs, OAuth, or API keys and validate permissions for each request.

Security
// JWT Authentication in Express.js
const jwt = require('jsonwebtoken');
const secret = process.env.JWT_SECRET;

// Generating a token
const generateToken = (user) => {
  return jwt.sign(
    { id: user.id, role: user.role },
    secret,
    { expiresIn: '24h' }
  );
};

// Middleware for verifying tokens
const verifyToken = (req, res, next) => {
  const token = req.headers.authorization?.split(' ')[1];
  
  if (!token) {
    return res.status(401).json({ message: 'No token provided' });
  }
  
  try {
    const decoded = jwt.verify(token, secret);
    req.user = decoded;
    next();
  } catch (err) {
    return res.status(401).json({ message: 'Invalid token' });
  }
};

// Role-based authorization
const checkRole = (roles) => {
  return (req, res, next) => {
    if (!req.user) {
      return res.status(401).json({ message: 'Unauthorized' });
    }
    
    if (!roles.includes(req.user.role)) {
      return res.status(403).json({ message: 'Forbidden' });
    }
    
    next();
  };
};

// Protect routes
app.get(
  '/admin', 
  verifyToken, 
  checkRole(['admin']), 
  (req, res) => {
    // Admin-only endpoint
  }
);

Rate Limiting

Rate limiting prevents abuse and DoS attacks by limiting how many requests a client can make in a given time period. Implement per-client and per-endpoint limits.

Security
// Rate limiting in Express.js
const rateLimit = require('express-rate-limit');

// Basic rate limiting
const apiLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100, // 100 requests per window
  standardHeaders: true,
  legacyHeaders: false,
  message: 'Too many requests, please try again after 15 minutes'
});

// Apply to all API routes
app.use('/api', apiLimiter);

// Different limits for different routes
const authLimiter = rateLimit({
  windowMs: 60 * 60 * 1000, // 1 hour
  max: 5, // 5 login attempts per hour
  message: 'Too many login attempts, please try again after an hour'
});

app.use('/api/auth/login', authLimiter);

// Redis-based rate limiting for distributed systems
const RedisStore = require('rate-limit-redis');
const redis = require('redis');
const redisClient = redis.createClient();

const limiter = rateLimit({
  store: new RedisStore({
    client: redisClient,
    prefix: 'rate-limit:',
    expiry: 60 * 15 // 15 minutes in seconds
  }),
  max: 100
});

Input Validation

Always validate and sanitize all input data. Use schema validation libraries and type checking to ensure data meets expected formats and constraints.

Security
// Input validation with Joi (Node.js)
const Joi = require('joi');

// Schema definition
const userSchema = Joi.object({
  username: Joi.string().alphanum().min(3).max(30).required(),
  password: Joi.string().pattern(new RegExp('^[a-zA-Z0-9]{8,30}$')).required(),
  email: Joi.string().email().required(),
  birthYear: Joi.number().integer().min(1900).max(2022),
  role: Joi.string().valid('admin', 'user', 'editor')
});

// Validation middleware
const validateUser = (req, res, next) => {
  const { error } = userSchema.validate(req.body);
  if (error) {
    return res.status(400).json({ message: error.details[0].message });
  }
  next();
};

// Apply validation
app.post('/api/users', validateUser, (req, res) => {
  // Process valid user data
});

// TypeScript with zod
import { z } from 'zod';

const userSchema = z.object({
  username: z.string().min(3).max(30),
  password: z.string().min(8),
  email: z.string().email(),
  birthYear: z.number().int().min(1900).max(2022).optional(),
  role: z.enum(['admin', 'user', 'editor'])
});

type User = z.infer<typeof userSchema>;

// Validation
try {
  const validatedData = userSchema.parse(requestData);
  // Process valid data
} catch (error) {
  // Handle validation errors
}

Security Headers

Security headers protect against various attacks. Use libraries like Helmet to automatically apply recommended headers to HTTP responses.

Security
// Node.js with Helmet
const helmet = require('helmet');
app.use(helmet()); // Applies all default security headers

// Custom header configuration
app.use(
  helmet({
    contentSecurityPolicy: {
      directives: {
        defaultSrc: ["'self'"],
        scriptSrc: ["'self'", "trusted-scripts.com"]
      }
    },
    xFrameOptions: { action: 'deny' },
    hsts: {
      maxAge: 15552000, // 180 days in seconds
      includeSubDomains: true,
      preload: true
    },
    referrerPolicy: { policy: 'no-referrer' }
  })
);

// Common security headers
// X-XSS-Protection: Helps prevent XSS in older browsers
app.use(helmet.xssFilter());

// X-Content-Type-Options: Prevents MIME-type sniffing
app.use(helmet.noSniff());

// Strict-Transport-Security: Enforces HTTPS
app.use(helmet.hsts());

// X-Frame-Options: Prevents clickjacking
app.use(helmet.frameguard({ action: 'deny' }));

// Referrer-Policy: Controls referrer information
app.use(helmet.referrerPolicy({ policy: 'same-origin' }));

Network & Application Security

HTTPS Implementation

Always use HTTPS to encrypt data in transit. Implement proper TLS/SSL configuration and redirect all HTTP traffic to HTTPS.

Security
// Node.js HTTPS server
const https = require('https');
const fs = require('fs');
const express = require('express');
const app = express();

// Load SSL certificates
const options = {
  key: fs.readFileSync('path/to/private-key.pem'),
  cert: fs.readFileSync('path/to/certificate.pem'),
  // Optional: CA certificates
  ca: fs.readFileSync('path/to/ca-cert.pem'),
  // Modern TLS configuration
  minVersion: 'TLSv1.2',
  ciphers: 'TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256'
};

// Create HTTPS server
https.createServer(options, app).listen(443, () => {
  console.log('HTTPS Server running on port 443');
});

// Redirect HTTP to HTTPS
const http = require('http');
http.createServer((req, res) => {
  res.writeHead(301, { 'Location': 'https://' + req.headers.host + req.url });
  res.end();
}).listen(80);

// Express.js HTTPS redirect middleware
app.use((req, res, next) => {
  if (!req.secure && req.get('x-forwarded-proto') !== 'https') {
    return res.redirect('https://' + req.get('host') + req.url);
  }
  next();
});

Password Security

Store passwords using strong, adaptive hashing algorithms (like bcrypt, Argon2). Never store plaintext passwords and implement strong password policies.

Security
// Node.js with bcrypt
const bcrypt = require('bcrypt');

// Hashing a password
const hashPassword = async (password) => {
  const saltRounds = 12; // Higher is more secure but slower
  return await bcrypt.hash(password, saltRounds);
};

// Verifying a password
const verifyPassword = async (password, hash) => {
  return await bcrypt.compare(password, hash);
};

// Usage example
async function registerUser(username, password) {
  try {
    const hashedPassword = await hashPassword(password);
    // Store username and hashedPassword in database
    return { success: true };
  } catch (error) {
    return { success: false, error };
  }
}

async function loginUser(username, password) {
  try {
    // Get stored hash from database
    const user = await getUserFromDB(username);
    if (!user) {
      return { success: false, message: 'User not found' };
    }
    
    const isValid = await verifyPassword(password, user.passwordHash);
    if (isValid) {
      return { success: true, user };
    } else {
      return { success: false, message: 'Invalid password' };
    }
  } catch (error) {
    return { success: false, error };
  }
}

// Password policies
function validatePasswordStrength(password) {
  // At least 12 characters
  if (password.length < 12) return false;
  
  // Check for lowercase, uppercase, numbers, and special chars
  const hasLowercase = /[a-z]/.test(password);
  const hasUppercase = /[A-Z]/.test(password);
  const hasNumber = /[0-9]/.test(password);
  const hasSpecial = /[!@#$%^&*()_+-=[]{};':"\|,.<>/?]/.test(password);
  
  return hasLowercase && hasUppercase && hasNumber && hasSpecial;
}

File Upload Security

Secure file uploads by validating file types, scanning for malware, using random filenames, and storing files outside the webroot.

Security
// Node.js secure file upload with multer
const express = require('express');
const multer = require('multer');
const path = require('path');
const crypto = require('crypto');
const fs = require('fs');

const app = express();

// Define allowed file types
const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf'];
// Max file size (2MB)
const MAX_SIZE = 2 * 1024 * 1024;

// Create storage configuration
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './uploads');
  },
  filename: function (req, file, cb) {
    // Generate random filename to prevent path traversal
    const randomName = crypto.randomBytes(16).toString('hex');
    const ext = path.extname(file.originalname);
    cb(null, `${randomName}${ext}`);
  }
});

// Filter files based on mime type
const fileFilter = (req, file, cb) => {
  if (ALLOWED_TYPES.includes(file.mimetype)) {
    cb(null, true);
  } else {
    cb(new Error('Unsupported file type'), false);
  }
};

// Set up multer upload
const upload = multer({ 
  storage: storage,
  limits: { fileSize: MAX_SIZE },
  fileFilter: fileFilter
});

// Handle file upload
app.post('/upload', upload.single('file'), (req, res) => {
  if (!req.file) {
    return res.status(400).json({ message: 'No file uploaded' });
  }
  
  // Validate file content (example: check if image)
  if (req.file.mimetype.startsWith('image/')) {
    // Further validation like checking dimensions, etc.
  }
  
  // Success
  res.json({ 
    message: 'File uploaded successfully',
    filename: req.file.filename 
  });
}, (error, req, res, next) => {
  // Error handling
  res.status(400).json({ message: error.message });
});

Server Hardening

Server hardening reduces attack surface by securing configurations, limiting access, and disabling unnecessary services. Implement firewall rules, secure SSH, and regularly update systems.

Security
# Firewall configuration (ufw - Ubuntu)
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 22/tcp # SSH
sudo ufw allow 80/tcp # HTTP
sudo ufw allow 443/tcp # HTTPS
sudo ufw enable

# Secure SSH configuration (/etc/ssh/sshd_config)
Port 2222                      # Non-standard port
PermitRootLogin no             # Disable root login
PasswordAuthentication no      # Disable password auth
PubkeyAuthentication yes       # Use key-based auth
AllowUsers user1 user2         # Restrict users
MaxAuthTries 3                 # Limit auth attempts
ClientAliveInterval 300        # Connection timeout
ClientAliveCountMax 2

# Restart SSH service
sudo systemctl restart sshd

# Disable unnecessary services
sudo systemctl disable telnet
sudo systemctl disable rsh
sudo systemctl disable rlogin

# Update packages regularly
sudo apt update && sudo apt upgrade -y

# Automatic security updates (Ubuntu)
sudo apt install unattended-upgrades
sudo dpkg-reconfigure -plow unattended-upgrades

# File permissions
# Set secure permissions for config files
sudo chmod 600 /path/to/config/file
sudo chown root:root /path/to/config/file

# Set proper permissions for web directories
sudo find /var/www/html -type d -exec chmod 755 {} \;
sudo find /var/www/html -type f -exec chmod 644 {} \;

# Configure system-wide security limits (/etc/security/limits.conf)
* hard core 0                  # Disable core dumps
* soft nproc 1000              # Process limit 
* hard nproc 2000
* soft nofile 4096             # Open file limit
* hard nofile 8192

DevSecOps & Security Testing

OWASP Top 10 (2021)

The OWASP Top 10 represents the most critical web application security risks. Understand and address these vulnerabilities in your applications.

Security
// OWASP Top 10 (2021) Security Risks:

1. Broken Access Control
   - Implement proper authorization checks
   - Use RBAC (Role-Based Access Control)
   - Test for vertical and horizontal privilege escalation

2. Cryptographic Failures
   - Use strong encryption algorithms (AES-256, RSA 2048+)
   - Implement proper key management
   - Use TLS 1.2+ with secure cipher suites

3. Injection
   - Use parameterized queries and prepared statements
   - Validate and sanitize all input
   - Implement context-specific output encoding

4. Insecure Design
   - Perform threat modeling during design phase
   - Implement security by design principles
   - Use secure coding patterns and libraries

5. Security Misconfiguration
   - Use security hardening guidelines
   - Implement proper error handling
   - Remove unnecessary features, documentation, and samples

6. Vulnerable and Outdated Components
   - Regularly update dependencies
   - Use dependency scanners (npm audit, OWASP Dependency Check)
   - Have a patch management process

7. Identification and Authentication Failures
   - Implement MFA (Multi-Factor Authentication)
   - Use secure session management
   - Implement secure password policies

8. Software and Data Integrity Failures
   - Use digital signatures and integrity verification
   - Verify CI/CD pipeline integrity
   - Validate data from untrusted sources

9. Security Logging and Monitoring Failures
   - Implement comprehensive logging
   - Set up automated alerting on suspicious activities
   - Perform regular log reviews

10. Server-Side Request Forgery (SSRF)
    - Validate and sanitize input from user-supplied URLs
    - Use allowlists for domains and IP addresses
    - Implement network segmentation

Security Testing Tools

Integrate security testing tools into your development workflow. Use SAST, DAST, SCA, and IaC scanners to identify vulnerabilities early.

Security
# Static Application Security Testing (SAST)
# SonarQube setup with Docker
docker run -d --name sonarqube -p 9000:9000 sonarqube:latest

# Run SonarQube analysis
mvn sonar:sonar \
  -Dsonar.projectKey=my-project \
  -Dsonar.host.url=http://localhost:9000 \
  -Dsonar.login=[token]

# NodeJS static analysis with ESLint Security Plugin
npm install eslint eslint-plugin-security

# .eslintrc.js
module.exports = {
  plugins: ['security'],
  extends: ['plugin:security/recommended']
}

# Run ESLint security scan
npx eslint . --ext .js,.ts

# Dynamic Application Security Testing (DAST)
# OWASP ZAP automated scan
docker run -t owasp/zap2docker-stable zap-baseline.py \
  -t https://example.com \
  -r report.html

# Dependency scanning with OWASP Dependency-Check
# Maven project
mvn org.owasp:dependency-check-maven:check

# npm project
npm audit
# Fix vulnerabilities
npm audit fix

# Docker image scanning with Trivy
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock \
  -v $HOME/trivy-reports:/reports aquasec/trivy \
  image myapp:latest

# Infrastructure as Code security scanning with TFSec
tfsec ./terraform-code

# Secrets scanning with GitLeaks
gitleaks detect --source . --verbose

# API security testing with OWASP ZAP API Scan
docker run -v $(pwd):/zap/wrk/:rw -t owasp/zap2docker-stable \
  zap-api-scan.py -t https://api.example.com/openapi.json \
  -f openapi -r api-report.html

Container Security

Secure containers by using minimal base images, running as non-root users, scanning for vulnerabilities, and limiting container capabilities.

Security
# Docker security best practices

# Use official base images
FROM node:18-alpine AS build

# Set non-root user
RUN addgroup -g 1001 appgroup && \
    adduser -u 1001 -G appgroup -s /bin/sh -D appuser

# Minimize image layers and remove unnecessary tools
FROM node:18-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production && \
    npm cache clean --force

# Multi-stage builds to reduce attack surface
FROM node:18-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM node:18-alpine AS production
WORKDIR /app
COPY --from=build /app/dist ./dist
COPY --from=build /app/node_modules ./node_modules
# Copy only necessary files

# Run as non-root user
USER appuser

# Scan for vulnerabilities
# Trivy container scan
trivy image myapp:latest

# Docker content trust
export DOCKER_CONTENT_TRUST=1
docker pull alpine:latest
docker push mycompany/myapp:latest

# Limit container resources
docker run --rm -d \
  --cpus="1.0" \
  --memory="256m" \
  --pids-limit=100 \
  myapp:latest

# Security options
docker run --security-opt=no-new-privileges \
  --cap-drop=ALL \
  --cap-add=NET_BIND_SERVICE \
  myapp:latest

# Use read-only filesystem
docker run --read-only \
  --tmpfs /tmp \
  myapp:latest

# Kubernetes security context
apiVersion: v1
kind: Pod
metadata:
  name: secure-pod
spec:
  securityContext:
    runAsUser: 1001
    runAsGroup: 1001
    fsGroup: 1001
  containers:
  - name: myapp
    image: myapp:latest
    securityContext:
      allowPrivilegeEscalation: false
      readOnlyRootFilesystem: true
      capabilities:
        drop:
        - ALL

Security Incident Response

Have a well-defined security incident response plan to quickly detect, contain, and mitigate security incidents when they occur.

Security
# Security Incident Response Plan

### 1. Preparation
- Document systems and data
- Train team members
- Establish communication channels
- Create incident templates
- Define severity levels

### 2. Detection & Analysis
- Monitor security events
- Confirm and prioritize incident
- Document initial findings
  
### 3. Containment
# Network isolation command
sudo iptables -A INPUT -s <malicious_ip> -j DROP
sudo iptables -A OUTPUT -d <malicious_ip> -j DROP

# Isolate compromised system
sudo ip link set eth0 down

# Process management
ps aux | grep <suspicious_process>
sudo kill -9 <pid>

# Stop and disable compromised service
sudo systemctl stop <service>
sudo systemctl disable <service>

### 4. Eradication
# Remove malware
sudo rm -rf /path/to/malicious/file

# Close security holes
sudo apt update && sudo apt upgrade -y
sudo ufw enable

# Reset credentials
sudo passwd <user>

### 5. Recovery
# Restore from backup
sudo rsync -avz /backup/path/ /restore/path/

# Verify system integrity
sudo debsums -s  # Debian/Ubuntu
sudo rpm -Va     # RHEL/CentOS

# Perform security scanning
nmap -sV -p- localhost
sudo rkhunter --check

### 6. Lessons Learned
- Document the incident
- Update security measures
- Improve detection capabilities
- Train team on new procedures

### 7. Reporting
# Sample incident report structure
1. Executive Summary
2. Incident Timeline
3. Indicators of Compromise
4. Attack Vector and Root Cause
5. Impact Assessment
6. Remediation Actions
7. Recommendations

Data Privacy & Compliance

Personal Data Handling

Handle personal data responsibly by implementing data minimization, encryption, anonymization, and obtaining proper consent.

Security
// Data minimization principle
const collectUserData = (userData) => {
  // Only collect what's necessary
  const necessaryData = {
    email: userData.email,
    name: userData.name
    // Don't collect sensitive data if not required
  };
  
  return necessaryData;
};

// Data masking in logs
const logUserActivity = (user, activity) => {
  // Mask PII in logs
  const maskedUser = {
    id: user.id,
    email: user.email.replace(/(.{3})(.*)(@.*)/, '$1***$3'),
    name: `${user.name.charAt(0)}.`
  };
  
  console.log(`User ${JSON.stringify(maskedUser)} performed ${activity}`);
};

// Data encryption at rest (Node.js)
const crypto = require('crypto');

const encryptData = (data, key) => {
  const iv = crypto.randomBytes(16);
  const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
  
  let encrypted = cipher.update(JSON.stringify(data), 'utf8', 'hex');
  encrypted += cipher.final('hex');
  
  const authTag = cipher.getAuthTag();
  
  return {
    iv: iv.toString('hex'),
    encryptedData: encrypted,
    authTag: authTag.toString('hex')
  };
};

const decryptData = (encryptedObj, key) => {
  const decipher = crypto.createDecipheriv(
    'aes-256-gcm', 
    key, 
    Buffer.from(encryptedObj.iv, 'hex')
  );
  
  decipher.setAuthTag(Buffer.from(encryptedObj.authTag, 'hex'));
  
  let decrypted = decipher.update(encryptedObj.encryptedData, 'hex', 'utf8');
  decrypted += decipher.final('utf8');
  
  return JSON.parse(decrypted);
};

// GDPR-compliant consent
const getUserConsent = () => {
  return {
    template: `
      <div class="consent-form">
        <h3>Data Processing Consent</h3>
        <p>We collect the following data:</p>
        <ul>
          <li>Name - to personalize your experience</li>
          <li>Email - for account identification and communication</li>
          <li>IP Address - for security and fraud prevention</li>
        </ul>
        <p>Your data will be:</p>
        <ul>
          <li>Stored securely in our EU-based data center</li>
          <li>Retained for 12 months after your last activity</li>
          <li>Not shared with third parties without explicit consent</li>
        </ul>
        <p>
          <input type="checkbox" id="consent-essential" required>
          <label for="consent-essential">I consent to essential data processing (required)</label>
        </p>
        <p>
          <input type="checkbox" id="consent-marketing">
          <label for="consent-marketing">I consent to receiving marketing communications (optional)</label>
        </p>
        <p>
          <input type="checkbox" id="consent-analytics">
          <label for="consent-analytics">I consent to analytics cookies (optional)</label>
        </p>
        <button type="submit">Submit</button>
      </div>
    `
  };
};

Compliance Frameworks

Understand and implement compliance requirements for relevant regulations like GDPR, HIPAA, CCPA, PCI DSS, and others based on your data processing activities.

Security
// GDPR Compliance Checklist

// 1. Data Subject Rights Implementation
const handleDataSubjectRequest = async (userId, requestType) => {
  switch (requestType) {
    case 'ACCESS': {
      // Provide copy of personal data
      const userData = await getUserData(userId);
      return formatUserDataReport(userData);
    }
    case 'RECTIFICATION': {
      // Update inaccurate data
      return updateUserData(userId, newData);
    }
    case 'ERASURE': {
      // Right to be forgotten
      await deleteUserData(userId);
      await deleteRelatedData(userId);
      return { success: true, message: 'All user data deleted' };
    }
    case 'RESTRICTION': {
      // Restrict processing
      await flagUserDataRestricted(userId);
      return { success: true, message: 'Processing restricted' };
    }
    case 'PORTABILITY': {
      // Provide data in machine-readable format
      const userData = await getUserData(userId);
      return generatePortableFormat(userData, 'JSON');
    }
    case 'OBJECT': {
      // Object to processing
      await optOutFromProcessing(userId);
      return { success: true, message: 'Processing objection recorded' };
    }
  }
};

// 2. Data Breach Notification
const handleDataBreach = async (breachDetails) => {
  // Log the breach internally
  await logSecurityIncident({
    type: 'DATA_BREACH',
    timestamp: new Date(),
    details: breachDetails
  });
  
  // Assess risk to individuals
  const riskAssessment = assessRiskToIndividuals(breachDetails);
  
  if (riskAssessment.requiresNotification) {
    // Notify supervisory authority (within 72 hours)
    await notifySupervisoryAuthority({
      breachDetails,
      measuresToken: breachDetails.measures,
      possibleConsequences: riskAssessment.possibleConsequences
    });
    
    // If high risk to individuals, notify them directly
    if (riskAssessment.highRisk) {
      const affectedUsers = await getAffectedUsers(breachDetails.scope);
      await notifyAffectedIndividuals(affectedUsers, {
        breachDescription: breachDetails.description,
        contactDetails: PRIVACY_OFFICER_CONTACT,
        recommendedActions: riskAssessment.recommendedActions
      });
    }
  }
  
  return { success: true, handled: true };
};

// 3. Legitimate Interest Assessment
const performLIA = (purpose, necessity, balancing) => {
  return {
    purpose: {
      description: purpose.description,
      isLegitimate: purpose.isLegitimate,
      justification: purpose.justification
    },
    necessity: {
      isNecessary: necessity.isNecessary,
      justification: necessity.justification,
      alternatives: necessity.alternatives
    },
    balancingTest: {
      individualImpact: balancing.individualImpact,
      safeguards: balancing.safeguards,
      balance: balancing.balance,
      conclusion: balancing.conclusion
    },
    outcome: {
      proceedWithProcessing: 
        purpose.isLegitimate && 
        necessity.isNecessary && 
        balancing.conclusion === 'PASS'
    }
  };
};

// HIPAA Compliance Example (US Healthcare)
// PHI De-identification (Safe Harbor Method)
const deidentifyPHI = (patientData) => {
  // Remove 18 identifiers per HIPAA Safe Harbor
  return {
    birthYear: patientData.dateOfBirth.getFullYear(),
    // Remove month and day
    zipCode3: patientData.zipCode.substring(0, 3),
    // Truncate ZIP code to first 3 digits
    gender: patientData.gender,
    diagnoses: patientData.diagnoses,
    treatments: patientData.treatments,
    // Exclude any unique identifiers
  };
};

// PCI DSS - Credit Card Handling
// Never store full credit card data!
const processPayment = async (paymentDetails) => {
  // Only store last 4 digits for reference
  const lastFour = paymentDetails.cardNumber.slice(-4);
  
  // Use a payment processor to handle the actual transaction
  const paymentResult = await paymentGateway.processPayment({
    cardNumber: paymentDetails.cardNumber,
    expiryMonth: paymentDetails.expiryMonth,
    expiryYear: paymentDetails.expiryYear,
    cvv: paymentDetails.cvv,
    amount: paymentDetails.amount
  });
  
  // Store minimal payment reference
  await storePaymentReference({
    userId: paymentDetails.userId,
    paymentId: paymentResult.paymentId,
    amount: paymentDetails.amount,
    last4: lastFour,
    timestamp: new Date()
  });
  
  return {
    success: paymentResult.success,
    reference: paymentResult.paymentId
  };
};

Security - Interactive Developer Reference

Hover over code blocks to copy or run in live playground