@powercred/liveguard-sdk
v1.0.0
Published
PowerCred LiveGuard SDK - Offline passive liveness detection and face matching for JavaScript
Maintainers
Readme
PowerCred LiveGuard SDK
A comprehensive JavaScript SDK for offline passive liveness detection and face matching between ID card photos and selfies. Built with TypeScript and optimized for web and mobile applications.
✨ Features
- 🛡️ Passive Liveness Detection - No user interaction required
- 📱 Complete Offline Operation - No API calls, works without internet
- 🔍 Face Matching - Compare ID card photos with selfies
- ⚡ WebAssembly Acceleration - Optimized performance
- 🎯 High Accuracy - Advanced ML algorithms for reliable results
- 🔒 Privacy First - All processing happens on-device
- 📦 Easy Integration - Simple API with TypeScript support
- 🌐 Cross-Platform - Works in browsers and mobile web apps
🚀 Quick Start
Installation
npm install @powercred/liveguard-sdkBasic Usage
import { LiveGuardSDK } from '@powercred/liveguard-sdk'
// Initialize the SDK
const sdk = new LiveGuardSDK({
modelPath: '/models', // Path to model files
debug: true
})
// Initialize and load models
await sdk.initialize()
// Verify identity
const result = await sdk.verifyIdentity(idCardFile, selfieFile)
if (result.success && result.data?.isVerified) {
console.log('✅ Identity verified!')
console.log(`Similarity: ${result.data.matchResult.similarity}%`)
console.log(`Liveness: ${result.data.livenessResult.isLive ? 'Live' : 'Spoof'}`)
} else {
console.log('❌ Verification failed:', result.error)
}Quick Verification (One-liner)
import { quickVerify } from '@powercred/liveguard-sdk'
const result = await quickVerify(idCardFile, selfieFile, {
matchThreshold: 85,
debug: true
})📖 API Documentation
Core Classes
LiveGuardSDK
The main SDK class providing all functionality.
const sdk = new LiveGuardSDK(config?: LiveGuardConfig)Configuration Options:
interface LiveGuardConfig {
modelPath?: string // Path to model files (default: '/models')
debug?: boolean // Enable debug logging (default: false)
minFaceConfidence?: number // Face detection threshold 0-1 (default: 0.8)
livenessSensitivity?: number // Liveness detection sensitivity 0-1 (default: 0.7)
matchThreshold?: number // Face matching threshold 0-100 (default: 80)
}Methods:
initialize(): Promise<ProcessingResult<SDKInfo>>- Initialize SDK and load modelsextractIDFace(file: File): Promise<ProcessingResult<FaceData>>- Extract face from ID cardanalyzeSelfie(file: File): Promise<ProcessingResult<LivenessResult>>- Analyze selfie for livenesscompareFaces(idFace: FaceData, selfieFace: FaceData): Promise<ProcessingResult<MatchResult>>- Compare two facesverifyIdentity(idFile: File, selfieFile: File): Promise<ProcessingResult<VerificationResult>>- Complete verification workflow
Result Types
LivenessResult
interface LivenessResult {
isLive: boolean // Whether the face appears to be from a live person
confidence: number // Overall confidence score (0-1)
metrics: {
skinTexture: number // Skin texture analysis (0-1)
lightReflection: number // Light reflection patterns (0-1)
spoofDetection: number // Spoof attempt detection (0-1)
// ... more metrics
}
faceData: FaceData | null // Extracted face information
}MatchResult
interface MatchResult {
similarity: number // Similarity percentage (0-100)
isMatch: boolean // Whether faces match based on threshold
distance: number // Euclidean distance between embeddings
cosineSimilarity: number // Cosine similarity score
confidence: 'high' | 'medium' | 'low' // Match confidence level
}🛠️ Setup and Installation
1. Install the Package
npm install @powercred/liveguard-sdk2. Download Model Files
The SDK requires pre-trained models. Download them from our releases:
# Create models directory
mkdir public/models
# Download face detection models (replace with actual URLs)
wget -O public/models/ssd_mobilenetv1_model.json [MODEL_URL]
wget -O public/models/ssd_mobilenetv1_weights.bin [MODEL_URL]
wget -O public/models/face_landmark_68_model.json [MODEL_URL]
wget -O public/models/face_landmark_68_weights.bin [MODEL_URL]
wget -O public/models/face_recognition_model.json [MODEL_URL]
wget -O public/models/face_recognition_weights.bin [MODEL_URL]3. Configure Your Build Tool
Vite Configuration
// vite.config.ts
export default defineConfig({
// ... other config
assetsInclude: ['**/*.bin', '**/*.json'], // Include model files
server: {
headers: {
'Cross-Origin-Embedder-Policy': 'require-corp',
'Cross-Origin-Opener-Policy': 'same-origin'
}
}
})Webpack Configuration
// webpack.config.js
module.exports = {
// ... other config
module: {
rules: [
{
test: /\.(bin|json)$/,
type: 'asset/resource'
}
]
}
}🎯 Advanced Usage
Individual Component Usage
import { FaceExtractor, LivenessAnalyzer, FaceMatcher } from '@powercred/liveguard-sdk'
// Use components individually for more control
const extractor = new FaceExtractor(logger, 0.8)
const analyzer = new LivenessAnalyzer(logger, 0.7)
const matcher = new FaceMatcher(logger, 80)
await extractor.initialize()
await analyzer.initialize()
await matcher.initialize()
// Extract faces
const idFace = await extractor.extractFromIDCard(idFile)
const selfieFace = await extractor.extractFromSelfie(selfieFile)
// Analyze liveness
const livenessResult = await analyzer.analyze(selfieFile, selfieFace)
// Compare faces
const matchResult = await matcher.compare(idFace, selfieFace)Custom Image Processing
import { ImageProcessor } from '@powercred/liveguard-sdk'
const processor = new ImageProcessor(logger)
// Preprocess images
const canvas = await processor.fileToCanvas(imageFile, {
maxWidth: 800,
maxHeight: 600,
grayscale: false,
quality: 0.8
})
// Enhance image quality
processor.enhanceContrast(canvas, 1.2)
processor.equalizeHistogram(canvas)
// Assess image quality
const quality = processor.assessImageQuality(canvas)Batch Processing
// Process multiple face comparisons
const candidates = [face1, face2, face3, face4]
const results = await matcher.compareOneToMany(queryFace, candidates)
// Find best match
const bestMatch = await matcher.findBestMatch(queryFace, candidates)🔧 Configuration Options
Performance Tuning
const config = {
// Adjust for performance vs accuracy trade-off
minFaceConfidence: 0.7, // Lower = faster, less accurate
livenessSensitivity: 0.8, // Higher = more strict
matchThreshold: 75, // Lower = more permissive matching
// Image processing options
maxImageWidth: 1024, // Reduce for better performance
maxImageHeight: 1024
}Quality Thresholds
// Fine-tune quality requirements
const imageOptions = {
maxWidth: 800,
maxHeight: 600,
quality: 0.9, // JPEG quality for preprocessing
grayscale: false // Keep color for better detection
}🧪 Testing
Run the Demo
# Clone the repository
git clone https://github.com/powercred/liveguard-sdk.git
cd liveguard-sdk
# Install dependencies
npm install
# Start development server
npm run dev
# Open demo at http://localhost:3000/examples/web/Unit Tests
npm testBrowser Compatibility Test
import { checkBrowserSupport } from '@powercred/liveguard-sdk'
const support = checkBrowserSupport()
if (!support.supported) {
console.warn('Missing features:', support.missing)
}🌐 Browser Support
- ✅ Chrome 80+
- ✅ Firefox 75+
- ✅ Safari 13+
- ✅ Edge 80+
- ✅ Mobile browsers (iOS Safari, Chrome Mobile)
Required Features:
- WebGL (for GPU acceleration)
- Canvas API
- File API
- WebAssembly
- ES2020 support
📊 Performance
Benchmarks
| Operation | Time (avg) | Notes | |-----------|------------|-------| | SDK Initialization | ~2-5s | One-time model loading | | ID Face Extraction | ~200-500ms | Depends on image size | | Selfie Liveness Analysis | ~300-800ms | Complex analysis | | Face Comparison | ~50-100ms | Fast embedding comparison | | Complete Verification | ~1-2s | Full workflow |
Memory Usage
- Initial Load: ~15-25MB (models + runtime)
- Per Image: ~5-10MB (temporary processing)
- Background: ~8-12MB (loaded models)
Optimization Tips
- Preload Models: Use
preloadModels()during app initialization - Image Size: Limit input images to 1024px max dimension
- Batch Processing: Process multiple comparisons together
- Memory Management: Clear results when not needed
🛡️ Security Considerations
Privacy
- ✅ No Data Transmission: All processing happens locally
- ✅ No Data Storage: Images are processed in memory only
- ✅ No Tracking: SDK doesn't collect any analytics
Security Features
- 🔒 Spoof Detection: Advanced algorithms detect printed photos, screens, masks
- 🔍 Quality Assessment: Ensures sufficient image quality for reliable analysis
- ⚡ Fast Processing: Reduces attack window with quick verification
🤝 Contributing
We welcome contributions! Please see our Contributing Guide for details.
Development Setup
git clone https://github.com/powercred/liveguard-sdk.git
cd liveguard-sdk
npm install
npm run dev📄 License
MIT License - see LICENSE file for details.
🆘 Support
- 📚 Documentation: https://docs.powercred.com/liveguard
- 🐛 Issues: GitHub Issues
- 💬 Discussions: GitHub Discussions
- 📧 Email: [email protected]
🎉 Acknowledgments
Built with:
- TensorFlow.js - Machine Learning runtime
- face-api.js - Face detection and recognition
- Vite - Build tool and development server
PowerCred LiveGuard SDK - Secure, Fast, and Privacy-First Identity Verification 🛡️
