Privacy Audit
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
# Find potential PII fields in TypeScript types, interfaces, and schemas
grep -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 columns
grep -rn --include="*.ts" -iE "(column|field|attribute).*\b(name|email|phone|address|ip|birth|ssn)\b" src/
# Find form fields collecting PII
grep -rn --include="*.tsx" --include="*.ts" -iE "(input|field|formField).*\b(name|email|phone|address|password)\b" src/
# Find analytics events transmitting PII
grep -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
| Finding | Regulation | Reference |
|---|---|---|
| PII collected without documented purpose | GDPR | Article 5(1)(b) - Purpose limitation |
| PII collected without legal basis | GDPR | Article 6(1) - Lawfulness of processing |
| No PII inventory maintained | GDPR | Article 30 - Records of processing activities |
| PII collected from California residents without disclosure | CCPA | Section 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
# Find cookie consent implementations
grep -rn --include="*.ts" --include="*.tsx" -iE "(cookie.?consent|consent.?banner|consent.?modal|cookie.?notice|gdpr.?banner)" src/
# Find consent state management
grep -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 consent
grep -rn --include="*.ts" --include="*.tsx" -iE "(gtag|analytics\.init|mixpanel\.init|segment\.load|hotjar|fbq|_paq)" src/
# Find consent preference persistence
grep -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
| Finding | Regulation | Reference |
|---|---|---|
| No consent obtained before tracking | GDPR | Article 7 - Conditions for consent |
| No granular consent categories | GDPR | Recital 43 - Freely given consent |
| No opt-out mechanism | CCPA | Section 1798.120 - Right to opt-out |
| Consent withdrawal harder than granting | GDPR | Article 7(3) - Right to withdraw consent |
| Pre-checked consent boxes | GDPR | Article 4(11) - Definition of consent (must be affirmative) |
Code Pattern: Consent-Gated Tracking
// UNSAFE: Tracking loads unconditionally
import analytics from "./analytics";
analytics.init("TRACKING_ID");
analytics.page();
// SAFE: Tracking gated on user consent
import 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
# Find Convex queries that return whole documents instead of picking fields
grep -rn --include="*.ts" -iE "return\s+await\s+ctx\.db\.(get|query)" convex/
# Find PII in log statements
grep -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 messages
grep -rn --include="*.ts" -iE "(throw new Error|reject\(|\.message\s*=).*\b(email|name|user|password)\b" src/
# Find data retention / TTL configuration
grep -rn --include="*.ts" -iE "(ttl|expir|retention|delete.?after|purge|cleanup|archive)" src/
# Find broad API responses returning full user objects
grep -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
| Finding | Regulation | Reference |
|---|---|---|
| Collecting data beyond stated purpose | GDPR | Article 5(1)(c) - Data minimization |
| No data retention limits | GDPR | Article 5(1)(e) - Storage limitation |
| PII in application logs | GDPR | Article 5(1)(f) - Integrity and confidentiality |
| Excessive data collection without business need | CCPA | Section 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.
import { v } from "convex/values";
import { query } from "./_generated/server";
// UNSAFE: returns the entire user document, including private fields
export const getUserBad = query({
args: { userId: v.id("users") },
handler: async (ctx, { userId }) => {
return await ctx.db.get(userId);
},
});
// SAFE: return only the public-facing fields
export 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
# Find third-party analytics and tracking scripts
grep -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 pixels
grep -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 widgets
grep -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/IP
grep -rn --include="*.ts" --include="*.tsx" --include="*.html" -iE "(cdn\.|cloudflare|jsdelivr|unpkg|cdnjs|fonts\.googleapis)" src/
# Find third-party SDK imports
grep -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
| Finding | Regulation | Reference |
|---|---|---|
| PII shared with third party without consent | GDPR | Article 44-49 - Transfer of personal data |
| No DPA with third-party processor | GDPR | Article 28 - Processor agreements |
| Selling/sharing personal information without opt-out | CCPA | Section 1798.120 - Right to opt-out of sale |
| Third-party tracking without disclosure | CCPA | Section 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
# Find database column definitions that may store PII unencrypted
grep -rn --include="*.ts" -iE "(column|field)\s*\(.*type.*\b(varchar|text|string)\b" src/
# Check for HTTPS enforcement
grep -rn --include="*.ts" -iE "(http://|redirect.*https|force.*ssl|hsts|strict.?transport)" src/
# Find client-side storage of sensitive data
grep -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 storage
grep -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
| Finding | Regulation | Reference |
|---|---|---|
| PII stored unencrypted | GDPR | Article 32 - Security of processing |
| Data transmitted over HTTP | GDPR | Article 5(1)(f) - Integrity and confidentiality |
| Passwords not properly hashed | GDPR | Article 32(1)(a) - Pseudonymisation and encryption |
| Sensitive data in client-side storage | GDPR | Article 25 - Data protection by design and by default |
Code Pattern: Encrypted PII Column
// UNSAFE: PII stored in plaintext column
@Column({ type: "varchar" })
email: string;
// SAFE: Application-level encryption for PII at rest
import { 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
# Find data export / download endpoints
grep -rn --include="*.ts" -iE "(export.?data|download.?data|data.?portability|user.?data.?export|takeout|archive.?data)" src/
# Find account deletion / right to erasure
grep -rn --include="*.ts" -iE "(delete.?account|remove.?account|erase.?data|right.?to.?erasure|account.?deletion|purge.?user|gdpr.?delete)" src/
# Find data access request handling
grep -rn --include="*.ts" -iE "(data.?request|subject.?access|sar\b|dsar\b|access.?request|data.?inquiry)" src/
# Find consent withdrawal mechanisms
grep -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
| Finding | Regulation | Reference |
|---|---|---|
| No data export capability | GDPR | Article 20 - Right to data portability |
| No account deletion mechanism | GDPR | Article 17 - Right to erasure |
| No data access request process | GDPR | Article 15 - Right of access |
| Cannot fulfill access requests within 45 days | CCPA | Section 1798.130 - Timing of response |
| No opt-out of data sale | CCPA | Section 1798.120 - Right to opt-out |
| Deletion does not cascade to processors | GDPR | Article 17(2) - Inform processors of erasure |
Code Pattern: Account Deletion
// UNSAFE: Soft-delete only, PII retained indefinitely
async function deleteAccount(userId: string): Promise<void> {
await db.users.update({ where: { id: userId }, data: { deletedAt: new Date() } });
}
// SAFE: Full erasure with cascade
async 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
# Find cookie setting operations
grep -rn --include="*.ts" --include="*.tsx" -iE "(document\.cookie|res\.cookie|setCookie|cookie\(|set-cookie)" src/
# Check cookie security flags
grep -rn --include="*.ts" -iE "(httpOnly|secure|sameSite|maxAge|expires|domain|path)" src/
# Find localStorage/sessionStorage usage with sensitive data
grep -rn --include="*.ts" --include="*.tsx" -iE "(localStorage|sessionStorage)\.(setItem|getItem|removeItem)" src/
# Detect browser fingerprinting techniques
grep -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, andSameSite=Strict(orLax) - 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
| Finding | Regulation | Reference |
|---|---|---|
| Non-essential cookies set without consent | GDPR | Article 5(3) ePrivacy Directive |
| Cookies missing Secure/HttpOnly flags | GDPR | Article 32 - Security of processing |
| Browser fingerprinting without consent | GDPR | Recital 30 - Online identifiers |
| No cookie inventory disclosed to users | GDPR | Article 13 - Information to be provided |
Code Pattern: Secure Cookie Configuration
// UNSAFE: Cookie with no security flags
res.cookie("session", token);
// SAFE: Cookie with full security configuration
res.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
# Find log statements that may contain PII
grep -rn --include="*.ts" -iE "(console\.(log|warn|error|info|debug)|logger\.(log|warn|error|info|debug|fatal))\s*\(" src/
# Find log configuration and retention settings
grep -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 resources
grep -rn --include="*.ts" -iE "(audit.?log|access.?log|data.?access|sensitive.?access|pii.?access)" src/
# Find structured logging configuration
grep -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
| Finding | Regulation | Reference |
|---|---|---|
| PII in application logs | GDPR | Article 5(1)(f) - Integrity and confidentiality |
| No log retention policy | GDPR | Article 5(1)(e) - Storage limitation |
| No audit trail for PII access | GDPR | Article 30 - Records of processing activities |
| Logs accessible without access control | GDPR | Article 32 - Security of processing |
Code Pattern: PII-Safe Logging
// UNSAFE: Logging PII directly
logger.info(`User registered: ${user.email}, name: ${user.fullName}`);
logger.error(`Failed login for ${email} from IP ${req.ip}`);
// SAFE: Redact PII in logs
function 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
# Find API route handlers returning user/PII data
grep -rn --include="*.ts" -iE "(res\.(json|send)|return.*(Response|json))\s*\(" src/
# Find GraphQL resolvers that may over-fetch
grep -rn --include="*.ts" -iE "(resolve|Query|Mutation|fieldResolver)" src/
# Find API response caching that may cache PII
grep -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 fields
grep -rn --include="*.ts" -E "return\s+await\s+ctx\.db\." convex/
# Find queries/mutations missing an auth check
grep -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
| Finding | Regulation | Reference |
|---|---|---|
| API returns unnecessary PII | GDPR | Article 5(1)(c) - Data minimization |
| No field-level access control on PII | GDPR | Article 25 - Data protection by design |
| PII cached in CDN or shared cache | GDPR | Article 32 - Security of processing |
| Bulk data extraction possible | CCPA | Section 1798.150 - Personal information security |
| No rate limiting on PII endpoints | GDPR | Article 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.
import { ConvexError, v } from "convex/values";
import { query } from "./_generated/server";
// UNSAFE: returns all fields to anyone who calls it
export 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 owner
export 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
| Regulation | Requirement | Status | Finding Reference |
|---|---|---|---|
| GDPR Art. 5(1)(c) | Data minimization | FAIL | #3 |
| GDPR Art. 7 | Consent | PASS | - |
| CCPA 1798.120 | Opt-out of sale | FAIL | #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