usiv-validator-sdk
v2.1.2
Published
SDK for USIV identity validation system - Liveness detection, ID scanning, and face comparison
Downloads
454
Maintainers
Readme
USIV Validator SDK
A comprehensive TypeScript SDK for identity validation with Firebase authentication, webview integration, and role-based access control. Designed for Chilean RUT validation, email verification, and complete identity document processing including liveness detection, OCR, and face recognition.
🚀 What's New in v2.1.1
✨ Webview Integration
- Generic Webview Interface: Seamless communication between native SDK and webview contexts
- Automatic Token Management: Firebase tokens are automatically refreshed and managed
- Bidirectional Messaging: Robust postMessage-based communication system
- Mobile-Ready: Perfect for iOS/Android applications with webview components
🔑 Enhanced Token Management
- Automatic Token Refresh: Tokens are renewed before expiration automatically
- Token Lifecycle Management: Complete handling of Firebase authentication tokens
- Debug Information: Detailed token status and debugging capabilities
- Event Listeners: Subscribe to token changes and authentication events
📋 Features
Core Validation Features
- 🇨🇱 RUT Validation: Complete validation for Chilean RUT numbers with format checking and verification digit validation
- 📧 Email Validation: Robust email address validation with multiple verification methods
- 📱 ID Document Processing: OCR, MRZ validation, and document verification
- 🤳 Liveness Detection: Advanced biometric liveness detection
- 👤 Face Recognition: Face comparison and matching capabilities
Authentication & Security
- 🔐 Firebase Authentication: Secure authentication with email/password, custom tokens, and anonymous auth
- 🎭 Role-Based Access Control: Three-tier system (user, admin, enterprise) with granular permissions
- 🔑 API Key Management: Secure API key generation and validation for server-side usage
- ⏱️ Rate Limiting: Configurable rate limits by subscription tier (Basic: 100/hr, Premium: 500/hr, Enterprise: 2000/hr)
Developer Experience
- 📡 Event-Driven Architecture: Comprehensive event system for tracking validation activities
- 📝 TypeScript Support: Full TypeScript definitions and type safety
- 🐛 Comprehensive Error Handling: Detailed error codes and meaningful error messages
- 📱 Webview Integration: Generic interface for mobile webview implementations
📦 Installation
npm install usiv-validator-sdk🎯 Quick Start
1. Basic Usage (Without Authentication)
import { UsivValidator } from 'usiv-validator-sdk';
// Initialize the validator
const validator = new UsivValidator();
// Validate a RUT
const rutResult = await validator.validateRUT('12.345.678-9');
console.log(rutResult);
// { isValid: true, formatted: '12.345.678-9', type: 'rut' }
// Validate an email
const emailResult = await validator.validateEmail('[email protected]');
console.log(emailResult);
// { isValid: true, formatted: '[email protected]', type: 'email' }2. Authentication Setup
import { AuthManager, UsivValidator } from 'usiv-validator-sdk';
// Configure Firebase
const firebaseConfig = {
apiKey: 'your-api-key',
authDomain: 'your-project.firebaseapp.com',
projectId: 'your-project-id',
storageBucket: 'your-project.appspot.com',
messagingSenderId: 'your-sender-id',
appId: 'your-app-id'
};
// Configure access control
const accessConfig = {
allowAnonymous: false,
requiredRoles: ['user', 'admin'],
requiredPermissions: ['validate_identity'],
rateLimit: {
maxRequests: 100,
windowMs: 3600000 // 1 hour
}
};
// Initialize AuthManager with TokenManager
const authManager = new AuthManager(firebaseConfig, accessConfig, {
refreshThreshold: 5 * 60 * 1000, // 5 minutes
enableDebug: true,
forceRefresh: false
});
// Initialize validator with authentication
const validator = new UsivValidator(sdkConfig, authManager);
// Sign in
await authManager.signInWithEmail('[email protected]', 'password');
// Get token (automatically managed)
const token = await authManager.getIdToken();
console.log('Token:', token);3. Webview Integration (Mobile Applications)
Setup in Native Context (iOS/Android)
// webview-integration.js - Runs in native WebView context
import { AuthManager, UsivValidator, WebviewInterface } from 'usiv-validator-sdk';
const authManager = new AuthManager(firebaseConfig, accessConfig, {
refreshThreshold: 5 * 60 * 1000, // 5 minutes
enableDebug: true,
forceRefresh: false
});
const validator = new UsivValidator(sdkConfig, authManager);
const webviewInterface = new WebviewInterface(authManager, validator, {
allowedOrigin: '*', // Specify exact origin in production
enableLogging: true,
responseTimeout: 30000
});
// Listen for token changes
authManager.addTokenListener((token) => {
console.log('Token updated:', token ? 'Available' : 'Cleared');
});
// Initialize when DOM is ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initializeWebviewSDK);
} else {
initializeWebviewSDK();
}Webview Communication (From your webview)
// From your webview HTML/JS
class USIVWebviewClient {
constructor() {
this.pendingMessages = new Map();
this.setupMessageListener();
}
// Send message to SDK
async sendMessage(action, payload = {}) {
return new Promise((resolve, reject) => {
const messageId = `msg_${Date.now()}_${Math.random()}`;
const timeout = setTimeout(() => {
this.pendingMessages.delete(messageId);
reject(new Error(`Timeout waiting for response: ${action}`));
}, 30000);
this.pendingMessages.set(messageId, { resolve, reject, timeout });
window.parent.postMessage({
id: messageId,
action,
payload,
timestamp: Date.now()
}, '*');
});
}
// Listen for responses
setupMessageListener() {
window.addEventListener('message', (event) => {
const message = event.data;
if (message.id && this.pendingMessages.has(message.id)) {
const pending = this.pendingMessages.get(message.id);
this.pendingMessages.delete(message.id);
clearTimeout(pending.timeout);
if (message.success) {
pending.resolve(message.data);
} else {
pending.reject(new Error(message.error));
}
}
});
}
// Get authentication token
async getToken(includeInfo = false) {
return this.sendMessage('getToken', { includeTokenInfo: includeInfo });
}
// Check authentication status
async checkAuth() {
return this.sendMessage('checkAuth');
}
// Start validation process
async startValidation(rut, config = {}) {
return this.sendMessage('startValidation', {
validationId: `val_${Date.now()}`,
rut,
config
});
}
}
// Usage
const client = new USIVWebviewClient();
// Get token
try {
const tokenData = await client.getToken(true);
console.log('Token:', tokenData.token);
console.log('Expires:', new Date(tokenData.tokenInfo.expirationTime));
} catch (error) {
console.error('Error getting token:', error);
}
// Check authentication
try {
const authStatus = await client.checkAuth();
console.log('Authenticated:', authStatus.authenticated);
if (authStatus.user) {
console.log('User:', authStatus.user.email);
}
} catch (error) {
console.error('Error checking auth:', error);
}4. Complete Identity Validation Workflow
import { UsivValidator } from 'usiv-validator-sdk';
// Initialize with authentication
const validator = new UsivValidator({
apiBaseUrl: 'https://api.usiv.cl',
region: 'us-east-1',
minLivenessScore: 0.8,
similarityThreshold: 0.85,
enableDebug: true,
timeout: 30000
}, authManager);
// Complete validation workflow
async function validateIdentity() {
try {
// Step 1: Liveness detection
console.log('Starting liveness detection...');
const livenessResult = await validator.startLivenessDetection();
// Step 2: Document scanning
console.log('Scanning ID document...');
const frontResult = await validator.scanDocument('front');
const backResult = await validator.scanDocument('back');
// Step 3: Face comparison
console.log('Comparing faces...');
const faceResult = await validator.compareFaces(
livenessResult.referenceImage,
frontResult.faceImage
);
// Step 4: RUT validation
console.log('Validating RUT...');
const rutResult = await validator.validateRUT(frontResult.extractedRUT);
// Step 5: Complete validation
const finalResult = await validator.completeValidation({
liveness: livenessResult,
documents: { front: frontResult, back: backResult },
faceComparison: faceResult,
rutValidation: rutResult
});
console.log('Validation completed:', finalResult);
return finalResult;
} catch (error) {
console.error('Validation failed:', error);
throw error;
}
}📡 Event Handling
// Listen for validation events
validator.on('validationStarted', (data) => {
console.log('Validation started:', data.validationId);
});
validator.on('validationCompleted', (result) => {
console.log('Validation successful:', result.success);
console.log('Score:', result.confidenceScore);
});
validator.on('validationFailed', (error) => {
console.log('Validation failed:', error.message);
console.log('Step:', error.step);
});
validator.on('auth:login', (user) => {
console.log('User logged in:', user.email);
console.log('Role:', user.customClaims?.role);
});
validator.on('auth:logout', () => {
console.log('User logged out');
});
validator.on('token:refreshed', (token) => {
console.log('Token refreshed successfully');
});
validator.on('rateLimit:exceeded', (data) => {
console.log('Rate limit exceeded:', data);
});🔧 Configuration Options
SDK Configuration
const sdkConfig = {
// API Configuration
apiBaseUrl: 'https://api.usiv.cl',
region: 'us-east-1',
// Validation Thresholds
minLivenessScore: 0.8,
similarityThreshold: 0.85,
// Performance
timeout: 30000,
enableDebug: true,
// Firebase (optional)
firebase: firebaseConfig,
// Custom headers
customHeaders: {
'X-Custom-Header': 'value'
},
// Retry configuration
retryAttempts: 3,
retryDelay: 1000
};Token Manager Configuration
const tokenManagerConfig = {
// Refresh token 5 minutes before expiration
refreshThreshold: 5 * 60 * 1000,
// Enable debug logging
enableDebug: true,
// Force token refresh on every request
forceRefresh: false
};Webview Interface Configuration
const webviewConfig = {
// Allowed origin for webview messages
allowedOrigin: 'https://your-app.com',
// Enable message logging
enableLogging: true,
// Response timeout in milliseconds
responseTimeout: 30000
};🚨 Error Handling
import { ERROR_CODES } from 'usiv-validator-sdk';
try {
await validator.validateRUT('invalid-rut');
} catch (error) {
switch (error.code) {
case ERROR_CODES.INVALID_RUT_FORMAT:
console.log('Invalid RUT format');
break;
case ERROR_CODES.INVALID_VERIFICATION_DIGIT:
console.log('Invalid verification digit');
break;
case ERROR_CODES.RATE_LIMIT_EXCEEDED:
console.log('Rate limit exceeded, try again later');
break;
case ERROR_CODES.AUTHENTICATION_ERROR:
console.log('Authentication required');
break;
case ERROR_CODES.TOKEN_EXPIRED:
console.log('Token expired, re-authentication required');
break;
case ERROR_CODES.INSUFFICIENT_PERMISSIONS:
console.log('Insufficient permissions for this operation');
break;
default:
console.log('Unknown error:', error.message);
}
}📊 Subscription Tiers
Basic Tier (Anonymous Users)
- Rate Limit: 100 validations/hour
- Features: Basic RUT and email validation
- Cost: Free
Premium Tier (Authenticated Users)
- Rate Limit: 500 validations/hour
- Features: All validation features, usage statistics, event tracking
- Cost: Subscription required
Enterprise Tier (Admin/Enterprise Users)
- Rate Limit: 2000 validations/hour
- Features: All features plus user management, custom configurations, priority support
- Cost: Enterprise subscription required
🔗 API Reference
Core Classes
UsivValidator
Main validation class for identity verification.
class UsivValidator {
// Validation methods
validateRUT(rut: string): Promise<ValidationResult>
validateEmail(email: string): Promise<ValidationResult>
startLivenessDetection(): Promise<LivenessResult>
scanDocument(side: 'front' | 'back'): Promise<ScanResult>
compareFaces(image1: string, image2: string): Promise<FaceComparisonResult>
completeValidation(data: ValidationData): Promise<FinalResult>
// Authentication
signInWithEmail(email: string, password: string): Promise<User>
signInWithCustomToken(token: string): Promise<User>
signInAnonymously(): Promise<User>
signOut(): Promise<void>
// Token management
getIdToken(): Promise<string | null>
getTokenResult(): Promise<TokenResult | null>
forceRefreshToken(): Promise<TokenResult | null>
// Event handling
on(event: string, callback: Function): void
off(event: string, callback: Function): void
// Properties
currentUser: User | null
isAuthenticated: boolean
config: SdkConfig
}AuthManager
Authentication and authorization management.
class AuthManager {
constructor(firebaseConfig: FirebaseConfig, accessConfig: SDKAccessConfig, tokenManagerConfig: TokenManagerConfig)
// Authentication methods
signInWithEmail(email: string, password: string): Promise<UsivUser>
signInWithCustomToken(token: string): Promise<UsivUser>
createUser(email: string, password: string, additionalData?: Record<string, any>): Promise<UsivUser>
signOut(): Promise<void>
// Token management
getIdToken(): Promise<string | null>
getTokenResult(): Promise<TokenResult | null>
forceRefreshToken(): Promise<TokenResult | null>
isTokenValid(): Promise<boolean>
addTokenListener(listener: (token: string) => void): () => void
// Access control
checkAccess(): Promise<boolean>
getUsageStats(): Promise<UsageStats>
requestApiKey(name?: string): Promise<string>
validateApiKey(apiKey: string): Promise<boolean>
// Properties
currentUser: UsivUser | null
isAuthenticated: boolean
tokenManagerInstance: TokenManager
}TokenManager
Firebase token lifecycle management.
class TokenManager {
constructor(auth: Auth, config?: TokenManagerConfig)
// Token operations
getValidToken(): Promise<TokenResult>
getCurrentToken(): FirebaseToken | null
forceRefresh(): Promise<TokenResult>
isAuthenticated(): Promise<boolean>
clearToken(): void
// Information
getTokenDebugInfo(): Promise<TokenDebugInfo>
addTokenListener(listener: (token: string) => void): () => void
}WebviewInterface
Communication interface for webview environments.
class WebviewInterface {
constructor(authManager: AuthManager, validator: UsivValidator, config?: WebviewConfig)
// Communication
sendToWebview(action: string, data?: any): Promise<WebviewResponse>
// SDK operations
getToken(request?: WebviewTokenRequest): Promise<TokenResult | string>
checkAuthentication(): Promise<AuthStatus>
startValidation(request?: WebviewValidationRequest): Promise<ValidationStartResult>
}📁 Examples
Check the examples directory for complete usage examples:
- Authentication Examples - All authentication methods with token management
- Basic Validation - Simple validation without authentication
- Advanced Usage - Event handling and user management
- Server-Side Usage - API key authentication for servers
- Webview Integration - Complete SDK setup for mobile webview
- Webview Example - Full webview implementation with UI
🛠️ Firebase Setup Guide
For detailed Firebase setup instructions, see Firebase Setup Guide.
Quick Firebase Setup
Install Firebase CLI:
npm install -g firebase-toolsInitialize Firebase:
firebase initDeploy Cloud Functions:
cd firebase-functions npm install firebase deploy --only functionsDeploy Firestore Rules:
firebase deploy --only firestore:rules
🤝 Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Run the test suite
- Submit a pull request
📄 License
MIT License - see LICENSE file for details.
🆘 Support
For support and questions:
- Create an issue on GitHub
- Check the documentation
- Contact: [email protected]
📈 Changelog
v2.1.2
- ✅ ENHANCED: Complete README documentation with comprehensive usage examples
- ✅ ADDED: Detailed webview integration guide with complete code examples
- ✅ IMPROVED: Quick start guides for different use cases
- ✅ ADDED: Complete API reference with TypeScript signatures
v2.1.1
- ✅ FIXED: Token manager encoding issues for build compatibility
- ✅ ADDED: Complete webview integration examples
- ✅ IMPROVED: Documentation with comprehensive examples
v2.1.0
- ✨ NEW: TokenManager for automatic Firebase token lifecycle management
- ✨ NEW: WebviewInterface for generic SDK-webview communication
- ✨ NEW: Automatic token refresh and expiration handling
- ✨ NEW: Bidirectional messaging system for webview environments
- ✨ NEW: Comprehensive webview integration examples
- ✨ ENHANCED: Authentication system with token-based authorization
v2.0.0
- 🔐 NEW: Firebase authentication system
- 🎭 NEW: Role-based access control
- 🔑 NEW: API key management for server-side usage
- ⏱️ NEW: Rate limiting by subscription tiers
- 📡 NEW: Comprehensive event system
- 🐛 NEW: Enhanced error handling with specific error codes
- 📝 NEW: TypeScript support
- ☁️ NEW: Firebase Cloud Functions for authentication
- 🔥 NEW: Firestore security rules
v1.0.0
- 🎯 INITIAL: Basic RUT and email validation
