@bharathwaj1421/cpm-sdk-core
v2.0.0
Published
Core consent and preference management engine
Maintainers
Readme
@cpm-sdk/core
The core package of the CPM SDK provides the fundamental consent and preference management functionality. This package is framework-agnostic and can be used independently or as part of the full SDK.
🚀 Features
- Multi-Storage Support: localStorage, cookies, sessionStorage, and memory storage
- Data Encryption: AES-256 encryption with PBKDF2 key derivation
- Type Safety: Full TypeScript support with comprehensive type definitions
- Compliance Ready: Built-in support for GDPR, CCPA, and LGPD compliance
- Event System: Comprehensive event tracking and audit trails
- Validation: Built-in data validation and integrity checks
- Performance: Optimized for minimal bundle size and fast operations
📦 Installation
npm install @cpm-sdk/core
# or
yarn add @cpm-sdk/core
# or
pnpm add @cpm-sdk/core🔧 Basic Usage
Initialize the SDK
import { StorageManager, ConsentData } from '@cpm-sdk/core';
// Configure storage settings
const storageSettings = {
type: 'localStorage',
encryption: {
enabled: true,
algorithm: 'AES-256-GCM',
keyDerivation: 'PBKDF2',
saltRounds: 10000,
},
retention: {
consentData: 365,
auditTrail: 2555,
preferences: 365,
anonymizeAfterRetention: false,
},
};
// Create storage manager
const storageManager = new StorageManager(storageSettings);Save Consent Data
const consentData: ConsentData = {
id: 'user-consent-1',
sessionId: 'session-123',
timestamp: new Date(),
version: '1.0',
categories: {
necessary: true,
analytics: false,
marketing: false,
},
preferences: {
language: 'en',
theme: 'light',
notifications: {
email: true,
push: false,
sms: false,
frequency: 'daily',
},
marketing: {
personalizedAds: false,
thirdPartyMarketing: false,
socialMediaTracking: false,
emailMarketing: false,
},
analytics: {
performance: false,
behavior: false,
errorTracking: false,
abTesting: false,
},
custom: {},
},
auditTrail: [],
source: 'banner',
};
// Save consent data
await storageManager.saveConsent(consentData);Load Consent Data
// Load existing consent data
const consent = await storageManager.loadConsent();
if (consent) {
console.log('User has given consent for:', consent.categories);
console.log('User preferences:', consent.preferences);
} else {
console.log('No consent data found');
}Check Consent Status
const consent = await storageManager.loadConsent();
if (consent?.categories.analytics) {
// Load analytics
loadAnalytics();
} else {
// Show analytics consent request
showAnalyticsConsent();
}🗄️ Storage Options
LocalStorage (Default)
const localStorageSettings = {
type: 'localStorage',
encryption: { enabled: false },
retention: { consentData: 365, auditTrail: 2555, preferences: 365 }
};Cookies
const cookieSettings = {
type: 'cookies',
cookies: {
path: '/',
expires: 365,
secure: true,
httpOnly: false,
sameSite: 'lax',
},
encryption: { enabled: true },
retention: { consentData: 365, auditTrail: 2555, preferences: 365 }
};SessionStorage
const sessionStorageSettings = {
type: 'sessionStorage',
encryption: { enabled: false },
retention: { consentData: 1, auditTrail: 1, preferences: 1 }
};Memory Storage
const memoryStorageSettings = {
type: 'memory',
encryption: { enabled: false },
retention: { consentData: 1, auditTrail: 1, preferences: 1 }
};🔐 Encryption
Enable Encryption
const encryptedSettings = {
type: 'localStorage',
encryption: {
enabled: true,
algorithm: 'AES-256-GCM', // or 'AES-256-CBC'
keyDerivation: 'PBKDF2', // or 'Argon2'
saltRounds: 10000,
},
retention: { consentData: 365, auditTrail: 2555, preferences: 365 }
};
const secureStorage = new StorageManager(encryptedSettings);Check Encryption Support
import { EncryptedStorage } from '@cpm-sdk/core';
if (EncryptedStorage.isSupported()) {
console.log('Encryption is supported');
console.log('Supported algorithms:', EncryptedStorage.getSupportedAlgorithms());
console.log('Supported key derivation:', EncryptedStorage.getSupportedKeyDerivation());
} else {
console.log('Encryption is not supported in this environment');
}📊 Data Management
Export Data
// Export all stored data
const exportedData = await storageManager.exportData();
console.log('Exported consent:', exportedData.consent);
console.log('Exported config:', exportedData.config);
console.log('Exported preferences:', exportedData.preferences);
console.log('Export metadata:', exportedData.metadata);Import Data
// Import data from export
await storageManager.importData({
consent: exportedData.consent,
config: exportedData.config,
preferences: exportedData.preferences,
});Clear All Data
// Clear all stored data
await storageManager.clear();Migrate Storage
// Migrate from one storage type to another
const newSettings = {
type: 'cookies',
cookies: { path: '/', expires: 365, secure: true },
encryption: { enabled: true },
retention: { consentData: 365, auditTrail: 2555, preferences: 365 }
};
await storageManager.migrateStorage(newSettings);🧪 Testing
Run Tests
# Run all tests
pnpm test
# Run tests in watch mode
pnpm test:watch
# Run tests with coverage
pnpm test:coverageTest Setup
The package includes comprehensive test setup with:
- Mocked localStorage and sessionStorage
- Mocked crypto API
- Mocked document.cookie
- Test utilities and helpers
📚 API Reference
StorageManager
Constructor
constructor(settings: StorageSettings)Methods
saveConsent(consent: ConsentData): Promise<void>loadConsent(): Promise<ConsentData | null>deleteConsent(): Promise<void>saveConfig(config: ConsentConfiguration): Promise<void>loadConfig(): Promise<ConsentConfiguration | null>savePreferences(preferences: any): Promise<void>loadPreferences(): Promise<any | null>isAvailable(): booleangetSize(): Promise<number>clear(): Promise<void>migrateStorage(newSettings: StorageSettings): Promise<void>exportData(): Promise<ExportData>importData(data: ImportData): Promise<void>
StorageAdapter
Interface for custom storage implementations:
interface StorageAdapter {
save(key: string, data: ConsentData): Promise<void>;
load(key: string): Promise<ConsentData | null>;
delete(key: string): Promise<void>;
isAvailable(): boolean;
getSize(): Promise<number>;
clear(): Promise<void>;
}EncryptedStorage
Utility class for data encryption:
class EncryptedStorage {
constructor(settings: EncryptionSettings);
encrypt(data: any): Promise<EncryptedData>;
decrypt(encryptedData: EncryptedData): Promise<any>;
static isSupported(): boolean;
static getSupportedAlgorithms(): string[];
static getSupportedKeyDerivation(): string[];
static generateKey(algorithm?: string): Promise<CryptoKey>;
static exportKey(key: CryptoKey): Promise<string>;
static importKey(keyData: string, algorithm?: string): Promise<CryptoKey>;
static hash(data: string): Promise<string>;
static verifyHash(data: string, expectedHash: string): Promise<boolean>;
}🔧 Configuration
StorageSettings
interface StorageSettings {
type: 'localStorage' | 'cookies' | 'sessionStorage' | 'memory';
cookies?: CookieSettings;
encryption: EncryptionSettings;
retention: RetentionSettings;
}EncryptionSettings
interface EncryptionSettings {
enabled: boolean;
algorithm: 'AES-256-GCM' | 'AES-256-CBC';
keyDerivation: 'PBKDF2' | 'Argon2';
saltRounds: number;
}RetentionSettings
interface RetentionSettings {
consentData: number; // Days to retain consent data
auditTrail: number; // Days to retain audit trail
preferences: number; // Days to retain preferences
anonymizeAfterRetention: boolean;
}🚀 Performance
Bundle Size
- Core package: ~15KB gzipped
- With encryption: ~20KB gzipped
- Tree-shakeable: Only import what you need
Runtime Performance
- Storage operations: < 1ms for typical data
- Encryption: < 5ms for typical data
- Memory usage: < 1MB for typical usage
🔒 Security
Data Protection
- Encryption: AES-256 encryption with secure key derivation
- Integrity: Data validation and integrity checks
- Privacy: No data sent to external servers
- Compliance: Built-in GDPR, CCPA, and LGPD support
Best Practices
- Enable encryption for sensitive data
- Use secure cookie settings in production
- Regularly rotate encryption keys
- Validate all input data
- Implement proper access controls
🤝 Contributing
We welcome contributions! Please see our Contributing Guide for details.
Development Setup
# Install dependencies
pnpm install
# Start development mode
pnpm dev
# Run tests
pnpm test
# Build package
pnpm build📄 License
This package is licensed under the MIT License - see the LICENSE file for details.
🆘 Support
- Documentation: docs/
- Issues: GitHub Issues
- Discussions: GitHub Discussions
Built with ❤️ for privacy-first web applications
This core package provides the foundation for building compliant consent and preference management solutions.
