npm package: @powercred/liveguard-sdk
Description: PowerCred LiveGuard SDK - Offline passive liveness detection and face matching for JavaScript
Author: PowerCred
Latest version: 1.0.0

# 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.

[![npm version](https://img.shields.io/npm/v/@powercred/liveguard-sdk.svg)](https://www.npmjs.com/package/@powercred/liveguard-sdk)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/)

## ✨ 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

```bash
npm install @powercred/liveguard-sdk
```

### Basic Usage

```typescript
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)

```typescript
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.

```typescript
const sdk = new LiveGuardSDK(config?: LiveGuardConfig)
```

**Configuration Options:**
```typescript
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 models
- `extractIDFace(file: File): Promise<ProcessingResult<FaceData>>` - Extract face from ID card
- `analyzeSelfie(file: File): Promise<ProcessingResult<LivenessResult>>` - Analyze selfie for liveness
- `compareFaces(idFace: FaceData, selfieFace: FaceData): Promise<ProcessingResult<MatchResult>>` - Compare two faces
- `verifyIdentity(idFile: File, selfieFile: File): Promise<ProcessingResult<VerificationResult>>` - Complete verification workflow

### Result Types

#### `LivenessResult`
```typescript
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`
```typescript
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

```bash
npm install @powercred/liveguard-sdk
```

### 2. Download Model Files

The SDK requires pre-trained models. Download them from our releases:

```bash
# 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

```typescript
// 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

```javascript
// webpack.config.js
module.exports = {
  // ... other config
  module: {
    rules: [
      {
        test: /\.(bin|json)$/,
        type: 'asset/resource'
      }
    ]
  }
}
```

## 🎯 Advanced Usage

### Individual Component Usage

```typescript
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

```typescript
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

```typescript
// 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

```typescript
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

```typescript
// 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

```bash
# 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

```bash
npm test
```

### Browser Compatibility Test

```typescript
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

1. **Preload Models**: Use `preloadModels()` during app initialization
2. **Image Size**: Limit input images to 1024px max dimension
3. **Batch Processing**: Process multiple comparisons together
4. **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](CONTRIBUTING.md) for details.

### Development Setup

```bash
git clone https://github.com/powercred/liveguard-sdk.git
cd liveguard-sdk
npm install
npm run dev
```

## 📄 License

MIT License - see [LICENSE](LICENSE) file for details.

## 🆘 Support

- 📚 **Documentation**: [https://docs.powercred.com/liveguard](https://docs.powercred.com/liveguard)
- 🐛 **Issues**: [GitHub Issues](https://github.com/powercred/liveguard-sdk/issues)
- 💬 **Discussions**: [GitHub Discussions](https://github.com/powercred/liveguard-sdk/discussions)
- 📧 **Email**: support@powercred.com

## 🎉 Acknowledgments

Built with:
- [TensorFlow.js](https://www.tensorflow.org/js) - Machine Learning runtime
- [face-api.js](https://github.com/justadudewhohacks/face-api.js) - Face detection and recognition
- [Vite](https://vitejs.dev/) - Build tool and development server

---

**PowerCred LiveGuard SDK** - Secure, Fast, and Privacy-First Identity Verification 🛡️