All skills
🔏

Privacy Audit

Security

Scan your app for privacy compliance issues. Checks data collection, consent management, personal data handling, data retention, cookie usage, and compliance with major privacy regulations in Europe, California, and beyond.

Skill prompt

Privacy Audit Skill

Perform a comprehensive privacy and data protection audit of a TypeScript codebase. All findings must reference specific files and line numbers, map to regulatory requirements (GDPR Article X, CCPA Section X), and include severity ratings.

Severity Ratings

  • CRITICAL: Active violation likely to trigger regulatory enforcement (e.g., PII transmitted unencrypted, no consent mechanism, no deletion capability)
  • HIGH: Significant compliance gap requiring prompt remediation (e.g., PII in logs, missing cookie flags, over-broad data collection)
  • MEDIUM: Best-practice violation that increases risk (e.g., missing data retention policy, excessive API response fields)
  • LOW: Minor improvement opportunity (e.g., missing audit trail for non-sensitive access, informational cookie without flag)

1. PII Detection

Scan the entire codebase for collection, storage, and transmission of personally identifiable information.

What to Search For
bash
# Find potential PII fields in TypeScript types, interfaces, and schemasgrep -rn --include="*.ts" --include="*.tsx" -iE "(firstName|lastName|fullName|email|phone|ssn|socialSecurity|dateOfBirth|dob|address|zipCode|postalCode|ipAddress|deviceId|geolocation|latitude|longitude|passport|driverLicense|nationalId|taxId)" src/
# Find database schema definitions with PII columnsgrep -rn --include="*.ts" -iE "(column|field|attribute).*\b(name|email|phone|address|ip|birth|ssn)\b" src/
# Find form fields collecting PIIgrep -rn --include="*.tsx" --include="*.ts" -iE "(input|field|formField).*\b(name|email|phone|address|password)\b" src/
# Find analytics events transmitting PIIgrep -rn --include="*.ts" --include="*.tsx" -iE "(track|analytics|event|identify|capture)\s*\(" src/
Checklist
  • Inventory all PII fields in database schemas (ORM models, migration files, SQL definitions)
  • Inventory all PII in API request/response types and interfaces
  • Inventory all form fields collecting user data
  • Identify PII transmitted in analytics/tracking events
  • Verify PII classification labels exist (sensitivity level, data category)
  • Check that PII fields have documented legal basis for collection
Regulatory Mapping
FindingRegulationReference
PII collected without documented purposeGDPRArticle 5(1)(b) - Purpose limitation
PII collected without legal basisGDPRArticle 6(1) - Lawfulness of processing
No PII inventory maintainedGDPRArticle 30 - Records of processing activities
PII collected from California residents without disclosureCCPASection 1798.100(b) - Right to know

2. Consent Management

Audit cookie consent implementation, consent-before-tracking enforcement, and opt-out mechanisms.

What to Search For
bash
# Find cookie consent implementationsgrep -rn --include="*.ts" --include="*.tsx" -iE "(cookie.?consent|consent.?banner|consent.?modal|cookie.?notice|gdpr.?banner)" src/
# Find consent state managementgrep -rn --include="*.ts" --include="*.tsx" -iE "(consent.?state|consent.?status|has.?consent|is.?consented|consent.?given|consent.?storage)" src/
# Find tracking initialization — must be gated on consentgrep -rn --include="*.ts" --include="*.tsx" -iE "(gtag|analytics\.init|mixpanel\.init|segment\.load|hotjar|fbq|_paq)" src/
# Find consent preference persistencegrep -rn --include="*.ts" --include="*.tsx" -iE "(localStorage|sessionStorage|cookie).*consent" src/
Checklist
  • Cookie consent banner exists and blocks tracking until accepted
  • Consent is obtained BEFORE any tracking scripts execute
  • Opt-out mechanism is functional and accessible
  • Consent state persists across sessions
  • Granular consent categories exist (necessary, analytics, marketing, preferences)
  • Consent withdrawal is as easy as giving consent
  • Consent records are stored with timestamp and version
  • Third-party scripts load only after relevant consent category is accepted
Regulatory Mapping
FindingRegulationReference
No consent obtained before trackingGDPRArticle 7 - Conditions for consent
No granular consent categoriesGDPRRecital 43 - Freely given consent
No opt-out mechanismCCPASection 1798.120 - Right to opt-out
Consent withdrawal harder than grantingGDPRArticle 7(3) - Right to withdraw consent
Pre-checked consent boxesGDPRArticle 4(11) - Definition of consent (must be affirmative)
Code Pattern: Consent-Gated Tracking
typescript
// UNSAFE: Tracking loads unconditionallyimport analytics from "./analytics";analytics.init("TRACKING_ID");analytics.page();
// SAFE: Tracking gated on user consentimport analytics from "./analytics";import { getConsentState } from "./consent";
const consent = getConsentState();if (consent.analytics) {  analytics.init("TRACKING_ID");  analytics.page();}

3. Data Minimization

Check for collection of excessive data, unnecessary storage, and PII leakage.

What to Search For
bash
# Find Convex queries that return whole documents instead of picking fieldsgrep -rn --include="*.ts" -iE "return\s+await\s+ctx\.db\.(get|query)" convex/
# Find PII in log statementsgrep -rn --include="*.ts" --include="*.tsx" -iE "(console\.(log|warn|error|info|debug)|logger\.(log|warn|error|info|debug))\s*\(.*\b(email|name|phone|address|password|token|ssn|ip)\b" src/
# Find PII in error messagesgrep -rn --include="*.ts" -iE "(throw new Error|reject\(|\.message\s*=).*\b(email|name|user|password)\b" src/
# Find data retention / TTL configurationgrep -rn --include="*.ts" -iE "(ttl|expir|retention|delete.?after|purge|cleanup|archive)" src/
# Find broad API responses returning full user objectsgrep -rn --include="*.ts" -iE "(res\.json|return|respond)\s*\(.*user[^I]" src/
Checklist
  • No SELECT * on tables containing PII — use explicit column lists
  • API responses do not include unnecessary PII fields
  • PII is not logged in application logs
  • PII is not included in error messages or stack traces
  • Data retention policies are defined and enforced programmatically
  • Temporary data (uploads, caches) has expiration configured
  • Form fields do not collect data unnecessary for the stated purpose
Regulatory Mapping
FindingRegulationReference
Collecting data beyond stated purposeGDPRArticle 5(1)(c) - Data minimization
No data retention limitsGDPRArticle 5(1)(e) - Storage limitation
PII in application logsGDPRArticle 5(1)(f) - Integrity and confidentiality
Excessive data collection without business needCCPASection 1798.100(c) - Collect only what is necessary
Code Pattern: Minimal Query Responses

In Convex, queries return whatever you send back from the handler. Returning the whole document leaks every field on it — including ones meant only for the server. Always pick out just the fields the client needs.

typescript
import { v } from "convex/values";import { query } from "./_generated/server";
// UNSAFE: returns the entire user document, including private fieldsexport const getUserBad = query({  args: { userId: v.id("users") },  handler: async (ctx, { userId }) => {    return await ctx.db.get(userId);  },});
// SAFE: return only the public-facing fieldsexport const getUser = query({  args: { userId: v.id("users") },  handler: async (ctx, { userId }) => {    const user = await ctx.db.get(userId);    if (!user) return null;    return { _id: user._id, displayName: user.displayName, avatarUrl: user.avatarUrl };  },});

4. Third-Party Data Sharing

Audit analytics scripts, advertising pixels, social embeds, CDN exposure, and SDK data flows.

What to Search For
bash
# Find third-party analytics and tracking scriptsgrep -rn --include="*.ts" --include="*.tsx" --include="*.html" -iE "(google.?analytics|gtag|ga\(|mixpanel|segment|amplitude|hotjar|heap|fullstory|posthog|plausible)" src/
# Find advertising and marketing pixelsgrep -rn --include="*.ts" --include="*.tsx" --include="*.html" -iE "(fbq|facebook.?pixel|google.?ads|gads|twitter.?pixel|linkedin.?insight|tiktok.?pixel|pinterest.?tag)" src/
# Find social media embeds and widgetsgrep -rn --include="*.ts" --include="*.tsx" --include="*.html" -iE "(facebook\.com/plugins|platform\.twitter|linkedin\.com/in|social.?embed|share.?button|addthis|sharethis)" src/
# Find external CDN references that may leak referrer/IPgrep -rn --include="*.ts" --include="*.tsx" --include="*.html" -iE "(cdn\.|cloudflare|jsdelivr|unpkg|cdnjs|fonts\.googleapis)" src/
# Find third-party SDK importsgrep -rn --include="*.ts" --include="*.tsx" -iE "import.*from\s+['\"](@?)(stripe|intercom|zendesk|hubspot|salesforce|sentry|bugsnag|datadog|newrelic)" src/
Checklist
  • Inventory all third-party scripts loaded in the application
  • Each third-party has a documented Data Processing Agreement (DPA)
  • Third-party scripts are gated behind consent categories
  • Data sent to third parties is minimized (no unnecessary PII)
  • Social media embeds do not load until user interaction (two-click pattern)
  • CDN requests include crossorigin="anonymous" where applicable
  • Referrer-Policy header is set to limit data leakage to third parties
  • Subresource Integrity (SRI) hashes on third-party scripts
Regulatory Mapping
FindingRegulationReference
PII shared with third party without consentGDPRArticle 44-49 - Transfer of personal data
No DPA with third-party processorGDPRArticle 28 - Processor agreements
Selling/sharing personal information without opt-outCCPASection 1798.120 - Right to opt-out of sale
Third-party tracking without disclosureCCPASection 1798.140(e) - Definition of business purpose

5. Data Storage & Encryption

Audit PII encryption at rest, secure transmission, and sensitive data in client-side storage.

What to Search For
bash
# Find database column definitions that may store PII unencryptedgrep -rn --include="*.ts" -iE "(column|field)\s*\(.*type.*\b(varchar|text|string)\b" src/
# Check for HTTPS enforcementgrep -rn --include="*.ts" -iE "(http://|redirect.*https|force.*ssl|hsts|strict.?transport)" src/
# Find client-side storage of sensitive datagrep -rn --include="*.ts" --include="*.tsx" -iE "(localStorage|sessionStorage)\.(setItem|getItem)\s*\(.*\b(token|password|email|user|auth|session|credit|ssn)\b" src/
# Find encryption usage (or lack thereof)grep -rn --include="*.ts" -iE "(crypto|encrypt|decrypt|cipher|aes|rsa|bcrypt|argon|scrypt|hash)" src/
# Find plaintext credential storagegrep -rn --include="*.ts" -iE "(password|secret|apiKey|api_key|token)\s*[:=]\s*['\"]" src/
Checklist
  • PII columns in database are encrypted at rest (application-level or database-level)
  • All data transmission uses HTTPS — HTTP redirects to HTTPS
  • HSTS header is configured with appropriate max-age
  • Passwords are hashed with Argon2 or bcrypt (never MD5/SHA1/SHA256 alone)
  • Encryption keys are managed securely (environment variables, KMS, vault)
  • Sensitive data is not stored in localStorage or sessionStorage
  • Database backups are encrypted
  • API keys and secrets are not hardcoded in source
Regulatory Mapping
FindingRegulationReference
PII stored unencryptedGDPRArticle 32 - Security of processing
Data transmitted over HTTPGDPRArticle 5(1)(f) - Integrity and confidentiality
Passwords not properly hashedGDPRArticle 32(1)(a) - Pseudonymisation and encryption
Sensitive data in client-side storageGDPRArticle 25 - Data protection by design and by default
Code Pattern: Encrypted PII Column
typescript
// UNSAFE: PII stored in plaintext column@Column({ type: "varchar" })email: string;
// SAFE: Application-level encryption for PII at restimport { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
const ALGORITHM = "aes-256-gcm";
function encryptPII(plaintext: string, key: Buffer): string {  const iv = randomBytes(16);  const cipher = createCipheriv(ALGORITHM, key, iv);  const encrypted = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);  const authTag = cipher.getAuthTag();  return Buffer.concat([iv, authTag, encrypted]).toString("base64");}
function decryptPII(ciphertext: string, key: Buffer): string {  const data = Buffer.from(ciphertext, "base64");  const iv = data.subarray(0, 16);  const authTag = data.subarray(16, 32);  const encrypted = data.subarray(32);  const decipher = createDecipheriv(ALGORITHM, key, iv);  decipher.setAuthTag(authTag);  return decipher.update(encrypted) + decipher.final("utf8");}

6. User Rights (GDPR / CCPA)

Audit data export, account deletion, data portability, access requests, and consent withdrawal.

What to Search For
bash
# Find data export / download endpointsgrep -rn --include="*.ts" -iE "(export.?data|download.?data|data.?portability|user.?data.?export|takeout|archive.?data)" src/
# Find account deletion / right to erasuregrep -rn --include="*.ts" -iE "(delete.?account|remove.?account|erase.?data|right.?to.?erasure|account.?deletion|purge.?user|gdpr.?delete)" src/
# Find data access request handlinggrep -rn --include="*.ts" -iE "(data.?request|subject.?access|sar\b|dsar\b|access.?request|data.?inquiry)" src/
# Find consent withdrawal mechanismsgrep -rn --include="*.ts" --include="*.tsx" -iE "(withdraw.?consent|revoke.?consent|opt.?out|unsubscribe|manage.?preferences|privacy.?settings)" src/
Checklist
  • Data export endpoint exists and returns all user data in machine-readable format (JSON/CSV)
  • Account deletion fully removes or anonymizes all PII (including backups, logs, caches)
  • Account deletion cascades to third-party services (analytics, email providers, CRMs)
  • Data access request can be fulfilled within 30 days (GDPR) / 45 days (CCPA)
  • Consent withdrawal mechanism exists and halts all non-essential processing
  • Deleted accounts cannot be reconstructed from remaining data
  • Soft-delete includes a hard-delete schedule (e.g., 30 days to final purge)
  • Data portability format is interoperable (standard JSON schema)
Regulatory Mapping
FindingRegulationReference
No data export capabilityGDPRArticle 20 - Right to data portability
No account deletion mechanismGDPRArticle 17 - Right to erasure
No data access request processGDPRArticle 15 - Right of access
Cannot fulfill access requests within 45 daysCCPASection 1798.130 - Timing of response
No opt-out of data saleCCPASection 1798.120 - Right to opt-out
Deletion does not cascade to processorsGDPRArticle 17(2) - Inform processors of erasure
Code Pattern: Account Deletion
typescript
// UNSAFE: Soft-delete only, PII retained indefinitelyasync function deleteAccount(userId: string): Promise<void> {  await db.users.update({ where: { id: userId }, data: { deletedAt: new Date() } });}
// SAFE: Full erasure with cascadeasync function deleteAccount(userId: string): Promise<void> {  // 1. Export user data for compliance record  const userData = await exportUserData(userId);  await archiveForCompliance(userId, userData);
  // 2. Delete from third-party services  await analytics.deleteUser(userId);  await emailProvider.deleteContact(userId);
  // 3. Anonymize records that must be retained (e.g., financial)  await db.orders.updateMany({    where: { userId },    data: { userId: "DELETED", email: "deleted@anonymized.local" },  });
  // 4. Hard-delete user PII  await db.userProfiles.deleteMany({ where: { userId } });  await db.sessions.deleteMany({ where: { userId } });  await db.users.delete({ where: { id: userId } });
  // 5. Purge from caches  await cache.invalidatePattern(`user:${userId}:*`);}

7. Cookie & Tracking Audit

Inventory all cookies, check security flags, audit localStorage/sessionStorage, and detect fingerprinting.

What to Search For
bash
# Find cookie setting operationsgrep -rn --include="*.ts" --include="*.tsx" -iE "(document\.cookie|res\.cookie|setCookie|cookie\(|set-cookie)" src/
# Check cookie security flagsgrep -rn --include="*.ts" -iE "(httpOnly|secure|sameSite|maxAge|expires|domain|path)" src/
# Find localStorage/sessionStorage usage with sensitive datagrep -rn --include="*.ts" --include="*.tsx" -iE "(localStorage|sessionStorage)\.(setItem|getItem|removeItem)" src/
# Detect browser fingerprinting techniquesgrep -rn --include="*.ts" --include="*.tsx" -iE "(navigator\.(userAgent|language|platform|plugins|hardwareConcurrency)|screen\.(width|height|colorDepth)|canvas.?fingerprint|webgl.?fingerprint|AudioContext)" src/
Checklist
  • Complete cookie inventory with purpose, duration, and category
  • All session cookies use Secure, HttpOnly, and SameSite=Strict (or Lax)
  • Session cookies have appropriate expiration (not excessively long)
  • Persistent cookies have justified retention periods
  • No sensitive data (tokens, PII) in localStorage or sessionStorage
  • No browser fingerprinting without explicit consent
  • Cookie names do not reveal technology stack or internal identifiers
  • Third-party cookies are inventoried and consent-gated
Regulatory Mapping
FindingRegulationReference
Non-essential cookies set without consentGDPRArticle 5(3) ePrivacy Directive
Cookies missing Secure/HttpOnly flagsGDPRArticle 32 - Security of processing
Browser fingerprinting without consentGDPRRecital 30 - Online identifiers
No cookie inventory disclosed to usersGDPRArticle 13 - Information to be provided
Code Pattern: Secure Cookie Configuration
typescript
// UNSAFE: Cookie with no security flagsres.cookie("session", token);
// SAFE: Cookie with full security configurationres.cookie("session", token, {  httpOnly: true,  secure: true,  sameSite: "strict",  maxAge: 24 * 60 * 60 * 1000, // 24 hours  path: "/",  domain: ".example.com",});

8. Logging & Monitoring

Audit logs for PII leakage, retention policies, access logging, and audit trails.

What to Search For
bash
# Find log statements that may contain PIIgrep -rn --include="*.ts" -iE "(console\.(log|warn|error|info|debug)|logger\.(log|warn|error|info|debug|fatal))\s*\(" src/
# Find log configuration and retention settingsgrep -rn --include="*.ts" --include="*.json" --include="*.yaml" -iE "(log.?retention|log.?rotate|log.?level|log.?format|maxFiles|maxSize)" src/ config/
# Find access logging for sensitive resourcesgrep -rn --include="*.ts" -iE "(audit.?log|access.?log|data.?access|sensitive.?access|pii.?access)" src/
# Find structured logging configurationgrep -rn --include="*.ts" -iE "(pino|winston|bunyan|log4js|morgan|logger.?config)" src/
Checklist
  • No PII appears in application logs (use redaction/masking)
  • Log retention policy is defined and enforced (auto-rotation/deletion)
  • Access to sensitive data is logged with user identity and timestamp
  • Audit trail exists for PII access, modification, and deletion
  • Log files are not publicly accessible
  • Log aggregation services (Datadog, Sentry, etc.) have PII scrubbing configured
  • Stack traces in production do not expose PII
  • Structured logging format used (not string interpolation of user data)
Regulatory Mapping
FindingRegulationReference
PII in application logsGDPRArticle 5(1)(f) - Integrity and confidentiality
No log retention policyGDPRArticle 5(1)(e) - Storage limitation
No audit trail for PII accessGDPRArticle 30 - Records of processing activities
Logs accessible without access controlGDPRArticle 32 - Security of processing
Code Pattern: PII-Safe Logging
typescript
// UNSAFE: Logging PII directlylogger.info(`User registered: ${user.email}, name: ${user.fullName}`);logger.error(`Failed login for ${email} from IP ${req.ip}`);
// SAFE: Redact PII in logsfunction redactEmail(email: string): string {  const [local, domain] = email.split("@");  return `${local[0]}***@${domain}`;}
function redactPII(obj: Record<string, unknown>): Record<string, unknown> {  const sensitive = new Set(["email", "name", "phone", "address", "ip", "ssn"]);  return Object.fromEntries(    Object.entries(obj).map(([key, value]) =>      sensitive.has(key.toLowerCase()) ? [key, "[REDACTED]"] : [key, value],    ),  );}
logger.info({ userId: user.id, event: "registration" }, "User registered");logger.error({ userId: "[UNKNOWN]", event: "login_failed", ip: "[REDACTED]" }, "Failed login");

9. API Privacy

Audit API responses for unnecessary data, missing field-level permissions, over-fetching, and caching of sensitive data.

What to Search For
bash
# Find API route handlers returning user/PII datagrep -rn --include="*.ts" -iE "(res\.(json|send)|return.*(Response|json))\s*\(" src/
# Find GraphQL resolvers that may over-fetchgrep -rn --include="*.ts" -iE "(resolve|Query|Mutation|fieldResolver)" src/
# Find API response caching that may cache PIIgrep -rn --include="*.ts" -iE "(cache.?control|cache.?set|redis\.set|memcached|cdn.?cache|stale.?while)" src/
# Find Convex queries that return raw documents without picking fieldsgrep -rn --include="*.ts" -E "return\s+await\s+ctx\.db\." convex/
# Find queries/mutations missing an auth checkgrep -rLn --include="*.ts" "ctx.auth.getUserIdentity" convex/
Checklist
  • API responses include only fields necessary for the client
  • Sensitive fields are excluded from default serialization (use allowlists, not denylists)
  • GraphQL queries cannot fetch arbitrary depth/breadth of PII
  • API responses containing PII use Cache-Control: no-store
  • Field-level permissions enforce who can see which fields
  • Pagination limits prevent bulk data extraction
  • API rate limiting prevents enumeration attacks
  • Response schemas are documented and reviewed for data exposure
Regulatory Mapping
FindingRegulationReference
API returns unnecessary PIIGDPRArticle 5(1)(c) - Data minimization
No field-level access control on PIIGDPRArticle 25 - Data protection by design
PII cached in CDN or shared cacheGDPRArticle 32 - Security of processing
Bulk data extraction possibleCCPASection 1798.150 - Personal information security
No rate limiting on PII endpointsGDPRArticle 32(1)(b) - Ability to ensure ongoing confidentiality
Code Pattern: Privacy-Safe Convex Query

In a Hercules app, the signed-in user comes from Hercules Auth via ctx.auth.getUserIdentity(). Throw a ConvexError so the client can handle the failure cleanly.

typescript
import { ConvexError, v } from "convex/values";import { query } from "./_generated/server";
// UNSAFE: returns all fields to anyone who calls itexport const getUserBad = query({  args: { userId: v.id("users") },  handler: async (ctx, { userId }) => {    return await ctx.db.get(userId);  },});
// SAFE: require auth, pick only public fields, expose private fields only to the ownerexport const getUser = query({  args: { userId: v.id("users") },  handler: async (ctx, { userId }) => {    const identity = await ctx.auth.getUserIdentity();    if (!identity) {      throw new ConvexError({ code: "UNAUTHENTICATED" });    }
    const user = await ctx.db.get(userId);    if (!user) return null;
    const isSelf = user.tokenIdentifier === identity.tokenIdentifier;    return {      _id: user._id,      displayName: user.displayName,      avatarUrl: user.avatarUrl,      // Email is only visible to the owner of the account      email: isSelf ? user.email : undefined,    };  },});

Audit Output Format

Structure audit findings as follows:

## Privacy Audit Report
### Summary- Total findings: [N]- Critical: [N] | High: [N] | Medium: [N] | Low: [N]
### Findings
#### [SEVERITY] Finding Title- **File**: `src/path/to/file.ts:42`- **Category**: [PII Detection | Consent | Data Minimization | Third-Party | Encryption | User Rights | Cookies | Logging | API Privacy]- **Regulation**: GDPR Article X / CCPA Section Y- **Description**: Clear explanation of the issue.- **Current Code**:  ```typescript  // problematic code snippet
  • Recommended Fix:
    typescript
    // corrected code snippet
Compliance Matrix
RegulationRequirementStatusFinding Reference
GDPR Art. 5(1)(c)Data minimizationFAIL#3
GDPR Art. 7ConsentPASS-
CCPA 1798.120Opt-out of saleFAIL#7

## When to Apply This Skill
Use this skill when:
- Auditing a TypeScript application for GDPR or CCPA compliance- Preparing for a privacy impact assessment (PIA/DPIA)- Reviewing data collection and processing practices- Checking third-party integrations for data leakage- Verifying user rights implementation (export, deletion, access)- Assessing cookie and tracking compliance- Reviewing API endpoints for data minimization- Investigating PII in logs, errors, or caches