Skip to content

maribeiromendes/privakit

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

34 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ›‘οΈ Privakit

A comprehensive TypeScript/JavaScript library for handling Personally Identifiable Information (PII) with privacy-first design principles.

Privakit provides enterprise-grade tools for detecting, validating, masking, redacting, and managing personal data in compliance with GDPR, CCPA, and other privacy regulations.

SonarQube Cloud

Security Rating VulnerabilitiesCodeQL

✨ Key Features

  • πŸ” Smart PII Detection - Automatically find 17+ types of PII in text using NLP and pattern matching
  • βœ… Robust Validation - Validate emails, phones, names, and addresses with international support
  • 🎭 Safe Masking - Display-safe concealment while preserving usability
  • 🚫 Secure Redaction - Complete removal for logging and archival
  • βš–οΈ Policy Engine - GDPR/CCPA compliance automation with audit trails
  • πŸ”§ Data Normalization - Standardize formats across locales and providers
  • 🌐 Zero Dependencies - No external API calls, completely local processing
  • πŸ“¦ Tree Shakable - Import only what you need for optimal bundle size

πŸš€ Quick Start

//: ### Installation

//: npm install privakit # or yarn add privakit # or pnpm add privakit //: ```

Basic Usage

import { detectPII, maskPII, createPolicyEngine } from "privakit";

// Detect PII in text
const text = "Contact John Doe at john@example.com or call (555) 123-4567";
const detection = detectPII(text);
console.log(detection.hasPII); // true
console.log(detection.detectedTypes); // ['name', 'email', 'phone']

// Apply safe masking for display
const maskedEmail = maskPII("john@example.com", "email");
console.log(maskedEmail.masked); // "j***@example.com"

// GDPR-compliant policy enforcement
const gdprEngine = createPolicyEngine("gdpr");
const decision = gdprEngine.evaluate("email", "log");
console.log(decision.allowed); // false (protects by default)

πŸ—οΈ What is PII and Why It Matters

Personally Identifiable Information (PII) is any data that can identify, contact, or locate an individual. This includes:

  • Direct identifiers: Names, emails, phone numbers, SSNs, addresses
  • Digital footprints: IP addresses, device IDs, online accounts
  • Financial data: Credit cards, bank accounts, payment information
  • Behavioral data: Location history, browsing patterns, preferences

Why PII Protection is Critical

  1. Legal Compliance πŸ“š

    • GDPR: €20M+ fines for violations
    • CCPA: $7,500 per violation
    • HIPAA, SOX, PCI DSS requirements
  2. Security Risks πŸ”’

    • Data breaches affecting millions
    • Identity theft and fraud
    • Social engineering attacks
  3. Business Impact πŸ’Ό

    • Customer trust and retention
    • Reputation management
    • Competitive advantage

πŸ”§ Core Modules

Module

Purpose

Key Features

Detection

Find PII in text

17+ PII types, NLP-powered, confidence scoring

Validation

Verify PII correctness

International support, custom rules, batch processing

Masking

Hide PII safely

Preserve usability, configurable visibility, role-based

Redaction

Remove PII completely

Logging safety, middleware, audit trails

Policy Engine

Automate compliance

GDPR/CCPA ready, risk-based rules, audit logging

Normalization

Standardize formats

Locale-aware, provider-specific, consistent data

πŸ“– Comprehensive Documentation

πŸ›‘οΈ Privacy & Security First

Privakit is built with privacy by design principles:

βœ… Complete Privacy Protection

  • No telemetry or tracking - Zero data collection
  • Local processing only - No external API calls or network requests
  • No data retention - Stateless processing, no persistent storage
  • Secure by default - Conservative privacy settings out-of-the-box

βœ… Enterprise Security

  • Memory safe - Automatic cleanup of sensitive data
  • Error safe - No PII leaked in error messages or logs
  • Audit ready - Comprehensive logging and compliance reporting
  • Deterministic - Consistent, predictable results

βœ… Compliance Ready

  • GDPR Article 25 - Privacy by design and by default
  • CCPA Section 1798.100 - Consumer privacy rights
  • ISO 27001 - Information security management
  • SOC 2 Type II - Security, availability, and confidentiality

🌐 Third-Party Dependencies

Privakit uses carefully selected, privacy-respecting dependencies:

Library

Version

License

Purpose

Privacy Impact

validator.js

^13.12.0

MIT

Email validation

βœ… Client-side only, no network calls

libphonenumber-js

^1.11.19

MIT

Phone number validation

βœ… Local processing, Google's offline data

compromise

^14.14.4

MIT

NLP for name detection

βœ… Pure JavaScript, no remote API

Why These Dependencies Are Safe

  1. No Network Activity: All processing happens locally
  2. Open Source: Full transparency, auditable code
  3. Established Libraries: Well-maintained, widely used
  4. MIT Licensed: Compatible with commercial use
  5. Privacy Focused: No tracking or data collection

🎯 Real-World Examples

Form Validation with Privacy

import { validateEmail, validatePhone, createPolicyEngine } from 'privakit';async function handleUserRegistration(formData: any) {  const policy = createPolicyEngine('gdpr');    // Validate email  const emailResult = validateEmail(formData.email);  if (!emailResult.isValid) {    throw new Error('Invalid email format');  }    // Check if processing is allowed  const emailDecision = policy.evaluate('email', 'store');  if (!emailDecision.allowed) {    throw new Error('Email processing not permitted');  }    // Safely store with encryption (as required by policy)  if (emailDecision.requiresEncryption) {    formData.email = await encryptPII(emailResult.normalized);  }    return saveUser(formData);}

Log Sanitization

import { createSafeLogger } from "privakit"; // Create PII-safe loggerconst logger = createSafeLogger({  replacement: '[REDACTED]',  strictMode: true});// All PII automatically redactedlogger.log('User john@example.com failed login from 192.168.1.100');// Output: "User [REDACTED] failed login from [REDACTED]"

Content Moderation

import { detectPII, processPII } from 'privakit';function moderateUserContent(content: string) {  const result = processPII(content, {    policy: createPolicyEngine('strict')  });    if (result.policyViolations.length > 0) {    return {      approved: false,      reason: 'Contains sensitive information',      safeMasked: result.masked  // Safe version for review    };  }    return { approved: true, content };}

πŸ”„ Migration and Integration

From Other Libraries

// Migrating from custom validation// Before:const isValidEmail = (email) => /S+@S+.S+/.test(email);// After:import { validateEmail } from 'privakit';const emailResult = validateEmail(email);const isValidEmail = emailResult.isValid;

Framework Integration

Privakit works seamlessly with all major frameworks:

React/Next.js

import { detectPII, maskPII } from 'privakit';function UserProfile({ user }) {  const maskedEmail = maskPII(user.email, 'email').masked;    return (    <div>      <span>{maskedEmail}</span>    </div>  );}

Vue.js/Nuxt

<script setup>
import { detectPII, maskPII } from "privakit";
const email = ref("user@example.com");
const maskedEmail = computed(() => maskPII(email.value, "email").masked);
</script>

Angular

import { detectPII, maskPII } from 'privakit';@Component({...})export class UserComponent {  getMaskedEmail(email: string) {    return maskPII(email, 'email').masked;  }}

Node.js/Express

import { createRedactionMiddleware } from "privakit";
app.use(
  createRedactionMiddleware({
    strictMode: process.env.NODE_ENV === "production",
  }),
);

πŸ“– Complete Framework Guide - Detailed integration examples for React, Vue, Angular, Svelte, Next.js, Nuxt, and more.

πŸ“Š Performance & Bundle Size

  • Core library: ~50KB gzipped
  • Tree-shakeable: Import only what you need
  • Zero runtime dependencies: All deps are for validation/NLP
  • Memory efficient: No data retention between calls
  • Fast processing: Optimized regex and NLP pipelines
// Minimal import for bundle optimization
import { validateEmail } from "privakit/validate/email";
import { maskEmail } from "privakit/mask";
// Only email validation and masking included in bundle

πŸ§ͺ Interactive Test App

Experience privakit in action with our comprehensive test application! The test app provides a visual interface to explore all privakit features.

🌐 Try It Online

Live Demo β†’ (Auto-deployed from main branch)

πŸš€ Run Locally

# Clone the repository
git clone https://github.com/maribeiromendes/privakit.git
cd privakit

# Install dependencies
npm install

# Start the test app (builds and runs privakit + Vue test interface)
npm run dev:test-app

The test app will be available at http://localhost:5175

✨ Test App Features

πŸ§ͺ Interactive Testing Sections:

  • πŸ“§ Validation & Normalization - Test email, phone, name validation with real-time feedback
  • πŸ” PII Detection - Analyze text for personal information with confidence scoring
  • 🎭 Masking & Redaction - Compare display-safe masking vs secure redaction
  • βš–οΈ Policy Engine - Test GDPR/CCPA compliance with strict/permissive modes
  • 🌍 Locales - International validation testing (phone validation via libphonenumber-js)
  • βš–οΈ Compliance Engines - Test against 6 major privacy regulations with official law links
  • πŸ”„ Complete Pipeline - End-to-end PII processing demonstration
  • πŸ’‘ Examples - Real-world use case scenarios

πŸ“– Built-in Documentation:

  • Step-by-step usage guides for each feature
  • Live links to official privacy regulation texts
  • Implementation status transparency
  • Pro tips and examples

πŸ› οΈ Current Implementation Status

βœ… Fully Implemented:

  • PII Detection - 17+ PII types with NLP and pattern matching
  • Phone Validation - International support via libphonenumber-js (US, BR, CA, GB, DE, and more)
  • Email Validation - Comprehensive validation with domain analysis
  • Name Validation - Person name detection and normalization
  • Address Validation - Basic address parsing and validation
  • Masking & Redaction - Display-safe masking vs secure redaction
  • Policy Engine - GDPR/CCPA compliance automation
  • Compliance Testing - Multi-regulation validation (GDPR, LGPD, HIPAA, CCPA, PIPEDA, Privacy Act)

🚧 In Development:

  • Full Locale Support - Country-specific validation rules (currently /src/locales/ folders are placeholders)
  • Advanced Address Validation - Region-specific address formats
  • Cultural Name Patterns - Locale-aware name validation beyond basic patterns

πŸ“‹ Planned:

  • Biometric Data Detection - Advanced pattern recognition
  • Real-time Streaming - Processing live data streams
  • Advanced Anonymization - k-anonymity and differential privacy

🀝 Help Us Improve

🌟 We need your help to make privakit better!

πŸ“± Test the App:

  • Try the test app and report any issues
  • Test with real-world data from your use cases
  • Suggest new features or improvements

🌍 Deploy the Demo:

  • Help us deploy the test app to Vercel, Netlify, or other platforms
  • Share the live demo with your team
  • Contribute deployment configurations

πŸ’» Contribute Code:

  • Implement locale-specific validation rules
  • Add new PII detection patterns
  • Improve compliance engine accuracy
  • Enhance documentation

πŸ”— Get Started Contributing:

# Run the test app locally
npm run dev:test-app

# Run the test suite
npm test

# Check specific functionality
node dev-scripts/validation/test-privacy.js

🀝 Contributing

We welcome contributions! Please open an issue or submit a pull request.

Development

git clone https://github.com/maribeiromendes/privakit.git
cd privakit
npm install
npm run dev     # Start development mode
npm test        # Run test suite
npm run build   # Build for production

Development Scripts

The dev-scripts/ folder contains organized development and testing utilities:

  • dev-scripts/debug/ - Component-specific debugging scripts
  • dev-scripts/validation/ - Privacy compliance and dependency testing
  • dev-scripts/research/ - Pattern research and improvement scripts
  • dev-scripts/utils/ - Build validation and utility scripts

Quick validation commands:

# Verify privacy compliance (CRITICAL before any release)
node dev-scripts/validation/test-privacy.js

# Test basic functionality
node dev-scripts/validation/test-simple.js

# Debug specific components
node dev-scripts/debug/test-phone-debug.js

See dev-scripts/README.md for detailed documentation on all available scripts.

πŸ“ License

MIT License - see LICENSE file for details.

πŸ”’ Security

For security issues, please report them privately via the GitHub security tab.

πŸ“Š Code Quality & Metrics

Quality Gate Status Coverage Reliability Rating Maintainability Rating

Bugs Code Smells Technical Debt Lines of Code


Built with ❀️ for developers who care about privacy.

Privakit - Making PII protection simple, automatic, and compliant.

About

Privakit is a TypeScript/JavaScript library for handling Personally Identifiable Information (PII) in web and Node.js apps. It provides tools to validate, normalize, mask, redact, and (pseudo)anonymize personal data, with optional free-text PII detection.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors