facezkp
Version:
Face analysis library with liveness detection, biometric template extraction, and fuzzy hashing for privacy-preserving identity verification.
306 lines (226 loc) • 7.96 kB
Markdown
# FaceZKP - ZKP-AI Proof of Humanity
[](https://badge.fury.io/js/%40facezk%2Fcore)
[](https://opensource.org/licenses/MIT)
[](https://github.com/VerifiedOnchain/facezk-lib/actions)
[](https://codecov.io/gh/facezk/facezk-lib)
**Face analysis library with liveness detection, biometric template extraction, and fuzzy hashing for privacy-preserving identity verification.**
## Features
### Core Capabilities
- **Real-time Face Detection** - MediaPipe-based face detection and mesh extraction
- **Biometric Template Generation** - Structured face descriptors and metadata
- **Fuzzy Biometric Hashing** - Locality-sensitive hashing for similarity matching
- **Liveness Detection** - Multi-frame analysis to prevent spoofing attacks
- **Privacy-Preserving** - No server-side biometric storage, client-side only
### Production Features
- **TypeScript Support** - Full type definitions and IntelliSense
- **Cross-Platform** - Browser and Node.js compatibility
- **Performance Optimized** - WebGL/WASM backend support, 30+ FPS
- **Memory Efficient** - Automatic tensor cleanup and garbage collection
- **Error Handling** - Comprehensive error recovery and validation
- **Event-Driven** - Real-time progress and completion events
### Security & Privacy
- ✅ **Zero Server Storage** - All processing happens locally
- ✅ **Fuzzy Tolerance** - Handles lighting, angle, and expression variations
- ✅ **Deterministic Hashing** - Same face always produces similar hashes
- ✅ **Configurable Security** - Adjustable similarity thresholds
- ✅ **GDPR Compliant** - Privacy by design architecture
## Installation
```bash
npm install facezk-core
```
## Quick Start
### Basic Usage
```typescript
import { FaceZK, HumanIntegration } from 'facezk-core';
// Initialize FaceZK
const facezk = new FaceZK({
backend: 'webgl',
debug: false,
minConfidence: 0.5,
minLivenessScore: 0.8,
});
await facezk.initialize();
// Start verification session
const session = facezk.startSession();
// Process video frame
const video = document.getElementById('video');
const result = await facezk.processFrame(video);
if (result?.verified) {
console.log('✅ Verification successful!');
console.log('Biometric ID:', result.biometricId);
console.log('Humanity Code:', result.humanityCode);
}
```
### Fuzzy Biometric Verification
```typescript
import { generateFuzzyHash, compareFuzzyHashes, defaultFuzzyConfig } from 'facezk-core';
// Generate fuzzy hash for storage
const template = await facezk.extractTemplate(faceResult);
const fuzzyHash = generateFuzzyHash(template, defaultFuzzyConfig);
// Store locally (never on server!)
localStorage.setItem('userBiometricHash', fuzzyHash.hash);
// Later verification
const newTemplate = await facezk.extractTemplate(newFaceResult);
const newHash = generateFuzzyHash(newTemplate, defaultFuzzyConfig);
const comparison = compareFuzzyHashes(fuzzyHash, newHash, defaultFuzzyConfig);
if (comparison.match) {
console.log(`✅ Same person! Similarity: ${comparison.similarity * 100}%`);
} else {
console.log(`❌ Different person. Similarity: ${comparison.similarity * 100}%`);
}
```
### Advanced Configuration
```typescript
const config = {
// Performance
backend: 'webgl', // 'webgl', 'wasm', 'cpu'
async: true,
// Detection
minConfidence: 0.7,
maxDetected: 1,
// Liveness
minLivenessScore: 0.85,
livenessFrames: 10,
// Fuzzy Hashing
fuzzyConfig: {
hashBits: 256,
similarityThreshold: 0.85,
normalization: 'l2',
},
// Features
face: {
detector: { enabled: true, rotation: true },
mesh: { enabled: true },
iris: { enabled: true },
emotion: { enabled: true },
ageGender: { enabled: true },
antispoof: { enabled: true },
},
};
const facezk = new FaceZK(config);
```
## API Reference
### Core Classes
#### `FaceZK`
Main library class for face verification.
```typescript
class FaceZK {
constructor(config?: Partial<FaceZKConfig>);
// Initialization
initialize(): Promise<void>;
// Session management
startSession(sessionId?: string): VerificationSession;
resetSession(): void;
// Processing
processFrame(input: Input): Promise<HumanityResult | null>;
// Events
addEventListener(event: VerificationEvent, listener: VerificationEventListener): void;
removeEventListener(event: VerificationEvent, listener: VerificationEventListener): void;
}
```
#### `HumanIntegration`
Integration with Human library for face detection.
```typescript
class HumanIntegration {
constructor(config: HumanIntegrationConfig);
// Initialization
initialize(): Promise<void>;
dispose(): void;
// Detection
detectFaces(input: Input): Promise<FaceResult[]>;
// Utilities
convertToBiometricTemplate(faceResult: FaceResult): BiometricTemplate;
drawOverlay(ctx: CanvasRenderingContext2D, faceResult: FaceResult): void;
}
```
### Fuzzy Hashing
#### `generateFuzzyHash(template, config?)`
Generate fuzzy-tolerant biometric hash.
```typescript
function generateFuzzyHash(
template: BiometricTemplate,
config?: FuzzyHashConfig
): FuzzyHashResult;
```
#### `compareFuzzyHashes(hash1, hash2, config?)`
Compare two fuzzy hashes for similarity.
```typescript
function compareFuzzyHashes(
hash1: FuzzyHashResult,
hash2: FuzzyHashResult,
config?: FuzzyHashConfig
): { similarity: number; match: boolean };
```
## Demo
Try the interactive demo to see FaceZK in action:
```bash
npm run demo
```
Then visit: http://localhost:3030/demo/
Features:
- Real-time face detection and analysis
- Fuzzy hash generation and comparison
- Performance monitoring
- Debug information panel
## Testing
```bash
# Run all tests
npm test
# Run tests with coverage
npm run test:ci
# Watch mode for development
npm run test:watch
```
## Performance
### Benchmarks
- **Detection Speed**: 30+ FPS on modern devices
- **Memory Usage**: <100MB for typical usage
- **Hash Generation**: ~5-10ms per template
- **Hash Comparison**: ~1-2ms per comparison
- **Accuracy**: 95%+ for same person, <5% false positives
### Browser Support
- ✅ Chrome 88+
- ✅ Firefox 85+
- ✅ Safari 14+
- ✅ Edge 88+
## Security
### Privacy Features
- **Local Processing** - No biometric data leaves the device
- **Fuzzy Hashing** - Prevents reverse engineering of face data
- **Deterministic** - Same face produces consistent hashes
- **Configurable** - Adjustable security thresholds
### Best Practices
1. **Always use HTTPS** in production
2. **Validate inputs** before processing
3. **Keep library updated** to latest version
4. **Use secure storage** for biometric hashes
5. **Test with diverse samples** for your use case
## Contributing
We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.
### Development Setup
```bash
# Clone repository
git clone https://github.com/VerifiedOnchain/facezk-lib.git
cd facezk-lib
# Install dependencies
npm install
# Build library
npm run build
# Run tests
npm test
# Start demo
npm run demo
```
## License
MIT License - see [LICENSE](LICENSE) for details.
## Support
- **Documentation**: [https://facezk.com/docs](https://facezk.com/docs)
- **Issues**: [GitHub Issues](https://github.com/VerifiedOnchain/facezk-lib/issues)
- **Security**: [security@facezk.com](mailto:security@facezk.com)
- **General**: [team@facezk.com](mailto:team@facezk.com)
## Acknowledgments
- [Human Library](https://github.com/vladmandic/human) - Face detection and analysis
- [TensorFlow.js](https://tensorflow.org/js) - Machine learning framework
- [MediaPipe](https://mediapipe.dev) - Face mesh and landmarks
---
**Made with ❤️ by the VerifiedOnchain Team**