📦 deps(thirdparty): update snapshots

This commit is contained in:
ci[bot]
2026-06-21 09:15:23 +00:00
parent 0e1bb1aef3
commit 3d137606c0
805 changed files with 93512 additions and 4532 deletions
@@ -0,0 +1,19 @@
{
"name": "antigravity-bundle-aas-privacy-compliance-engineering",
"version": "13.0.0",
"description": "Editorial \"AAS Privacy & Compliance Engineering\" bundle for Claude Code from Antigravity Awesome Skills.",
"author": {
"name": "sickn33 and contributors",
"url": "https://github.com/sickn33/antigravity-awesome-skills"
},
"homepage": "https://github.com/sickn33/antigravity-awesome-skills",
"repository": "https://github.com/sickn33/antigravity-awesome-skills",
"license": "MIT",
"keywords": [
"claude-code",
"skills",
"bundle",
"aas-privacy-compliance-engineering",
"antigravity-awesome-skills"
]
}
@@ -0,0 +1,38 @@
{
"name": "agyb-aas-privacy-compliance-engineering",
"version": "13.0.0",
"description": "Install the \"AAS Privacy & Compliance Engineering\" workflow plugin from Antigravity Awesome Skills.",
"author": {
"name": "sickn33 and contributors",
"url": "https://github.com/sickn33/antigravity-awesome-skills"
},
"homepage": "https://github.com/sickn33/antigravity-awesome-skills",
"repository": "https://github.com/sickn33/antigravity-awesome-skills",
"license": "MIT",
"keywords": [
"codex",
"skills",
"bundle",
"aas-privacy-compliance-engineering",
"productivity"
],
"skills": "./skills/",
"interface": {
"displayName": "AAS Privacy & Compliance Engineering",
"shortDescription": "Engineer privacy and compliance controls with GDPR, PCI, compliance checks, cloud posture, specs, and security review.",
"longDescription": "Engineer privacy and compliance controls with GDPR, PCI, compliance checks, cloud posture, specs, and security review. Uses existing privacy, GDPR, PCI, compliance, cloud, spec, and security review skills to create a practical engineering compliance workflow. Recommended for: SaaS teams, AI app teams, Compliance-sensitive engineering teams. Not for: Legal advice as a substitute for counsel, Offensive security testing. Covers Privacy By Design, Gdpr Data Handling, and 5 more skills.",
"developerName": "sickn33 and contributors",
"category": "Specialized Product Plugins - Next Wave",
"capabilities": [
"Interactive",
"Write"
],
"websiteURL": "https://github.com/sickn33/antigravity-awesome-skills",
"brandColor": "#111827",
"defaultPrompt": [
"Use this plugin to review this feature for privacy-by-design, GDPR handling, PCI exposure, and security controls.",
"Use this plugin to map compliance-sensitive data flows and identify engineering changes before launch.",
"Use this plugin to check whether this implementation matches the spec and expected compliance controls."
]
}
}
@@ -0,0 +1,504 @@
---
name: cc-skill-security-review
description: "This skill ensures all code follows security best practices and identifies potential vulnerabilities. Use when implementing authentication or authorization, handling user input or file uploads, or creating new API endpoints."
risk: unknown
source: community
date_added: "2026-02-27"
---
# Security Review Skill
This skill ensures all code follows security best practices and identifies potential vulnerabilities.
## When to Use
- Implementing authentication or authorization
- Handling user input or file uploads
- Creating new API endpoints
- Working with secrets or credentials
- Implementing payment features
- Storing or transmitting sensitive data
- Integrating third-party APIs
## Security Checklist
### 1. Secrets Management
#### ❌ NEVER Do This
```typescript
const apiKey = "sk-proj-xxxxx" // Hardcoded secret
const dbPassword = "password123" // In source code
```
#### ✅ ALWAYS Do This
```typescript
const apiKey = process.env.OPENAI_API_KEY
const dbUrl = process.env.DATABASE_URL
// Verify secrets exist
if (!apiKey) {
throw new Error('OPENAI_API_KEY not configured')
}
```
#### Verification Steps
- [ ] No hardcoded API keys, tokens, or passwords
- [ ] All secrets in environment variables
- [ ] `.env.local` in .gitignore
- [ ] No secrets in git history
- [ ] Production secrets in hosting platform (Vercel, Railway)
### 2. Input Validation
#### Always Validate User Input
```typescript
import { z } from 'zod'
// Define validation schema
const CreateUserSchema = z.object({
email: z.string().email(),
name: z.string().min(1).max(100),
age: z.number().int().min(0).max(150)
})
// Validate before processing
export async function createUser(input: unknown) {
try {
const validated = CreateUserSchema.parse(input)
return await db.users.create(validated)
} catch (error) {
if (error instanceof z.ZodError) {
return { success: false, errors: error.errors }
}
throw error
}
}
```
#### File Upload Validation
```typescript
function validateFileUpload(file: File) {
// Size check (5MB max)
const maxSize = 5 * 1024 * 1024
if (file.size > maxSize) {
throw new Error('File too large (max 5MB)')
}
// Type check
const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']
if (!allowedTypes.includes(file.type)) {
throw new Error('Invalid file type')
}
// Extension check
const allowedExtensions = ['.jpg', '.jpeg', '.png', '.gif']
const extension = file.name.toLowerCase().match(/\.[^.]+$/)?.[0]
if (!extension || !allowedExtensions.includes(extension)) {
throw new Error('Invalid file extension')
}
return true
}
```
#### Verification Steps
- [ ] All user inputs validated with schemas
- [ ] File uploads restricted (size, type, extension)
- [ ] No direct use of user input in queries
- [ ] Whitelist validation (not blacklist)
- [ ] Error messages don't leak sensitive info
### 3. SQL Injection Prevention
#### ❌ NEVER Concatenate SQL
```typescript
// DANGEROUS - SQL Injection vulnerability
const query = `SELECT * FROM users WHERE email = '${userEmail}'`
await db.query(query)
```
#### ✅ ALWAYS Use Parameterized Queries
```typescript
// Safe - parameterized query
const { data } = await supabase
.from('users')
.select('*')
.eq('email', userEmail)
// Or with raw SQL
await db.query(
'SELECT * FROM users WHERE email = $1',
[userEmail]
)
```
#### Verification Steps
- [ ] All database queries use parameterized queries
- [ ] No string concatenation in SQL
- [ ] ORM/query builder used correctly
- [ ] Supabase queries properly sanitized
### 4. Authentication & Authorization
#### JWT Token Handling
```typescript
// ❌ WRONG: localStorage (vulnerable to XSS)
localStorage.setItem('token', token)
// ✅ CORRECT: httpOnly cookies
res.setHeader('Set-Cookie',
`token=${token}; HttpOnly; Secure; SameSite=Strict; Max-Age=3600`)
```
#### Authorization Checks
```typescript
export async function deleteUser(userId: string, requesterId: string) {
// ALWAYS verify authorization first
const requester = await db.users.findUnique({
where: { id: requesterId }
})
if (requester.role !== 'admin') {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 403 }
)
}
// Proceed with deletion
await db.users.delete({ where: { id: userId } })
}
```
#### Row Level Security (Supabase)
```sql
-- Enable RLS on all tables
ALTER TABLE users ENABLE ROW LEVEL SECURITY;
-- Users can only view their own data
CREATE POLICY "Users view own data"
ON users FOR SELECT
USING (auth.uid() = id);
-- Users can only update their own data
CREATE POLICY "Users update own data"
ON users FOR UPDATE
USING (auth.uid() = id);
```
#### Verification Steps
- [ ] Tokens stored in httpOnly cookies (not localStorage)
- [ ] Authorization checks before sensitive operations
- [ ] Row Level Security enabled in Supabase
- [ ] Role-based access control implemented
- [ ] Session management secure
### 5. XSS Prevention
#### Sanitize HTML
```typescript
import DOMPurify from 'isomorphic-dompurify'
// ALWAYS sanitize user-provided HTML
function renderUserContent(html: string) {
const clean = DOMPurify.sanitize(html, {
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'p'],
ALLOWED_ATTR: []
})
return <div dangerouslySetInnerHTML={{ __html: clean }} />
}
```
#### Content Security Policy
```typescript
// next.config.js
const securityHeaders = [
{
key: 'Content-Security-Policy',
value: `
default-src 'self';
script-src 'self' 'unsafe-eval' 'unsafe-inline';
style-src 'self' 'unsafe-inline';
img-src 'self' data: https:;
font-src 'self';
connect-src 'self' https://api.example.com;
`.replace(/\s{2,}/g, ' ').trim()
}
]
```
#### Verification Steps
- [ ] User-provided HTML sanitized
- [ ] CSP headers configured
- [ ] No unvalidated dynamic content rendering
- [ ] React's built-in XSS protection used
### 6. CSRF Protection
#### CSRF Tokens
```typescript
import { csrf } from '@/lib/csrf'
export async function POST(request: Request) {
const token = request.headers.get('X-CSRF-Token')
if (!csrf.verify(token)) {
return NextResponse.json(
{ error: 'Invalid CSRF token' },
{ status: 403 }
)
}
// Process request
}
```
#### SameSite Cookies
```typescript
res.setHeader('Set-Cookie',
`session=${sessionId}; HttpOnly; Secure; SameSite=Strict`)
```
#### Verification Steps
- [ ] CSRF tokens on state-changing operations
- [ ] SameSite=Strict on all cookies
- [ ] Double-submit cookie pattern implemented
### 7. Rate Limiting
#### API Rate Limiting
```typescript
import rateLimit from 'express-rate-limit'
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // 100 requests per window
message: 'Too many requests'
})
// Apply to routes
app.use('/api/', limiter)
```
#### Expensive Operations
```typescript
// Aggressive rate limiting for searches
const searchLimiter = rateLimit({
windowMs: 60 * 1000, // 1 minute
max: 10, // 10 requests per minute
message: 'Too many search requests'
})
app.use('/api/search', searchLimiter)
```
#### Verification Steps
- [ ] Rate limiting on all API endpoints
- [ ] Stricter limits on expensive operations
- [ ] IP-based rate limiting
- [ ] User-based rate limiting (authenticated)
### 8. Sensitive Data Exposure
#### Logging
```typescript
// ❌ WRONG: Logging sensitive data
console.log('User login:', { email, password })
console.log('Payment:', { cardNumber, cvv })
// ✅ CORRECT: Redact sensitive data
console.log('User login:', { email, userId })
console.log('Payment:', { last4: card.last4, userId })
```
#### Error Messages
```typescript
// ❌ WRONG: Exposing internal details
catch (error) {
return NextResponse.json(
{ error: error.message, stack: error.stack },
{ status: 500 }
)
}
// ✅ CORRECT: Generic error messages
catch (error) {
console.error('Internal error:', error)
return NextResponse.json(
{ error: 'An error occurred. Please try again.' },
{ status: 500 }
)
}
```
#### Verification Steps
- [ ] No passwords, tokens, or secrets in logs
- [ ] Error messages generic for users
- [ ] Detailed errors only in server logs
- [ ] No stack traces exposed to users
### 9. Blockchain Security (Solana)
#### Wallet Verification
```typescript
import { verify } from '@solana/web3.js'
async function verifyWalletOwnership(
publicKey: string,
signature: string,
message: string
) {
try {
const isValid = verify(
Buffer.from(message),
Buffer.from(signature, 'base64'),
Buffer.from(publicKey, 'base64')
)
return isValid
} catch (error) {
return false
}
}
```
#### Transaction Verification
```typescript
async function verifyTransaction(transaction: Transaction) {
// Verify recipient
if (transaction.to !== expectedRecipient) {
throw new Error('Invalid recipient')
}
// Verify amount
if (transaction.amount > maxAmount) {
throw new Error('Amount exceeds limit')
}
// Verify user has sufficient balance
const balance = await getBalance(transaction.from)
if (balance < transaction.amount) {
throw new Error('Insufficient balance')
}
return true
}
```
#### Verification Steps
- [ ] Wallet signatures verified
- [ ] Transaction details validated
- [ ] Balance checks before transactions
- [ ] No blind transaction signing
### 10. Dependency Security
#### Regular Updates
```bash
# Check for vulnerabilities
npm audit
# Fix automatically fixable issues
npm audit fix
# Update dependencies
npm update
# Check for outdated packages
npm outdated
```
#### Lock Files
```bash
# ALWAYS commit lock files
git add package-lock.json
# Use in CI/CD for reproducible builds
npm ci # Instead of npm install
```
#### Verification Steps
- [ ] Dependencies up to date
- [ ] No known vulnerabilities (npm audit clean)
- [ ] Lock files committed
- [ ] Dependabot enabled on GitHub
- [ ] Regular security updates
## Security Testing
### Automated Security Tests
```typescript
// Test authentication
test('requires authentication', async () => {
const response = await fetch('/api/protected')
expect(response.status).toBe(401)
})
// Test authorization
test('requires admin role', async () => {
const response = await fetch('/api/admin', {
headers: { Authorization: `Bearer ${userToken}` }
})
expect(response.status).toBe(403)
})
// Test input validation
test('rejects invalid input', async () => {
const response = await fetch('/api/users', {
method: 'POST',
body: JSON.stringify({ email: 'not-an-email' })
})
expect(response.status).toBe(400)
})
// Test rate limiting
test('enforces rate limits', async () => {
const requests = Array(101).fill(null).map(() =>
fetch('/api/endpoint')
)
const responses = await Promise.all(requests)
const tooManyRequests = responses.filter(r => r.status === 429)
expect(tooManyRequests.length).toBeGreaterThan(0)
})
```
## Pre-Deployment Security Checklist
Before ANY production deployment:
- [ ] **Secrets**: No hardcoded secrets, all in env vars
- [ ] **Input Validation**: All user inputs validated
- [ ] **SQL Injection**: All queries parameterized
- [ ] **XSS**: User content sanitized
- [ ] **CSRF**: Protection enabled
- [ ] **Authentication**: Proper token handling
- [ ] **Authorization**: Role checks in place
- [ ] **Rate Limiting**: Enabled on all endpoints
- [ ] **HTTPS**: Enforced in production
- [ ] **Security Headers**: CSP, X-Frame-Options configured
- [ ] **Error Handling**: No sensitive data in errors
- [ ] **Logging**: No sensitive data logged
- [ ] **Dependencies**: Up to date, no vulnerabilities
- [ ] **Row Level Security**: Enabled in Supabase
- [ ] **CORS**: Properly configured
- [ ] **File Uploads**: Validated (size, type)
- [ ] **Wallet Signatures**: Verified (if blockchain)
## Resources
- [OWASP Top 10](https://owasp.org/www-project-top-ten/)
- [Next.js Security](https://nextjs.org/docs/security)
- [Supabase Security](https://supabase.com/docs/guides/auth)
- [Web Security Academy](https://portswigger.net/web-security)
---
**Remember**: Security is not optional. One vulnerability can compromise the entire platform. When in doubt, err on the side of caution.
### When to Use
This skill is applicable to execute the workflow or actions described in the overview.
## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.
@@ -0,0 +1,125 @@
---
name: fsi-compliance-checker
description: "Maps code, architecture, and infrastructure changes to specific control IDs in PCI-DSS v4.0 and MAS TRM (Singapore financial regulator), producing an audit-traceable findings report with per-control remediation."
category: security
risk: safe
source: community
source_repo: timwukp/agent-skills-best-practice
source_type: community
date_added: "2026-06-12"
author: timwukp
tags: [compliance, pci-dss, mas-trm, fintech, banking, security-review, audit, financial-services]
tools: [claude, cursor, gemini, codex, antigravity]
license: "MIT"
license_source: "https://github.com/timwukp/agent-skills-best-practice/blob/main/LICENSE"
---
# FSI Compliance Checker
## Overview
Maps a concrete change (code diff, architecture design, IaC, pipeline config) to the specific controls it touches in financial services compliance frameworks — PCI-DSS v4.0 for payment card data and MAS TRM for Singapore-regulated institutions — and reports gaps with actionable remediation. This is engineering-level compliance triage: it helps teams catch violations before audit, but it does not replace a qualified assessor (QSA) or the institution's compliance function. Say so in every report.
## When to Use This Skill
- Use when a change touches payment card data (PAN, CVV, track data) and needs a PCI-DSS check
- Use when reviewing changes at a Singapore-regulated financial institution against MAS TRM expectations
- Use when someone asks "is this compliant", "does logging this violate PCI", or requests a banking-regulation review of a diff, design, or Terraform change
- Do NOT use for generic security review (no framework involved), GDPR/SOC2/HIPAA (out of bundled scope), or legal advice
## How It Works
### Step 1: Select the framework
Load only the reference file(s) the engagement needs:
| Situation | Load |
|-----------|------|
| Payment card data is stored, processed, or transmitted | [pci-dss.md](pci-dss.md) |
| Singapore-regulated financial institution (bank, insurer, capital markets, major payment institution) | [mas-trm.md](mas-trm.md) |
| Both apply (e.g. Singapore bank handling cards) | Both files |
| Other jurisdictions/frameworks (SOX, GDPR, HKMA, APRA) | State they are out of scope; offer general secure-engineering review instead |
If the user hasn't said which applies, ask one question: what data does the change touch, and is the institution Singapore-regulated?
### Step 2: Scope the change
Identify what the diff/design actually touches: data elements (card data? customer PII? credentials?), trust boundaries, environments (production? DR?), and third parties.
### Step 3: Assess applicable controls
Select the applicable controls from the loaded reference file(s) — typically 5-15 controls, not the whole framework. List what you ruled out and why (one line each) so the scoping is auditable. Assess each as `Compliant` / `Gap` / `Needs evidence` (can't tell from the artifact — name the evidence required).
### Step 4: Report
Every Gap gets: the control ID, what's wrong in this specific change, concrete remediation, and severity (Critical = violation involving live regulated data; High = control absent; Medium = control partial/undocumented).
```markdown
# Compliance Review: [change title]
**Frameworks:** [PCI-DSS v4.0 / MAS TRM 2021] · **Date:** [YYYY-MM-DD]
**Scope:** [what was reviewed: files, design doc, pipeline]
> Engineering triage only — not a substitute for QSA assessment or the compliance function.
## Data & Boundary Analysis
- Data elements touched: [e.g. PAN (masked), customer NRIC, none]
- Environments/boundaries: [e.g. CDE-adjacent service, public API]
## Findings
| # | Control | Status | Severity | Finding | Remediation |
|---|---------|--------|----------|---------|-------------|
| 1 | [PCI 3.5.1] | Gap | Critical | [specific issue in this change] | [specific fix] |
## Ruled Out (not applicable)
- [Control area] — [one-line reason]
## Evidence Needed
- [Control]: [what artifact would demonstrate compliance]
```
### Step 5: Offer story conversion
Offer to turn findings into backlog items with the control ID in each story for traceability.
## Examples
### Example 1: Logging review
**User**: "Is this PCI-DSS compliant: we log the full request body of card authorization calls for debugging?"
**Skill**: Loads pci-dss.md → Critical findings against 3.3.1 (CVV must never be stored post-authorization — logs are storage), 3.4.1 (PAN display masking), 3.5.1 (PAN unreadable at rest); remediation: remove the log line or apply a field-allowlist redaction filter; flags downstream log-pipeline scoping (10.3.x); QSA disclaimer included.
### Example 2: Cloud migration
**User**: "Our Singapore bank is moving the customer notification service to a cloud region in another country. MAS TRM implications?"
**Skill**: Loads mas-trm.md → reviews against §11.5 (cloud: due diligence, data residency, exit strategy), flags the MAS Outsourcing Guidelines as a related instrument, asks what customer data the service touches before rating severity.
## Common FSI Engineering Triggers
Changes that almost always have compliance impact — check proactively when they appear in a diff:
- Logging statements near payment or authentication flows (PAN/CVV must never be logged; MAS TRM requires security event logging — both directions matter)
- New data stores or caches receiving customer or card data (encryption at rest, retention, residency)
- Authentication/session changes (MFA requirements, session timeout, credential storage)
- New third-party SDKs or API integrations (outsourcing/vendor controls, data flows leaving the boundary)
- Infrastructure changes touching network segmentation, security groups, or public exposure
- CI/CD changes that alter who/what can deploy to production (change management, segregation of duties)
## Guardrails
- Cite control IDs precisely (e.g. "PCI-DSS 8.3.6", "MAS TRM 9.1.1") so findings are traceable in audit tooling; the bundled reference files carry the ID schemes.
- Severity discipline: don't inflate. A missing comment is not a Critical; unencrypted PAN at rest is.
- When the change is compliant, say so affirmatively per control — "no findings" plus the checked-control list is a useful audit artifact.
- Never output real card numbers, even as examples; use the standard test PANs (e.g. 4111 1111 1111 1111) when illustrating.
- Read-only: this skill reviews and reports; it never modifies code, infrastructure, or configuration.
## Limitations
- Covers only the bundled PCI-DSS v4.0 and MAS TRM engineering summaries; other frameworks or local policy overlays need separate review.
- Provides engineering triage, not legal advice, QSA assessment, or formal compliance sign-off.
- Requires concrete evidence such as diffs, designs, IaC, logs, or control artifacts; incomplete evidence should be marked `Needs evidence`.
- The bundled references are concise control maps, not substitutes for reading the official standards.
## Credits
Adapted from [timwukp/agent-skills-best-practice](https://github.com/timwukp/agent-skills-best-practice) (MIT), where the skill ships with evals and a documented 4-layer test methodology (see the repo's TESTING.md).
@@ -0,0 +1,99 @@
# MAS Technology Risk Management (TRM) Guidelines — Engineering Control Reference
Engineering-relevant expectations from the Monetary Authority of Singapore's TRM Guidelines (January 2021), organized for change triage. Section numbers follow the official guidelines. The TRM Guidelines apply to all MAS-regulated financial institutions; they are principles-based guidelines (not prescriptive rules), so findings should be framed as "expectation gaps", and the institution's own TRM-aligned policies take precedence where stricter.
Related instruments to flag when relevant (not summarized here): MAS Notices on Cyber Hygiene (legally binding baseline), Outsourcing Guidelines, and the MAS AI model risk management information paper for AI/ML systems.
## Contents
1. [Software development & DevOps (§6)](#1-software-development--devops-6)
2. [IT resilience & availability (§8)](#2-it-resilience--availability-8)
3. [Access control (§9)](#3-access-control-9)
4. [Cryptography (§10)](#4-cryptography-10)
5. [Data & infrastructure security (§11)](#5-data--infrastructure-security-11)
6. [Cyber operations & monitoring (§12-13)](#6-cyber-operations--monitoring-12-13)
7. [Online financial services (§14)](#7-online-financial-services-14)
8. [Quick triage table](#8-quick-triage-table)
## 1. Software Development & DevOps (§6)
| Ref | Expectation (summary) | Engineering check |
|-----|----------------------|-------------------|
| 6.1 | Secure-by-design SDLC: security requirements defined at the start, not bolted on | Security stories/threat model exist for the feature |
| 6.2 | Secure coding standards; code review (peer or automated) before deployment | Review gates; standards documented and enforced |
| 6.3 | Source code security: access to repositories controlled; code integrity protected | Repo permissions, branch protection, signed commits where applicable |
| 6.4 | Security testing: vulnerability assessment before production launch and after major changes; penetration testing for internet-facing systems | SAST/DAST in pipeline; pen-test cadence for public systems |
| 6.5 | Separate environments for development, testing, production; production data not used in non-production without protection | Environment isolation; data masking for test data |
| 6.6 | Change management: assessed, tested, approved before production; emergency change procedures with retrospective approval | CI/CD approval gates, change records, rollback plans |
| 6.7 | End-of-life/unsupported software identified and risk-managed | Dependency and runtime version currency |
| — | DevOps note: §6 expectations apply to pipeline automation itself — the pipeline is a production system (access control, audit, segregation of duties in deployment approval) | Who can approve+deploy; pipeline credentials |
## 2. IT Resilience & Availability (§8)
| Ref | Expectation (summary) | Engineering check |
|-----|----------------------|-------------------|
| 8.2 | Availability targets defined; critical systems' RTO ≤ 4 hours and RPO defined per MAS Notice expectations | Architecture supports the institution's stated RTO/RPO |
| 8.3 | Single points of failure identified and addressed for critical systems | Redundancy in new components; multi-AZ/multi-site where critical |
| 8.4 | DR plans tested at least annually; recovery procedures current | New components included in DR runbooks |
| 8.5 | Capacity management: monitor and plan for demand | Load assumptions documented for new services |
## 3. Access Control (§9)
| Ref | Expectation (summary) | Engineering check |
|-----|----------------------|-------------------|
| 9.1 | Least privilege and need-to-have for all access; access reviewed periodically | New roles/permissions minimal; review process covers them |
| 9.2 | Strong authentication for privileged access; MFA expected for critical system administration | Admin paths MFA-protected |
| 9.3 | Privileged access managed: just-in-time where possible, activities logged and reviewed | Break-glass procedures, session recording/audit for admin ops |
| 9.4 | Segregation of duties: no single person develops, approves, and deploys to production unchecked | Pipeline approval separation |
| 9.5 | Remote access secured (MFA, encrypted channels, device posture) | VPN/zero-trust requirements for any new remote path |
## 4. Cryptography (§10)
| Ref | Expectation (summary) | Engineering check |
|-----|----------------------|-------------------|
| 10.1 | Strong, industry-accepted algorithms and key lengths; no deprecated crypto | No MD5/SHA-1 for security, no TLS <1.2, AES-128+ |
| 10.2 | Key lifecycle management: generation, distribution, storage, rotation, revocation, destruction | KMS/HSM usage; no keys in code, config files, or tickets |
| 10.3 | Cryptographic key compromise procedures | Key rotation runbook covers new keys |
## 5. Data & Infrastructure Security (§11)
| Ref | Expectation (summary) | Engineering check |
|-----|----------------------|-------------------|
| 11.1 | Data security throughout lifecycle: at rest, in transit, in use; data loss prevention strategy | Encryption defaults on new stores; egress paths controlled |
| 11.2 | Network security: segmentation, defense in depth; critical systems in secured zones | New services placed in correct zones; no flattening of segmentation |
| 11.3 | Endpoint and server hardening per standards | Base images hardened; IaC matches hardening baselines |
| 11.4 | Virtualization/container security: hypervisor and orchestration hardening | K8s RBAC, pod security, image provenance |
| 11.5 | Cloud: institution remains responsible; due diligence, data residency, exit strategy, and MAS Outsourcing Guidelines apply | New cloud services assessed; data residency for Singapore customer data confirmed |
## 6. Cyber Operations & Monitoring (§12-13)
| Ref | Expectation (summary) | Engineering check |
|-----|----------------------|-------------------|
| 12.1 | Security event logging across systems; logs protected and retained per policy | New components emit security events to central SIEM |
| 12.2 | Continuous monitoring and correlation; anomaly detection for critical systems | Alert rules accompany new security-relevant functionality |
| 13.1 | Cyber incident response plan; roles defined; MAS notification obligations for relevant incidents (as required by notices — commonly understood as within 1 hour for severe incidents) | New failure modes mapped to incident severity matrix |
| 13.2 | Post-incident review and remediation tracking | Incident learnings feed backlog |
## 7. Online Financial Services (§14)
| Ref | Expectation (summary) | Engineering check |
|-----|----------------------|-------------------|
| 14.1 | Strong customer authentication: MFA for login to online financial services and for high-risk transactions | Customer auth flows; step-up auth for transfers/payee changes |
| 14.2 | Transaction signing/confirmation for high-risk transactions; out-of-band notification to customers | Transaction flows notify customers of significant actions |
| 14.3 | Session management: timeout, re-authentication for sensitive actions, protection against hijacking | Session config on customer-facing changes |
| 14.4 | Fraud monitoring and customer education surfaces | New transaction types covered by fraud rules |
| — | Anti-scam expectations (post-2022 MAS/ABS measures): kill switch, cooling-off for new payees/devices, transaction limits | Payment feature changes checked against these measures |
## 8. Quick Triage Table
| Change type | Check first |
|-------------|-------------|
| New feature touching customer money | §14.1-14.2, §6.1, threat model |
| Auth/session change | §9.x, §14.1, §14.3 |
| New data store / data flow | §11.1, §11.5 (residency), §10.1 |
| New cloud service | §11.5 + Outsourcing Guidelines flag |
| CI/CD or repo change | §6.3, §6.6, §9.4 |
| Infra/network change | §11.2, §8.3 |
| New logging/monitoring | §12.1-12.2 |
| Incident-relevant failure mode | §13.1 severity mapping |
| AI/ML model in decisioning | Flag MAS AI information paper review |
@@ -0,0 +1,89 @@
# PCI-DSS v4.0 — Engineering Control Reference
Engineering-relevant controls from PCI-DSS v4.0, organized by what a code/architecture change typically touches. Control numbers follow the official standard (PCI Security Standards Council). This is a working summary for triage, not the standard itself — for formal scoping consult the full standard and a QSA.
**Key v4.0 dates:** v4.0 became mandatory March 2024; the ~50 future-dated requirements (marked FD below) became mandatory **31 March 2025** — they are now in force.
## Contents
1. [Cardholder data handling (Req 3, 4)](#1-cardholder-data-handling)
2. [Authentication & access (Req 7, 8)](#2-authentication--access)
3. [Secure development (Req 6)](#3-secure-development)
4. [Logging & monitoring (Req 10)](#4-logging--monitoring)
5. [Network & segmentation (Req 1)](#5-network--segmentation)
6. [Payment page / client-side (Req 6.4.3, 11.6.1)](#6-payment-page--client-side)
7. [Quick triage table](#7-quick-triage-table)
## 1. Cardholder Data Handling
| Control | Requirement (summary) | Engineering check |
|---------|----------------------|-------------------|
| 3.2.1 | Account data storage kept to minimum: retention/disposal policies covering all storage locations | New stores/caches must update the data-flow inventory; retention defined |
| 3.3.1 | Don't store sensitive authentication data (CVV/CVC, full track, PIN) after authorization — ever, even encrypted | grep for CVV/CVC fields in models, logs, caches, analytics events |
| 3.4.1 | Mask PAN when displayed (BIN + last 4 max visible) | UI components, receipts, admin screens, support tooling |
| 3.5.1 | Render PAN unreadable anywhere stored (strong crypto, truncation, tokens) | DB columns, backups, object storage, message queues, data lakes |
| 3.6 / 3.7 | Key management: documented procedures, key rotation, split knowledge for manual operations | KMS usage, key rotation schedules, no keys in code/config |
| 4.2.1 | Strong cryptography for PAN over open/public networks; no fallback to insecure versions | TLS 1.2+ enforced, cert validation not disabled, no PAN over email/chat |
## 2. Authentication & Access
| Control | Requirement (summary) | Engineering check |
|---------|----------------------|-------------------|
| 7.2.1 | Access by least privilege, need-to-know, defined roles | New endpoints/services declare required roles; no wildcard IAM |
| 8.3.6 (FD) | Passwords minimum 12 characters with complexity | Password validators, policy configs |
| 8.3.9 | Password change every 90 days OR dynamic risk analysis OR MFA-always | Session/auth design |
| 8.4.2 (FD) | MFA for ALL access into the CDE (not just admins) | Auth flows for any CDE-touching application access |
| 8.6.1-8.6.3 (FD) | Interactive use of system/service accounts restricted; their passwords managed and rotated | Service account credentials in pipelines, cron jobs |
| 8.2.2 | No shared/group accounts except documented exceptional circumstances | Service design, break-glass procedures |
## 3. Secure Development
| Control | Requirement (summary) | Engineering check |
|---------|----------------------|-------------------|
| 6.2.1 | Software developed per secure SDLC, security throughout | Threat modeling, security stories, review gates exist |
| 6.2.4 | Engineering techniques preventing common attack classes (injection, XSS, etc.) | Parameterized queries, output encoding, input validation at boundaries |
| 6.3.1 | Security vulnerabilities identified and ranked (CVSS or equivalent) | Scanner integration, triage workflow |
| 6.3.2 (FD) | Inventory of bespoke and custom software, and third-party components (SBOM-like) | Dependency manifests current; new deps recorded |
| 6.3.3 | Critical/high patches within one month | Dependency update cadence |
| 6.4.1/6.4.2 | Public-facing web apps protected (WAF in blocking mode per 6.4.2 FD) | New public endpoints behind WAF |
| 6.5.1-6.5.6 | Change management: documented, tested, approved; separation of dev/test from prod; no prod data in test; no test accounts/data left in prod before release | CI/CD gates, seed data hygiene, environment separation |
## 4. Logging & Monitoring
| Control | Requirement (summary) | Engineering check |
|---------|----------------------|-------------------|
| 10.2.1 | Audit logs capture: individual user access to cardholder data, admin actions, auth attempts (success/failure), log access, security event types | Audit events emitted for these actions with user identity |
| 10.2.1.2 | All actions by accounts with admin access logged | Admin tooling, support backdoors |
| 10.3.1-10.3.4 | Logs protected from modification, access limited, integrity monitored | Append-only/immutable log storage, restricted access |
| 10.4.1 (FD: automated) | Daily review of security events — automated mechanisms required in v4.0 | Alerting rules exist for new security-relevant events |
| — | **Never log:** full PAN, CVV, passwords, full track data | grep logging statements in payment/auth paths |
## 5. Network & Segmentation
| Control | Requirement (summary) | Engineering check |
|---------|----------------------|-------------------|
| 1.2.5 / 1.2.6 | All services/ports/protocols identified, approved, with security features defined | New listeners/ports documented and justified |
| 1.3.1 / 1.3.2 | Inbound and outbound CDE traffic restricted to necessary only | Security group / firewall changes reviewed against data flows |
| 1.4.4 | Stored cardholder data not directly accessible from untrusted networks | No DB with card data reachable from public subnets |
## 6. Payment Page / Client-Side
The two controls that catch most modern e-commerce teams (both FD, mandatory since 31 Mar 2025):
| Control | Requirement (summary) | Engineering check |
|---------|----------------------|-------------------|
| 6.4.3 | All payment-page scripts: inventoried, authorized, integrity-assured (e.g. SRI/CSP) | Script inventory for checkout pages; CSP headers; no unvetted tags |
| 11.6.1 | Change/tamper detection on payment pages, alerting on unauthorized modification | Monitoring on checkout page headers and script changes |
## 7. Quick Triage Table
| Change type | Check first |
|-------------|-------------|
| New logging | 3.3.1, never-log list (§4) |
| New data store/cache | 3.5.1, 3.2.1, 1.4.4 |
| Auth/session change | 8.3.x, 8.4.2, 10.2.1 |
| New dependency | 6.3.2, 6.3.3 |
| New public endpoint | 6.4.1/6.4.2, 1.2.x |
| Checkout/payment UI | 6.4.3, 11.6.1, 3.4.1 |
| CI/CD change | 6.5.1-6.5.6, 8.6.x |
| Infra/network change | 1.2.x, 1.3.x |
@@ -0,0 +1,41 @@
---
name: gdpr-data-handling
description: "Practical implementation guide for GDPR-compliant data processing, consent management, and privacy controls."
risk: safe
source: community
date_added: "2026-02-27"
---
# GDPR Data Handling
Practical implementation guide for GDPR-compliant data processing, consent management, and privacy controls.
## Use this skill when
- Building systems that process EU personal data
- Implementing consent management
- Handling data subject requests (DSRs)
- Conducting GDPR compliance reviews
- Designing privacy-first architectures
- Creating data processing agreements
## Do not use this skill when
- The task is unrelated to gdpr data handling
- You need a different domain or tool outside this scope
## Instructions
- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open `resources/implementation-playbook.md`.
## Resources
- `resources/implementation-playbook.md` for detailed patterns and examples.
## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.
@@ -0,0 +1,615 @@
# GDPR Data Handling Implementation Playbook
This file contains detailed patterns, checklists, and code samples referenced by the skill.
# GDPR Data Handling
Practical implementation guide for GDPR-compliant data processing, consent management, and privacy controls.
## When to Use This Skill
- Building systems that process EU personal data
- Implementing consent management
- Handling data subject requests (DSRs)
- Conducting GDPR compliance reviews
- Designing privacy-first architectures
- Creating data processing agreements
## Core Concepts
### 1. Personal Data Categories
| Category | Examples | Protection Level |
|----------|----------|------------------|
| **Basic** | Name, email, phone | Standard |
| **Sensitive (Art. 9)** | Health, religion, ethnicity | Explicit consent |
| **Criminal (Art. 10)** | Convictions, offenses | Official authority |
| **Children's** | Under 16 data | Parental consent |
### 2. Legal Bases for Processing
```
Article 6 - Lawful Bases:
├── Consent: Freely given, specific, informed
├── Contract: Necessary for contract performance
├── Legal Obligation: Required by law
├── Vital Interests: Protecting someone's life
├── Public Interest: Official functions
└── Legitimate Interest: Balanced against rights
```
### 3. Data Subject Rights
```
Right to Access (Art. 15) ─┐
Right to Rectification (Art. 16) │
Right to Erasure (Art. 17) │ Must respond
Right to Restrict (Art. 18) │ within 1 month
Right to Portability (Art. 20) │
Right to Object (Art. 21) ─┘
```
## Implementation Patterns
### Pattern 1: Consent Management
```javascript
// Consent data model
const consentSchema = {
userId: String,
consents: [{
purpose: String, // 'marketing', 'analytics', etc.
granted: Boolean,
timestamp: Date,
source: String, // 'web_form', 'api', etc.
version: String, // Privacy policy version
ipAddress: String, // For proof
userAgent: String // For proof
}],
auditLog: [{
action: String, // 'granted', 'withdrawn', 'updated'
purpose: String,
timestamp: Date,
source: String
}]
};
// Consent service
class ConsentManager {
async recordConsent(userId, purpose, granted, metadata) {
const consent = {
purpose,
granted,
timestamp: new Date(),
source: metadata.source,
version: await this.getCurrentPolicyVersion(),
ipAddress: metadata.ipAddress,
userAgent: metadata.userAgent
};
// Store consent
await this.db.consents.updateOne(
{ userId },
{
$push: {
consents: consent,
auditLog: {
action: granted ? 'granted' : 'withdrawn',
purpose,
timestamp: consent.timestamp,
source: metadata.source
}
}
},
{ upsert: true }
);
// Emit event for downstream systems
await this.eventBus.emit('consent.changed', {
userId,
purpose,
granted,
timestamp: consent.timestamp
});
}
async hasConsent(userId, purpose) {
const record = await this.db.consents.findOne({ userId });
if (!record) return false;
const latestConsent = record.consents
.filter(c => c.purpose === purpose)
.sort((a, b) => b.timestamp - a.timestamp)[0];
return latestConsent?.granted === true;
}
async getConsentHistory(userId) {
const record = await this.db.consents.findOne({ userId });
return record?.auditLog || [];
}
}
```
```html
<!-- GDPR-compliant consent UI -->
<div class="consent-banner" role="dialog" aria-labelledby="consent-title">
<h2 id="consent-title">Cookie Preferences</h2>
<p>We use cookies to improve your experience. Select your preferences below.</p>
<form id="consent-form">
<!-- Necessary - always on, no consent needed -->
<div class="consent-category">
<input type="checkbox" id="necessary" checked disabled>
<label for="necessary">
<strong>Necessary</strong>
<span>Required for the website to function. Cannot be disabled.</span>
</label>
</div>
<!-- Analytics - requires consent -->
<div class="consent-category">
<input type="checkbox" id="analytics" name="analytics">
<label for="analytics">
<strong>Analytics</strong>
<span>Help us understand how you use our site.</span>
</label>
</div>
<!-- Marketing - requires consent -->
<div class="consent-category">
<input type="checkbox" id="marketing" name="marketing">
<label for="marketing">
<strong>Marketing</strong>
<span>Personalized ads based on your interests.</span>
</label>
</div>
<div class="consent-actions">
<button type="button" id="accept-all">Accept All</button>
<button type="button" id="reject-all">Reject All</button>
<button type="submit">Save Preferences</button>
</div>
<p class="consent-links">
<a href="/privacy-policy">Privacy Policy</a> |
<a href="/cookie-policy">Cookie Policy</a>
</p>
</form>
</div>
```
### Pattern 2: Data Subject Access Request (DSAR)
```python
from datetime import datetime, timedelta
from typing import Dict, List, Optional
import json
class DSARHandler:
"""Handle Data Subject Access Requests."""
RESPONSE_DEADLINE_DAYS = 30
EXTENSION_ALLOWED_DAYS = 60 # For complex requests
def __init__(self, data_sources: List['DataSource']):
self.data_sources = data_sources
async def submit_request(
self,
request_type: str, # 'access', 'erasure', 'rectification', 'portability'
user_id: str,
verified: bool,
details: Optional[Dict] = None
) -> str:
"""Submit a new DSAR."""
request = {
'id': self.generate_request_id(),
'type': request_type,
'user_id': user_id,
'status': 'pending_verification' if not verified else 'processing',
'submitted_at': datetime.utcnow(),
'deadline': datetime.utcnow() + timedelta(days=self.RESPONSE_DEADLINE_DAYS),
'details': details or {},
'audit_log': [{
'action': 'submitted',
'timestamp': datetime.utcnow(),
'details': 'Request received'
}]
}
await self.db.dsar_requests.insert_one(request)
await self.notify_dpo(request)
return request['id']
async def process_access_request(self, request_id: str) -> Dict:
"""Process a data access request."""
request = await self.get_request(request_id)
if request['type'] != 'access':
raise ValueError("Not an access request")
# Collect data from all sources
user_data = {}
for source in self.data_sources:
try:
data = await source.get_user_data(request['user_id'])
user_data[source.name] = data
except Exception as e:
user_data[source.name] = {'error': str(e)}
# Format response
response = {
'request_id': request_id,
'generated_at': datetime.utcnow().isoformat(),
'data_categories': list(user_data.keys()),
'data': user_data,
'retention_info': await self.get_retention_info(),
'processing_purposes': await self.get_processing_purposes(),
'third_party_recipients': await self.get_recipients()
}
# Update request status
await self.update_request(request_id, 'completed', response)
return response
async def process_erasure_request(self, request_id: str) -> Dict:
"""Process a right to erasure request."""
request = await self.get_request(request_id)
if request['type'] != 'erasure':
raise ValueError("Not an erasure request")
results = {}
exceptions = []
for source in self.data_sources:
try:
# Check for legal exceptions
can_delete, reason = await source.can_delete(request['user_id'])
if can_delete:
await source.delete_user_data(request['user_id'])
results[source.name] = 'deleted'
else:
exceptions.append({
'source': source.name,
'reason': reason # e.g., 'legal retention requirement'
})
results[source.name] = f'retained: {reason}'
except Exception as e:
results[source.name] = f'error: {str(e)}'
response = {
'request_id': request_id,
'completed_at': datetime.utcnow().isoformat(),
'results': results,
'exceptions': exceptions
}
await self.update_request(request_id, 'completed', response)
return response
async def process_portability_request(self, request_id: str) -> bytes:
"""Generate portable data export."""
request = await self.get_request(request_id)
user_data = await self.process_access_request(request_id)
# Convert to machine-readable format (JSON)
portable_data = {
'export_date': datetime.utcnow().isoformat(),
'format_version': '1.0',
'data': user_data['data']
}
return json.dumps(portable_data, indent=2, default=str).encode()
```
### Pattern 3: Data Retention
```python
from datetime import datetime, timedelta
from enum import Enum
class RetentionBasis(Enum):
CONSENT = "consent"
CONTRACT = "contract"
LEGAL_OBLIGATION = "legal_obligation"
LEGITIMATE_INTEREST = "legitimate_interest"
class DataRetentionPolicy:
"""Define and enforce data retention policies."""
POLICIES = {
'user_account': {
'retention_period_days': 365 * 3, # 3 years after last activity
'basis': RetentionBasis.CONTRACT,
'trigger': 'last_activity_date',
'archive_before_delete': True
},
'transaction_records': {
'retention_period_days': 365 * 7, # 7 years for tax
'basis': RetentionBasis.LEGAL_OBLIGATION,
'trigger': 'transaction_date',
'archive_before_delete': True,
'legal_reference': 'Tax regulations require 7 year retention'
},
'marketing_consent': {
'retention_period_days': 365 * 2, # 2 years
'basis': RetentionBasis.CONSENT,
'trigger': 'consent_date',
'archive_before_delete': False
},
'support_tickets': {
'retention_period_days': 365 * 2,
'basis': RetentionBasis.LEGITIMATE_INTEREST,
'trigger': 'ticket_closed_date',
'archive_before_delete': True
},
'analytics_data': {
'retention_period_days': 365, # 1 year
'basis': RetentionBasis.CONSENT,
'trigger': 'collection_date',
'archive_before_delete': False,
'anonymize_instead': True
}
}
async def apply_retention_policies(self):
"""Run retention policy enforcement."""
for data_type, policy in self.POLICIES.items():
cutoff_date = datetime.utcnow() - timedelta(
days=policy['retention_period_days']
)
if policy.get('anonymize_instead'):
await self.anonymize_old_data(data_type, cutoff_date)
else:
if policy.get('archive_before_delete'):
await self.archive_data(data_type, cutoff_date)
await self.delete_old_data(data_type, cutoff_date)
await self.log_retention_action(data_type, cutoff_date)
async def anonymize_old_data(self, data_type: str, before_date: datetime):
"""Anonymize data instead of deleting."""
# Example: Replace identifying fields with hashes
if data_type == 'analytics_data':
await self.db.analytics.update_many(
{'collection_date': {'$lt': before_date}},
{'$set': {
'user_id': None,
'ip_address': None,
'device_id': None,
'anonymized': True,
'anonymized_date': datetime.utcnow()
}}
)
```
### Pattern 4: Privacy by Design
```python
class PrivacyFirstDataModel:
"""Example of privacy-by-design data model."""
# Separate PII from behavioral data
user_profile_schema = {
'user_id': str, # UUID, not sequential
'email_hash': str, # Hashed for lookups
'created_at': datetime,
# Minimal data collection
'preferences': {
'language': str,
'timezone': str
}
}
# Encrypted at rest
user_pii_schema = {
'user_id': str,
'email': str, # Encrypted
'name': str, # Encrypted
'phone': str, # Encrypted (optional)
'address': dict, # Encrypted (optional)
'encryption_key_id': str
}
# Pseudonymized behavioral data
analytics_schema = {
'session_id': str, # Not linked to user_id
'pseudonym_id': str, # Rotating pseudonym
'events': list,
'device_category': str, # Generalized, not specific
'country': str, # Not city-level
}
class DataMinimization:
"""Implement data minimization principles."""
@staticmethod
def collect_only_needed(form_data: dict, purpose: str) -> dict:
"""Filter form data to only fields needed for purpose."""
REQUIRED_FIELDS = {
'account_creation': ['email', 'password'],
'newsletter': ['email'],
'purchase': ['email', 'name', 'address', 'payment'],
'support': ['email', 'message']
}
allowed = REQUIRED_FIELDS.get(purpose, [])
return {k: v for k, v in form_data.items() if k in allowed}
@staticmethod
def generalize_location(ip_address: str) -> str:
"""Generalize IP to country level only."""
import geoip2.database
reader = geoip2.database.Reader('GeoLite2-Country.mmdb')
try:
response = reader.country(ip_address)
return response.country.iso_code
except:
return 'UNKNOWN'
```
### Pattern 5: Breach Notification
```python
from datetime import datetime
from enum import Enum
class BreachSeverity(Enum):
LOW = "low"
MEDIUM = "medium"
HIGH = "high"
CRITICAL = "critical"
class BreachNotificationHandler:
"""Handle GDPR breach notification requirements."""
AUTHORITY_NOTIFICATION_HOURS = 72
AFFECTED_NOTIFICATION_REQUIRED_SEVERITY = BreachSeverity.HIGH
async def report_breach(
self,
description: str,
data_types: List[str],
affected_count: int,
severity: BreachSeverity
) -> dict:
"""Report and handle a data breach."""
breach = {
'id': self.generate_breach_id(),
'reported_at': datetime.utcnow(),
'description': description,
'data_types_affected': data_types,
'affected_individuals_count': affected_count,
'severity': severity.value,
'status': 'investigating',
'timeline': [{
'event': 'breach_reported',
'timestamp': datetime.utcnow(),
'details': description
}]
}
await self.db.breaches.insert_one(breach)
# Immediate notifications
await self.notify_dpo(breach)
await self.notify_security_team(breach)
# Authority notification required within 72 hours
if self.requires_authority_notification(severity, data_types):
breach['authority_notification_deadline'] = (
datetime.utcnow() + timedelta(hours=self.AUTHORITY_NOTIFICATION_HOURS)
)
await self.schedule_authority_notification(breach)
# Affected individuals notification
if severity.value in [BreachSeverity.HIGH.value, BreachSeverity.CRITICAL.value]:
await self.schedule_individual_notifications(breach)
return breach
def requires_authority_notification(
self,
severity: BreachSeverity,
data_types: List[str]
) -> bool:
"""Determine if supervisory authority must be notified."""
# Always notify for sensitive data
sensitive_types = ['health', 'financial', 'credentials', 'biometric']
if any(t in sensitive_types for t in data_types):
return True
# Notify for medium+ severity
return severity in [BreachSeverity.MEDIUM, BreachSeverity.HIGH, BreachSeverity.CRITICAL]
async def generate_authority_report(self, breach_id: str) -> dict:
"""Generate report for supervisory authority."""
breach = await self.get_breach(breach_id)
return {
'organization': {
'name': self.config.org_name,
'contact': self.config.dpo_contact,
'registration': self.config.registration_number
},
'breach': {
'nature': breach['description'],
'categories_affected': breach['data_types_affected'],
'approximate_number_affected': breach['affected_individuals_count'],
'likely_consequences': self.assess_consequences(breach),
'measures_taken': await self.get_remediation_measures(breach_id),
'measures_proposed': await self.get_proposed_measures(breach_id)
},
'timeline': breach['timeline'],
'submitted_at': datetime.utcnow().isoformat()
}
```
## Compliance Checklist
```markdown
## GDPR Implementation Checklist
### Legal Basis
- [ ] Documented legal basis for each processing activity
- [ ] Consent mechanisms meet GDPR requirements
- [ ] Legitimate interest assessments completed
### Transparency
- [ ] Privacy policy is clear and accessible
- [ ] Processing purposes clearly stated
- [ ] Data retention periods documented
### Data Subject Rights
- [ ] Access request process implemented
- [ ] Erasure request process implemented
- [ ] Portability export available
- [ ] Rectification process available
- [ ] Response within 30-day deadline
### Security
- [ ] Encryption at rest implemented
- [ ] Encryption in transit (TLS)
- [ ] Access controls in place
- [ ] Audit logging enabled
### Breach Response
- [ ] Breach detection mechanisms
- [ ] 72-hour notification process
- [ ] Breach documentation system
### Documentation
- [ ] Records of processing activities (Art. 30)
- [ ] Data protection impact assessments
- [ ] Data processing agreements with vendors
```
## Best Practices
### Do's
- **Minimize data collection** - Only collect what's needed
- **Document everything** - Processing activities, legal bases
- **Encrypt PII** - At rest and in transit
- **Implement access controls** - Need-to-know basis
- **Regular audits** - Verify compliance continuously
### Don'ts
- **Don't pre-check consent boxes** - Must be opt-in
- **Don't bundle consent** - Separate purposes separately
- **Don't retain indefinitely** - Define and enforce retention
- **Don't ignore DSARs** - 30-day response required
- **Don't transfer without safeguards** - SCCs or adequacy decisions
## Resources
- [GDPR Full Text](https://gdpr-info.eu/)
- [ICO Guidance](https://ico.org.uk/for-organisations/guide-to-data-protection/guide-to-the-general-data-protection-regulation-gdpr/)
- [EDPB Guidelines](https://edpb.europa.eu/our-work-tools/general-guidance/gdpr-guidelines-recommendations-best-practices_en)
@@ -0,0 +1,486 @@
---
name: pci-compliance
description: "Master PCI DSS (Payment Card Industry Data Security Standard) compliance for secure payment processing and handling of cardholder data."
risk: unknown
source: community
date_added: "2026-02-27"
---
# PCI Compliance
Master PCI DSS (Payment Card Industry Data Security Standard) compliance for secure payment processing and handling of cardholder data.
## Do not use this skill when
- The task is unrelated to pci compliance
- You need a different domain or tool outside this scope
## Instructions
- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open `resources/implementation-playbook.md`.
## Use this skill when
- Building payment processing systems
- Handling credit card information
- Implementing secure payment flows
- Conducting PCI compliance audits
- Reducing PCI compliance scope
- Implementing tokenization and encryption
- Preparing for PCI DSS assessments
## PCI DSS Requirements (12 Core Requirements)
### Build and Maintain Secure Network
1. Install and maintain firewall configuration
2. Don't use vendor-supplied defaults for passwords
### Protect Cardholder Data
3. Protect stored cardholder data
4. Encrypt transmission of cardholder data across public networks
### Maintain Vulnerability Management
5. Protect systems against malware
6. Develop and maintain secure systems and applications
### Implement Strong Access Control
7. Restrict access to cardholder data by business need-to-know
8. Identify and authenticate access to system components
9. Restrict physical access to cardholder data
### Monitor and Test Networks
10. Track and monitor all access to network resources and cardholder data
11. Regularly test security systems and processes
### Maintain Information Security Policy
12. Maintain a policy that addresses information security
## Compliance Levels
**Level 1**: > 6 million transactions/year (annual ROC required)
**Level 2**: 1-6 million transactions/year (annual SAQ)
**Level 3**: 20,000-1 million e-commerce transactions/year
**Level 4**: < 20,000 e-commerce or < 1 million total transactions
## Data Minimization (Never Store)
```python
# NEVER STORE THESE
PROHIBITED_DATA = {
'full_track_data': 'Magnetic stripe data',
'cvv': 'Card verification code/value',
'pin': 'PIN or PIN block'
}
# CAN STORE (if encrypted)
ALLOWED_DATA = {
'pan': 'Primary Account Number (card number)',
'cardholder_name': 'Name on card',
'expiration_date': 'Card expiration',
'service_code': 'Service code'
}
class PaymentData:
"""Safe payment data handling."""
def __init__(self):
self.prohibited_fields = ['cvv', 'cvv2', 'cvc', 'pin']
def sanitize_log(self, data):
"""Remove sensitive data from logs."""
sanitized = data.copy()
# Mask PAN
if 'card_number' in sanitized:
card = sanitized['card_number']
sanitized['card_number'] = f"{card[:6]}{'*' * (len(card) - 10)}{card[-4:]}"
# Remove prohibited data
for field in self.prohibited_fields:
sanitized.pop(field, None)
return sanitized
def validate_no_prohibited_storage(self, data):
"""Ensure no prohibited data is being stored."""
for field in self.prohibited_fields:
if field in data:
raise SecurityError(f"Attempting to store prohibited field: {field}")
```
## Tokenization
### Using Payment Processor Tokens
```python
import stripe
class TokenizedPayment:
"""Handle payments using tokens (no card data on server)."""
@staticmethod
def create_payment_method_token(card_details):
"""Create token from card details (client-side only)."""
# THIS SHOULD ONLY BE DONE CLIENT-SIDE WITH STRIPE.JS
# NEVER send card details to your server
"""
// Frontend JavaScript
const stripe = Stripe('pk_...');
const {token, error} = await stripe.createToken({
card: {
number: '4242424242424242',
exp_month: 12,
exp_year: 2024,
cvc: '123'
}
});
// Send token.id to server (NOT card details)
"""
pass
@staticmethod
def charge_with_token(token_id, amount):
"""Charge using token (server-side)."""
# Your server only sees the token, never the card number
stripe.api_key = "sk_..."
charge = stripe.Charge.create(
amount=amount,
currency="usd",
source=token_id, # Token instead of card details
description="Payment"
)
return charge
@staticmethod
def store_payment_method(customer_id, payment_method_token):
"""Store payment method as token for future use."""
stripe.Customer.modify(
customer_id,
source=payment_method_token
)
# Store only customer_id and payment_method_id in your database
# NEVER store actual card details
return {
'customer_id': customer_id,
'has_payment_method': True
# DO NOT store: card number, CVV, etc.
}
```
### Custom Tokenization (Advanced)
```python
import secrets
from cryptography.fernet import Fernet
class TokenVault:
"""Secure token vault for card data (if you must store it)."""
def __init__(self, encryption_key):
self.cipher = Fernet(encryption_key)
self.vault = {} # In production: use encrypted database
def tokenize(self, card_data):
"""Convert card data to token."""
# Generate secure random token
token = secrets.token_urlsafe(32)
# Encrypt card data
encrypted = self.cipher.encrypt(json.dumps(card_data).encode())
# Store token -> encrypted data mapping
self.vault[token] = encrypted
return token
def detokenize(self, token):
"""Retrieve card data from token."""
encrypted = self.vault.get(token)
if not encrypted:
raise ValueError("Token not found")
# Decrypt
decrypted = self.cipher.decrypt(encrypted)
return json.loads(decrypted.decode())
def delete_token(self, token):
"""Remove token from vault."""
self.vault.pop(token, None)
```
## Encryption
### Data at Rest
```python
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
import os
class EncryptedStorage:
"""Encrypt data at rest using AES-256-GCM."""
def __init__(self, encryption_key):
"""Initialize with 256-bit key."""
self.key = encryption_key # Must be 32 bytes
def encrypt(self, plaintext):
"""Encrypt data."""
# Generate random nonce
nonce = os.urandom(12)
# Encrypt
aesgcm = AESGCM(self.key)
ciphertext = aesgcm.encrypt(nonce, plaintext.encode(), None)
# Return nonce + ciphertext
return nonce + ciphertext
def decrypt(self, encrypted_data):
"""Decrypt data."""
# Extract nonce and ciphertext
nonce = encrypted_data[:12]
ciphertext = encrypted_data[12:]
# Decrypt
aesgcm = AESGCM(self.key)
plaintext = aesgcm.decrypt(nonce, ciphertext, None)
return plaintext.decode()
# Usage
storage = EncryptedStorage(os.urandom(32))
encrypted_pan = storage.encrypt("4242424242424242")
# Store encrypted_pan in database
```
### Data in Transit
```python
# Always use TLS 1.2 or higher
# Flask/Django example
app.config['SESSION_COOKIE_SECURE'] = True # HTTPS only
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_COOKIE_SAMESITE'] = 'Strict'
# Enforce HTTPS
from flask_talisman import Talisman
Talisman(app, force_https=True)
```
## Access Control
```python
from functools import wraps
from flask import session
def require_pci_access(f):
"""Decorator to restrict access to cardholder data."""
@wraps(f)
def decorated_function(*args, **kwargs):
user = session.get('user')
# Check if user has PCI access role
if not user or 'pci_access' not in user.get('roles', []):
return {'error': 'Unauthorized access to cardholder data'}, 403
# Log access attempt
audit_log(
user=user['id'],
action='access_cardholder_data',
resource=f.__name__
)
return f(*args, **kwargs)
return decorated_function
@app.route('/api/payment-methods')
@require_pci_access
def get_payment_methods():
"""Retrieve payment methods (restricted access)."""
# Only accessible to users with pci_access role
pass
```
## Audit Logging
```python
import logging
from datetime import datetime
class PCIAuditLogger:
"""PCI-compliant audit logging."""
def __init__(self):
self.logger = logging.getLogger('pci_audit')
# Configure to write to secure, append-only log
def log_access(self, user_id, resource, action, result):
"""Log access to cardholder data."""
entry = {
'timestamp': datetime.utcnow().isoformat(),
'user_id': user_id,
'resource': resource,
'action': action,
'result': result,
'ip_address': request.remote_addr
}
self.logger.info(json.dumps(entry))
def log_authentication(self, user_id, success, method):
"""Log authentication attempt."""
entry = {
'timestamp': datetime.utcnow().isoformat(),
'user_id': user_id,
'event': 'authentication',
'success': success,
'method': method,
'ip_address': request.remote_addr
}
self.logger.info(json.dumps(entry))
# Usage
audit = PCIAuditLogger()
audit.log_access(user_id=123, resource='payment_methods', action='read', result='success')
```
## Security Best Practices
### Input Validation
```python
import re
def validate_card_number(card_number):
"""Validate card number format (Luhn algorithm)."""
# Remove spaces and dashes
card_number = re.sub(r'[\s-]', '', card_number)
# Check if all digits
if not card_number.isdigit():
return False
# Luhn algorithm
def luhn_checksum(card_num):
def digits_of(n):
return [int(d) for d in str(n)]
digits = digits_of(card_num)
odd_digits = digits[-1::-2]
even_digits = digits[-2::-2]
checksum = sum(odd_digits)
for d in even_digits:
checksum += sum(digits_of(d * 2))
return checksum % 10
return luhn_checksum(card_number) == 0
def sanitize_input(user_input):
"""Sanitize user input to prevent injection."""
# Remove special characters
# Validate against expected format
# Escape for database queries
pass
```
## PCI DSS SAQ (Self-Assessment Questionnaire)
### SAQ A (Least Requirements)
- E-commerce using hosted payment page
- No card data on your systems
- ~20 questions
### SAQ A-EP
- E-commerce with embedded payment form
- Uses JavaScript to handle card data
- ~180 questions
### SAQ D (Most Requirements)
- Store, process, or transmit card data
- Full PCI DSS requirements
- ~300 questions
## Compliance Checklist
```python
PCI_COMPLIANCE_CHECKLIST = {
'network_security': [
'Firewall configured and maintained',
'No vendor default passwords',
'Network segmentation implemented'
],
'data_protection': [
'No storage of CVV, track data, or PIN',
'PAN encrypted when stored',
'PAN masked when displayed',
'Encryption keys properly managed'
],
'vulnerability_management': [
'Anti-virus installed and updated',
'Secure development practices',
'Regular security patches',
'Vulnerability scanning performed'
],
'access_control': [
'Access restricted by role',
'Unique IDs for all users',
'Multi-factor authentication',
'Physical security measures'
],
'monitoring': [
'Audit logs enabled',
'Log review process',
'File integrity monitoring',
'Regular security testing'
],
'policy': [
'Security policy documented',
'Risk assessment performed',
'Security awareness training',
'Incident response plan'
]
}
```
## Resources
- **references/data-minimization.md**: Never store prohibited data
- **references/tokenization.md**: Tokenization strategies
- **references/encryption.md**: Encryption requirements
- **references/access-control.md**: Role-based access
- **references/audit-logging.md**: Comprehensive logging
- **assets/pci-compliance-checklist.md**: Complete checklist
- **assets/encrypted-storage.py**: Encryption utilities
- **scripts/audit-payment-system.sh**: Compliance audit script
## Common Violations
1. **Storing CVV**: Never store card verification codes
2. **Unencrypted PAN**: Card numbers must be encrypted at rest
3. **Weak Encryption**: Use AES-256 or equivalent
4. **No Access Controls**: Restrict who can access cardholder data
5. **Missing Audit Logs**: Must log all access to payment data
6. **Insecure Transmission**: Always use TLS 1.2+
7. **Default Passwords**: Change all default credentials
8. **No Security Testing**: Regular penetration testing required
## Reducing PCI Scope
1. **Use Hosted Payments**: Stripe Checkout, PayPal, etc.
2. **Tokenization**: Replace card data with tokens
3. **Network Segmentation**: Isolate cardholder data environment
4. **Outsource**: Use PCI-compliant payment processors
5. **No Storage**: Never store full card details
By minimizing systems that touch card data, you reduce compliance burden significantly.
## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.
@@ -0,0 +1,25 @@
# 🔒 Privacy by Design
Guides AI agents to integrate privacy protections into software from the start—data minimization, consent, encryption, retention. Applies GDPR Article 25, CCPA, and LGPD principles during design and implementation.
## ✨ What It Does
- 🛡️ Enforces data minimization and purpose limitation
- ✅ Ensures consent before collection and third-party sharing
- 🔐 Covers encryption, retention policies, and user rights (access, erasure, portability)
- 💻 Provides code patterns in JavaScript, Python, and SQL
- 📋 Includes logging safety, third-party audit, and common pitfalls
## 🚀 Usage
```
Use @privacy-by-design when designing the user registration flow
```
```
Use @privacy-by-design to review our database schema for PII
```
---
**Contributor:** [@Abdeltoto](https://github.com/Abdeltoto)
@@ -0,0 +1,213 @@
---
name: privacy-by-design
description: "Use when building apps that collect user data. Ensures privacy protections are built in from the start—data minimization, consent, encryption."
risk: safe
source: community
date_added: "2026-02-23"
---
# Privacy by Design
## Overview
Integrate privacy protections into software architecture from the beginning, not as an afterthought. This skill applies Privacy by Design principles (GDPR Article 25, Cavoukian's framework) when designing databases, APIs, and user flows. Protects real users' data and builds trust.
## When to Use This Skill
- Use when building apps that collect personal data (names, emails, locations, preferences)
- Use when designing database schemas, APIs, or authentication flows
- Use when the user mentions forms, user accounts, analytics, or third-party integrations
- Use when deploying to production—verify privacy controls before launch
## Legal Frameworks
**GDPR (EU)** — Primary reference. Article 25 mandates "data protection by design and by default." Applies to EU users and often adopted globally.
**CCPA (California)** — Right to know, delete, opt-out of sale. Similar principles: minimize, disclose, allow control.
**LGPD (Brazil)** — Aligned with GDPR. Purpose limitation, necessity, transparency. Applies to Brazil users.
Design for the strictest framework you target; it often satisfies others.
---
## Core Principles
### 1. Data Minimization
Collect only what is strictly necessary. Every field needs a documented justification. Avoid "we might need it later."
### 2. Purpose Limitation
Store the purpose of each data point. Do not reuse data for purposes the user did not consent to.
### 3. Storage Limitation
Define retention periods. Implement automated deletion or anonymization when retention expires. Never keep data "forever" by default.
### 4. Privacy as Default
Opt-in for optional collection, not opt-out. Sensitive settings (analytics, marketing) off by default. No pre-checked consent boxes.
### 5. End-to-End Security
Encrypt at rest and in transit. Use RBAC. Log access to sensitive data for audit.
### 6. Transparency
Document what is collected and why. Clear privacy policies. Easy access and deletion for users.
---
## User Rights (GDPR)
Ensure these are implementable from day one:
| Right | What to build |
|-------|---------------|
| **Access** | Endpoint or flow to return all user data |
| **Rectification** | Ability to update/correct data |
| **Erasure** | Account deletion + data purge (including backups) |
| **Portability** | Export data in machine-readable format (JSON, CSV) |
---
## Deep Dive: Why It Matters
**Data minimization** — Less data = less breach impact, lower storage cost, simpler compliance. Each field is a liability.
**Purpose limitation** — Reusing data without consent is illegal under GDPR. Document purpose in schema or metadata.
**Retention** — Indefinite storage increases risk and violates GDPR. Define `retention_days` per data type; automate cleanup.
**Logging** — Logs often leak PII. Redact emails, IDs, tokens. Use structured logging with allowlists.
**Third parties** — Every SDK (analytics, crash reporting, ads) may send data elsewhere. Audit dependencies; require consent before loading.
---
## Code Examples
### JavaScript/Node — Minimal User Model
```javascript
// BAD: Collecting everything "just in case"
const user = { email, name, phone, address, birthdate, ipAddress, userAgent, ... };
// GOOD: Minimal, documented purpose
const user = {
email, // purpose: authentication
displayName, // purpose: UI display
createdAt, // purpose: account age
};
```
### JavaScript — Consent Before Tracking
```javascript
// BAD: Track first, ask later
analytics.track(userId, event);
// GOOD: Check consent first
if (userConsent.analytics) {
analytics.track(userId, event);
}
```
### Python — Safe Logging
```python
# BAD: Logging PII in plain text
logger.info(f"User {user.email} logged in from {request.remote_addr}")
# GOOD: Redact or hash identifiers
logger.info(f"User {hash_user_id(user.id)} logged in")
# Or: logger.info("User login", extra={"user_id_hash": hash_id(user.id)})
```
### SQL — Schema with Purpose and Retention
```sql
-- GOOD: Document purpose and retention in schema
CREATE TABLE users (
id UUID PRIMARY KEY,
email VARCHAR(255) NOT NULL, -- purpose: auth, retention: account lifetime
display_name VARCHAR(100), -- purpose: UI, retention: account lifetime
created_at TIMESTAMPTZ, -- purpose: audit, retention: 7 years
last_login_at TIMESTAMPTZ -- purpose: security, retention: 90 days
);
-- Add retention policy (PostgreSQL example)
-- Schedule job to anonymize/delete last_login_at after 90 days
```
### API — Return Only Needed Fields
```python
# BAD: Returning full user object
return jsonify(user) # May include internal fields, hashed passwords
# GOOD: Explicit allowlist
return jsonify({
"id": user.id,
"email": user.email,
"displayName": user.display_name,
})
```
---
## Common Pitfalls
| Pitfall | Solution |
|---------|----------|
| Logs contain emails, IPs, tokens | Redact PII; use hashed IDs or structured logs |
| Error messages expose data | Return generic errors to client; log details server-side |
| Third-party SDKs load before consent | Load analytics/ads only after consent; use consent management |
| No deletion flow | Design account deletion + data purge from day one |
| Backups keep data forever | Include backups in retention; encrypt backups |
| Cookies without consent | Use consent banner; respect Do Not Track where applicable |
---
## Third-Party Audit
Before adding a dependency that touches user data:
- [ ] What data does it collect or receive?
- [ ] Where does it send data (servers, countries)?
- [ ] Is it loaded before or after user consent?
- [ ] Can we disable it if user opts out?
- [ ] Does their privacy policy align with ours?
---
## Implementation Checklist
When building a feature that touches user data:
- [ ] Is this data necessary? Can we achieve the goal with less?
- [ ] Do we have explicit consent for this use?
- [ ] Is it encrypted (at rest and in transit)?
- [ ] Do we have a retention/deletion policy?
- [ ] Can the user export or delete their data?
- [ ] Are third-party services disclosed and consented?
- [ ] Are logs free of PII?
- [ ] Are backups included in retention policy?
---
## Best Practices
- ✅ Ask "do we need this?" for every new data field
- ✅ Design deletion and export flows from day one
- ✅ Use hashing or tokenization for sensitive identifiers when possible
- ✅ Document purpose and retention in schema or metadata
- ❌ Don't log passwords, tokens, or PII in plain text
- ❌ Don't share data with third parties without explicit consent
- ❌ Don't assume "we'll add privacy later"—it rarely happens
- ❌ Don't expose stack traces or internal errors to clients
---
## When to Use
This skill is applicable when building software that collects, stores, or processes personal data. Apply it proactively during design and implementation.
## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.
@@ -0,0 +1,222 @@
---
name: security-audit
description: "Comprehensive security auditing workflow covering web application testing, API security, penetration testing, vulnerability scanning, and security hardening."
category: workflow-bundle
risk: safe
source: personal
date_added: "2026-02-27"
---
# Security Auditing Workflow Bundle
## Overview
Comprehensive security auditing workflow for web applications, APIs, and infrastructure. This bundle orchestrates skills for penetration testing, vulnerability assessment, security scanning, and remediation.
## When to Use This Workflow
Use this workflow when:
- Performing security audits on web applications
- Testing API security
- Conducting penetration tests
- Scanning for vulnerabilities
- Hardening application security
- Compliance security assessments
## Workflow Phases
### Phase 1: Reconnaissance
#### Skills to Invoke
- `scanning-tools` - Security scanning
- `shodan-reconnaissance` - Shodan searches
- `top-web-vulnerabilities` - OWASP Top 10
#### Actions
1. Identify target scope
2. Gather intelligence
3. Map attack surface
4. Identify technologies
5. Document findings
#### Copy-Paste Prompts
```
Use @scanning-tools to perform initial reconnaissance
```
```
Use @shodan-reconnaissance to find exposed services
```
### Phase 2: Vulnerability Scanning
#### Skills to Invoke
- `vulnerability-scanner` - Vulnerability analysis
- `security-scanning-security-sast` - Static analysis
- `security-scanning-security-dependencies` - Dependency scanning
#### Actions
1. Run automated scanners
2. Perform static analysis
3. Scan dependencies
4. Identify misconfigurations
5. Document vulnerabilities
#### Copy-Paste Prompts
```
Use @vulnerability-scanner to scan for OWASP Top 10 vulnerabilities
```
```
Use @security-scanning-security-dependencies to audit dependencies
```
### Phase 3: Web Application Testing
#### Skills to Invoke
- `top-web-vulnerabilities` - OWASP vulnerabilities
- `sql-injection-testing` - SQL injection
- `xss-html-injection` - XSS testing
- `broken-authentication` - Authentication testing
- `idor-testing` - IDOR testing
- `file-path-traversal` - Path traversal
- `burp-suite-testing` - Burp Suite testing
#### Actions
1. Test for injection flaws
2. Test authentication mechanisms
3. Test session management
4. Test access controls
5. Test input validation
6. Test security headers
#### Copy-Paste Prompts
```
Use @sql-injection-testing to test for SQL injection vulnerabilities
```
```
Use @xss-html-injection to test for cross-site scripting
```
```
Use @broken-authentication to test authentication security
```
### Phase 4: API Security Testing
#### Skills to Invoke
- `api-fuzzing-bug-bounty` - API fuzzing
- `api-security-best-practices` - API security
#### Actions
1. Enumerate API endpoints
2. Test authentication/authorization
3. Test rate limiting
4. Test input validation
5. Test error handling
6. Document API vulnerabilities
#### Copy-Paste Prompts
```
Use @api-fuzzing-bug-bounty to fuzz API endpoints
```
### Phase 5: Penetration Testing
#### Skills to Invoke
- `pentest-commands` - Penetration testing commands
- `pentest-checklist` - Pentest planning
- `ethical-hacking-methodology` - Ethical hacking
- `metasploit-framework` - Metasploit
#### Actions
1. Plan penetration test
2. Execute attack scenarios
3. Exploit vulnerabilities
4. Document proof of concept
5. Assess impact
#### Copy-Paste Prompts
```
Use @pentest-checklist to plan penetration test
```
```
Use @pentest-commands to execute penetration testing
```
### Phase 6: Security Hardening
#### Skills to Invoke
- `security-scanning-security-hardening` - Security hardening
- `auth-implementation-patterns` - Authentication
- `api-security-best-practices` - API security
#### Actions
1. Implement security controls
2. Configure security headers
3. Set up authentication
4. Implement authorization
5. Configure logging
6. Apply patches
#### Copy-Paste Prompts
```
Use @security-scanning-security-hardening to harden application security
```
### Phase 7: Reporting
#### Skills to Invoke
- `reporting-standards` - Security reporting
#### Actions
1. Document findings
2. Assess risk levels
3. Provide remediation steps
4. Create executive summary
5. Generate technical report
## Security Testing Checklist
### OWASP Top 10
- [ ] Injection (SQL, NoSQL, OS, LDAP)
- [ ] Broken Authentication
- [ ] Sensitive Data Exposure
- [ ] XML External Entities (XXE)
- [ ] Broken Access Control
- [ ] Security Misconfiguration
- [ ] Cross-Site Scripting (XSS)
- [ ] Insecure Deserialization
- [ ] Using Components with Known Vulnerabilities
- [ ] Insufficient Logging & Monitoring
### API Security
- [ ] Authentication mechanisms
- [ ] Authorization checks
- [ ] Rate limiting
- [ ] Input validation
- [ ] Error handling
- [ ] Security headers
## Quality Gates
- [ ] All planned tests executed
- [ ] Vulnerabilities documented
- [ ] Proof of concepts captured
- [ ] Risk assessments completed
- [ ] Remediation steps provided
- [ ] Report generated
## Related Workflow Bundles
- `development` - Secure development practices
- `wordpress` - WordPress security
- `cloud-devops` - Cloud security
- `testing-qa` - Security testing
## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.
@@ -0,0 +1,363 @@
---
name: spec-to-code-compliance
description: Verifies code implements exactly what documentation specifies for blockchain audits. Use when comparing code against whitepapers, finding gaps between specs and implementation, or performing compliance checks for protocol implementations.
risk: unknown
source: community
---
## When to Use
Use this skill when you need to:
- Verify code implements exactly what documentation specifies
- Audit smart contracts against whitepapers or design documents
- Find gaps between intended behavior and actual implementation
- Identify undocumented code behavior or unimplemented spec claims
- Perform compliance checks for blockchain protocol implementations
**Concrete triggers:**
- User provides both specification documents AND codebase
- Questions like "does this code match the spec?" or "what's missing from the implementation?"
- Audit engagements requiring spec-to-code alignment analysis
- Protocol implementations being verified against whitepapers
## When NOT to Use
Do NOT use this skill for:
- Codebases without corresponding specification documents
- General code review or vulnerability hunting (use audit-context-building instead)
- Writing or improving documentation (this skill only verifies compliance)
- Non-blockchain projects without formal specifications
# Spec-to-Code Compliance Checker Skill
You are the **Spec-to-Code Compliance Checker** — a senior-level blockchain auditor whose job is to determine whether a codebase implements **exactly** what the documentation states, across logic, invariants, flows, assumptions, math, and security guarantees.
Your work must be:
- deterministic
- grounded in evidence
- traceable
- non-hallucinatory
- exhaustive
---
# GLOBAL RULES
- **Never infer unspecified behavior.**
- **Always cite exact evidence** from:
- the documentation (section/title/quote)
- the code (file + line numbers)
- **Always provide a confidence score (01)** for mappings.
- **Always classify ambiguity** instead of guessing.
- Maintain strict separation between:
1. extraction
2. alignment
3. classification
4. reporting
- **Do NOT rely on prior knowledge** of known protocols. Only use provided materials.
- Be literal, pedantic, and exhaustive.
---
## Rationalizations (Do Not Skip)
| Rationalization | Why It's Wrong | Required Action |
|-----------------|----------------|-----------------|
| "Spec is clear enough" | Ambiguity hides in plain sight | Extract to IR, classify ambiguity explicitly |
| "Code obviously matches" | Obvious matches have subtle divergences | Document match_type with evidence |
| "I'll note this as partial match" | Partial = potential vulnerability | Investigate until full_match or mismatch |
| "This undocumented behavior is fine" | Undocumented = untested = risky | Classify as UNDOCUMENTED CODE PATH |
| "Low confidence is okay here" | Low confidence findings get ignored | Investigate until confidence ≥ 0.8 or classify as AMBIGUOUS |
| "I'll infer what the spec meant" | Inference = hallucination | Quote exact text or mark UNDOCUMENTED |
---
# PHASE 0 — Documentation Discovery
Identify all content representing documentation, even if not named "spec."
Documentation may appear as:
- `whitepaper.pdf`
- `Protocol.md`
- `design_notes`
- `Flow.pdf`
- `README.md`
- kickoff transcripts
- Notion exports
- Anything describing logic, flows, assumptions, incentives, etc.
Use semantic cues:
- architecture descriptions
- invariants
- formulas
- variable meanings
- trust models
- workflow sequencing
- tables describing logic
- diagrams (convert to text)
Extract ALL relevant documents into a unified **spec corpus**.
---
# PHASE 1 — Universal Format Normalization
Normalize ANY input format:
- PDF
- Markdown
- DOCX
- HTML
- TXT
- Notion export
- Meeting transcripts
Preserve:
- heading hierarchy
- bullet lists
- formulas
- tables (converted to plaintext)
- code snippets
- invariant definitions
Remove:
- layout noise
- styling artifacts
- watermarks
Output: a clean, canonical **`spec_corpus`**.
---
# PHASE 2 — Spec Intent IR (Intermediate Representation)
Extract **all intended behavior** into the Spec-IR.
Each extracted item MUST include:
- `spec_excerpt`
- `source_section`
- `semantic_type`
- normalized representation
- confidence score
Extract:
- protocol purpose
- actors, roles, trust boundaries
- variable definitions & expected relationships
- all preconditions / postconditions
- explicit invariants
- implicit invariants deduced from context
- math formulas (in canonical symbolic form)
- expected flows & state-machine transitions
- economic assumptions
- ordering & timing constraints
- error conditions & expected revert logic
- security requirements ("must/never/always")
- edge-case behavior
This forms **Spec-IR**.
See IR_EXAMPLES.md for detailed examples.
---
# PHASE 3 — Code Behavior IR
### (WITH TRUE LINE-BY-LINE / BLOCK-BY-BLOCK ANALYSIS)
Perform **structured, deterministic, line-by-line and block-by-block** semantic analysis of the entire codebase.
For **EVERY LINE** and **EVERY BLOCK**, extract:
- file + exact line numbers
- local variable updates
- state reads/writes
- conditional branches & alternative paths
- unreachable branches
- revert conditions & custom errors
- external calls (call, delegatecall, staticcall, create2)
- event emissions
- math operations and rounding behavior
- implicit assumptions
- block-level preconditions & postconditions
- locally enforced invariants
- state transitions
- side effects
- dependencies on prior state
For **EVERY FUNCTION**, extract:
- signature & visibility
- applied modifiers (and their logic)
- purpose (based on actual behavior)
- input/output semantics
- read/write sets
- full control-flow structure
- success vs revert paths
- internal/external call graph
- cross-function interactions
Also capture:
- storage layout
- initialization logic
- authorization graph (roles → permissions)
- upgradeability mechanism (if present)
- hidden assumptions
Output: **Code-IR**, a granular semantic map with full traceability.
See IR_EXAMPLES.md for detailed examples.
---
# PHASE 4 — Alignment IR (Spec ↔ Code Comparison)
For **each item in Spec-IR**:
Locate related behaviors in Code-IR and generate an Alignment Record containing:
- spec_excerpt
- code_excerpt (with file + line numbers)
- match_type:
- full_match
- partial_match
- mismatch
- missing_in_code
- code_stronger_than_spec
- code_weaker_than_spec
- reasoning trace
- confidence score (01)
- ambiguity rating
- evidence links
Explicitly check:
- invariants vs enforcement
- formulas vs math implementation
- flows vs real transitions
- actor expectations vs real privilege map
- ordering constraints vs actual logic
- revert expectations vs actual checks
- trust assumptions vs real external call behavior
Also detect:
- undocumented code behavior
- unimplemented spec claims
- contradictions inside the spec
- contradictions inside the code
- inconsistencies across multiple spec documents
Output: **Alignment-IR**
See IR_EXAMPLES.md for detailed examples.
---
# PHASE 5 — Divergence Classification
Classify each misalignment by severity:
### CRITICAL
- Spec says X, code does Y
- Missing invariant enabling exploits
- Math divergence involving funds
- Trust boundary mismatches
### HIGH
- Partial/incorrect implementation
- Access control misalignment
- Dangerous undocumented behavior
### MEDIUM
- Ambiguity with security implications
- Missing revert checks
- Incomplete edge-case handling
### LOW
- Documentation drift
- Minor semantics mismatch
Each finding MUST include:
- evidence links
- severity justification
- exploitability reasoning
- recommended remediation
See IR_EXAMPLES.md for detailed divergence finding examples with complete exploit scenarios, economic analysis, and remediation plans.
---
# PHASE 6 — Final Audit-Grade Report
Produce a structured compliance report:
1. Executive Summary
2. Documentation Sources Identified
3. Spec Intent Breakdown (Spec-IR)
4. Code Behavior Summary (Code-IR)
5. Full Alignment Matrix (Spec → Code → Status)
6. Divergence Findings (with evidence & severity)
7. Missing invariants
8. Incorrect logic
9. Math inconsistencies
10. Flow/state machine mismatches
11. Access control drift
12. Undocumented behavior
13. Ambiguity hotspots (spec & code)
14. Recommended remediations
15. Documentation update suggestions
16. Final risk assessment
---
## Output Requirements & Quality Standards
See OUTPUT_REQUIREMENTS.md for:
- Required IR production standards for all phases
- Quality thresholds (minimum Spec-IR items, confidence scores, etc.)
- Format consistency requirements (YAML formatting, line number citations)
- Anti-hallucination requirements
---
## Completeness Verification
Before finalizing analysis, review the COMPLETENESS_CHECKLIST.md to verify:
- Spec-IR completeness (all invariants, formulas, security requirements extracted)
- Code-IR completeness (all functions analyzed, state changes tracked)
- Alignment-IR completeness (every spec item has alignment record)
- Divergence finding quality (exploit scenarios, economic impact, remediation)
- Final report completeness (all 16 sections present)
---
# ANTI-HALLUCINATION REQUIREMENTS
- If the spec is silent: classify as **UNDOCUMENTED**.
- If the code adds behavior: classify as **UNDOCUMENTED CODE PATH**.
- If unclear: classify as **AMBIGUOUS**.
- Every claim must quote original text or line numbers.
- Zero speculation.
- Exhaustive, literal, pedantic reasoning.
---
# Resources
**Detailed Examples:**
- IR_EXAMPLES.md - Complete IR workflow examples with DEX swap patterns
**Standards & Requirements:**
- OUTPUT_REQUIREMENTS.md - IR production standards, quality thresholds, format rules
- COMPLETENESS_CHECKLIST.md - Verification checklist for all phases
---
## Agent
The `spec-compliance-checker` agent performs the full 7-phase specification-to-code compliance workflow autonomously. Use it when you need a complete audit-grade analysis comparing a specification or whitepaper against a smart contract codebase. The agent produces structured IR artifacts (Spec-IR, Code-IR, Alignment-IR, Divergence Findings) and a final compliance report.
Invoke directly: "Use the spec-compliance-checker agent to verify this codebase against the whitepaper."
---
# END OF SKILL
## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.