healthcare-phi-compliance
Protected Health Information (PHI) and Personally Identifiable Information (PII) compliance patterns for healthcare applications. Covers data classification, access control, audit trails, encryption, and common leak vectors.
About this skill
This skill provides an AI agent with deep insights and actionable patterns for ensuring data privacy and regulatory compliance in healthcare applications. It covers critical aspects such as robust data classification strategies, stringent access control mechanisms, detailed audit trail implementations, advanced encryption techniques, and identification of common data leak vectors. The patterns are designed to be applicable across multiple regulatory frameworks, including HIPAA (US), DISHA (India), and GDPR (EU), as well as general healthcare data protection principles. Sourced from 'Health1 Super Speciality Hospitals' and part of the 'everything-claude-code' repository, this skill leverages production-grade engineering patterns to guide AI agents in designing, developing, and reviewing systems that safeguard patient, clinician, and financial data.
Best use case
An AI agent can use this skill to: design secure database schemas for healthcare data; generate code snippets for compliant data handling (e.g., encryption, access checks); review existing application architectures or codebases for PHI/PII compliance vulnerabilities; and provide expert guidance on data protection strategies in clinical or administrative healthcare systems.
Protected Health Information (PHI) and Personally Identifiable Information (PII) compliance patterns for healthcare applications. Covers data classification, access control, audit trails, encryption, and common leak vectors.
The AI agent will generate designs, code, recommendations, or analyses that are inherently compliant with major healthcare data protection regulations. This leads to a reduced risk of data breaches, robust data security posture, and greater confidence in the regulatory adherence of healthcare applications it helps develop or evaluate.
Practical example
Example input
Design a secure, HIPAA-compliant API endpoint for retrieving a patient's allergy history. Include considerations for data encryption, access control, and audit logging.
Example output
```json
{
"api_endpoint_design": {
"path": "/patients/{patient_id}/allergies",
"method": "GET",
"authentication": "OAuth2 with JWT (patient-specific scope)",
"authorization": "Role-Based Access Control (RBAC): Only 'Doctor', 'Nurse', 'Patient' (for self) roles can access.",
"input_validation": "Validate patient_id as UUID; sanitize all input.",
"data_retrieval_strategy": {
"database_query": "SELECT encrypted_allergies FROM patient_records WHERE patient_id = :patient_id AND is_active = TRUE",
"encryption_details": "AES-256 GCM encryption. Key derived from KMS service, per-patient key management.",
"decryption_process": "Retrieve encrypted data -> fetch decryption key from KMS -> decrypt data server-side before sending."
},
"data_output": {
"fields": ["allergy_name", "severity", "reaction", "onset_date"],
"format": "JSON",
"masking_anonymization": "Ensure no PII other than patient_id (if authorized) is exposed in headers or URLs. Limit scope of data to only allergies."
},
"audit_logging": {
"log_event_types": ["data_access", "authorization_failure", "decryption_attempt"],
"log_details": "Timestamp, User ID, Patient ID, IP Address, Action (GET), Outcome (Success/Failure), Data fields accessed.",
"log_storage": "Immutable, tamper-evident log service, encrypted at rest."
},
"error_handling": "Generic error messages; avoid exposing sensitive system details."
},
"compliance_notes": [
"**HIPAA (Security Rule)**: Encryption for data in transit and at rest, access control, audit controls are fundamental.",
"**HIPAA (Privacy Rule)**: Minimum Necessary Standard applied by limiting data scope to allergies only.",
"**Data Classification**: Allergy history is classified as PHI and requires the highest level of protection."
]
}
```
**Additional Python snippet for data encryption (conceptual):**
```python
from cryptography.fernet import Fernet
import os
def encrypt_phi_field(data_to_encrypt: str, patient_id: str) -> bytes:
"""
Encrypts a single PHI field for a specific patient.
In a real system, key management would be more sophisticated (e.g., KMS, per-patient keys).
"""
# Placeholder: In production, retrieve a secure, patient-specific key from a KMS
# For demo: generate a key (NEVER do this in production for actual patient data)
key = os.getenv(f"PATIENT_{patient_id.replace('-', '_').upper()}_ENCRYPTION_KEY") # Example placeholder
if not key: # Generate a new key for the patient if not found (NOT for production)
key = Fernet.generate_key().decode()
# Store this key securely (e.g., KMS) associated with the patient_id
print(f"Warning: Generated temporary key for patient {patient_id}. In production, use KMS.")
f = Fernet(key.encode())
encrypted_data = f.encrypt(data_to_encrypt.encode())
return encrypted_data
def decrypt_phi_field(encrypted_data: bytes, patient_id: str) -> str:
"""
Decrypts an encrypted PHI field for a specific patient.
"""
key = os.getenv(f"PATIENT_{patient_id.replace('-', '_').upper()}_ENCRYPTION_KEY") # Example placeholder
if not key:
raise ValueError("Encryption key not found for patient.")
f = Fernet(key.encode())
decrypted_data = f.decrypt(encrypted_data).decode()
return decrypted_data
# Example usage:
# patient_data = "Penicillin: Anaphylactic shock"
# patient_id_example = "a1b2c3d4-e5f6-7890-1234-567890abcdef"
# encrypted = encrypt_phi_field(patient_data, patient_id_example)
# print(f"Encrypted: {encrypted}")
# decrypted = decrypt_phi_field(encrypted, patient_id_example)
# print(f"Decrypted: {decrypted}")
```When to use this skill
- When building any new feature or application component that processes, stores, or transmits patient records or other sensitive healthcare data.
- When designing or implementing access control, authentication, or authorization systems for clinical or administrative healthcare systems.
- When creating database schemas for storing any form of healthcare-related data, ensuring compliance from the ground up.
- When an AI agent is tasked with advising on, reviewing, or implementing data privacy and security measures in healthcare software development.
When not to use this skill
- For applications or systems that do not handle any form of Protected Health Information (PHI) or Personally Identifiable Information (PII) related to healthcare.
- When only general software security patterns are required, without the specific regulatory context and complexities of healthcare data protection.
- For tasks involving data privacy in domains entirely unrelated to healthcare (e.g., general e-commerce PII, financial non-PHI data).
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/healthcare-phi-compliance/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How healthcare-phi-compliance Compares
| Feature / Agent | healthcare-phi-compliance | Standard Approach |
|---|---|---|
| Platform Support | Claude | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | easy | N/A |
Frequently Asked Questions
What does this skill do?
Protected Health Information (PHI) and Personally Identifiable Information (PII) compliance patterns for healthcare applications. Covers data classification, access control, audit trails, encryption, and common leak vectors.
Which AI agents support this skill?
This skill is designed for Claude.
How difficult is it to install?
The installation complexity is rated as easy. You can find the installation instructions above.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
AI Agents for Coding
Browse AI agent skills for coding, debugging, testing, refactoring, code review, and developer workflows across Claude, Cursor, and Codex.
Best AI Skills for Claude
Explore the best AI skills for Claude and Claude Code across coding, research, workflow automation, documentation, and agent operations.
ChatGPT vs Claude for Agent Skills
Compare ChatGPT and Claude for AI agent skills across coding, writing, research, and reusable workflow execution.
SKILL.md Source
# Healthcare PHI/PII Compliance Patterns
Patterns for protecting patient data, clinician data, and financial data in healthcare applications. Applicable to HIPAA (US), DISHA (India), GDPR (EU), and general healthcare data protection.
## When to Use
- Building any feature that touches patient records
- Implementing access control or authentication for clinical systems
- Designing database schemas for healthcare data
- Building APIs that return patient or clinician data
- Implementing audit trails or logging
- Reviewing code for data exposure vulnerabilities
- Setting up Row-Level Security (RLS) for multi-tenant healthcare systems
## How It Works
Healthcare data protection operates on three layers: **classification** (what is sensitive), **access control** (who can see it), and **audit** (who did see it).
### Data Classification
**PHI (Protected Health Information)** — any data that can identify a patient AND relates to their health: patient name, date of birth, address, phone, email, national ID numbers (SSN, Aadhaar, NHS number), medical record numbers, diagnoses, medications, lab results, imaging, insurance policy and claim details, appointment and admission records, or any combination of the above.
**PII (Non-patient-sensitive data)** in healthcare systems: clinician/staff personal details, doctor fee structures and payout amounts, employee salary and bank details, vendor payment information.
### Access Control: Row-Level Security
```sql
ALTER TABLE patients ENABLE ROW LEVEL SECURITY;
-- Scope access by facility
CREATE POLICY "staff_read_own_facility"
ON patients FOR SELECT TO authenticated
USING (facility_id IN (
SELECT facility_id FROM staff_assignments
WHERE user_id = auth.uid() AND role IN ('doctor','nurse','lab_tech','admin')
));
-- Audit log: insert-only (tamper-proof)
CREATE POLICY "audit_insert_only" ON audit_log FOR INSERT
TO authenticated WITH CHECK (user_id = auth.uid());
CREATE POLICY "audit_no_modify" ON audit_log FOR UPDATE USING (false);
CREATE POLICY "audit_no_delete" ON audit_log FOR DELETE USING (false);
```
### Audit Trail
Every PHI access or modification must be logged:
```typescript
interface AuditEntry {
timestamp: string;
user_id: string;
patient_id: string;
action: 'create' | 'read' | 'update' | 'delete' | 'print' | 'export';
resource_type: string;
resource_id: string;
changes?: { before: object; after: object };
ip_address: string;
session_id: string;
}
```
### Common Leak Vectors
**Error messages:** Never include patient-identifying data in error messages thrown to the client. Log details server-side only.
**Console output:** Never log full patient objects. Use opaque internal record IDs (UUIDs) — not medical record numbers, national IDs, or names.
**URL parameters:** Never put patient-identifying data in query strings or path segments that could appear in logs or browser history. Use opaque UUIDs only.
**Browser storage:** Never store PHI in localStorage or sessionStorage. Keep PHI in memory only, fetch on demand.
**Service role keys:** Never use the service_role key in client-side code. Always use the anon/publishable key and let RLS enforce access.
**Logs and monitoring:** Never log full patient records. Use opaque record IDs only (not medical record numbers). Sanitize stack traces before sending to error tracking services.
### Database Schema Tagging
Mark PHI/PII columns at the schema level:
```sql
COMMENT ON COLUMN patients.name IS 'PHI: patient_name';
COMMENT ON COLUMN patients.dob IS 'PHI: date_of_birth';
COMMENT ON COLUMN patients.aadhaar IS 'PHI: national_id';
COMMENT ON COLUMN doctor_payouts.amount IS 'PII: financial';
```
### Deployment Checklist
Before every deployment:
- No PHI in error messages or stack traces
- No PHI in console.log/console.error
- No PHI in URL parameters
- No PHI in browser storage
- No service_role key in client code
- RLS enabled on all PHI/PII tables
- Audit trail for all data modifications
- Session timeout configured
- API authentication on all PHI endpoints
- Cross-facility data isolation verified
## Examples
### Example 1: Safe vs Unsafe Error Handling
```typescript
// BAD — leaks PHI in error
throw new Error(`Patient ${patient.name} not found in ${patient.facility}`);
// GOOD — generic error, details logged server-side with opaque IDs only
logger.error('Patient lookup failed', { recordId: patient.id, facilityId });
throw new Error('Record not found');
```
### Example 2: RLS Policy for Multi-Facility Isolation
```sql
-- Doctor at Facility A cannot see Facility B patients
CREATE POLICY "facility_isolation"
ON patients FOR SELECT TO authenticated
USING (facility_id IN (
SELECT facility_id FROM staff_assignments WHERE user_id = auth.uid()
));
-- Test: login as doctor-facility-a, query facility-b patients
-- Expected: 0 rows returned
```
### Example 3: Safe Logging
```typescript
// BAD — logs identifiable patient data
console.log('Processing patient:', patient);
// GOOD — logs only opaque internal record ID
console.log('Processing record:', patient.id);
// Note: even patient.id should be an opaque UUID, not a medical record number
```Related Skills
Export Compliance & Trade Controls
Analyze products, destinations, and end-users against US export control regulations (EAR, ITAR, OFAC sanctions). Generate classification recommendations, license requirements, and compliance checklists.
Environmental Compliance Manager
Assess, track, and maintain environmental regulatory compliance across EPA, state agencies, and industry-specific requirements. Built for manufacturing, construction, energy, logistics, and any business with environmental obligations.
healthcare-eval-harness
Patient safety evaluation harness for healthcare application deployments. Automated test suites for CDSS accuracy, PHI exposure, clinical workflow integrity, and integration compliance. Blocks deployments on safety failures.
healthcare-emr-patterns
EMR/EHR development patterns for healthcare applications. Clinical safety, encounter workflows, prescription generation, clinical decision support integration, and accessibility-first UI for medical data entry.
healthcare-cdss-patterns
Clinical Decision Support System (CDSS) development patterns. Drug interaction checking, dose validation, clinical scoring (NEWS2, qSOFA), alert severity classification, and integration into EMR workflows.
customs-trade-compliance
海关文件、关税分类、关税优化、受限方筛查以及多司法管辖区法规合规的编码化专业知识。由拥有15年以上经验的贸易合规专家提供。包括HS分类逻辑、Incoterms应用、自贸协定利用以及罚款减免。适用于处理海关清关、关税分类、贸易合规、进出口文件或关税优化时使用。license: Apache-2.0
workspace-surface-audit
Audit the active repo, MCP servers, plugins, connectors, env surfaces, and harness setup, then recommend the highest-value ECC-native skills, hooks, agents, and operator workflows. Use when the user wants help setting up Claude Code or understanding what capabilities are actually available in their environment.
ui-demo
Record polished UI demo videos using Playwright. Use when the user asks to create a demo, walkthrough, screen recording, or tutorial video of a web application. Produces WebM videos with visible cursor, natural pacing, and professional feel.
token-budget-advisor
Offers the user an informed choice about how much response depth to consume before answering. Use this skill when the user explicitly wants to control response length, depth, or token budget. TRIGGER when: "token budget", "token count", "token usage", "token limit", "response length", "answer depth", "short version", "brief answer", "detailed answer", "exhaustive answer", "respuesta corta vs larga", "cuántos tokens", "ahorrar tokens", "responde al 50%", "dame la versión corta", "quiero controlar cuánto usas", or clear variants where the user is explicitly asking to control answer size or depth. DO NOT TRIGGER when: user has already specified a level in the current session (maintain it), the request is clearly a one-word answer, or "token" refers to auth/session/payment tokens rather than response size.
skill-comply
Visualize whether skills, rules, and agent definitions are actually followed — auto-generates scenarios at 3 prompt strictness levels, runs agents, classifies behavioral sequences, and reports compliance rates with full tool call timelines
santa-method
Multi-agent adversarial verification with convergence loop. Two independent review agents must both pass before output ships.
safety-guard
Use this skill to prevent destructive operations when working on production systems or running agents autonomously.