credence-sdk
v0.1.0
Published
Official TypeScript/JavaScript SDK for the Credence API - Identity verification and trust scoring platform
Maintainers
Readme
Credence SDK
Official TypeScript/JavaScript SDK for the Credence API - Identity verification and trust scoring platform.
Features
- 🔐 Dual Authentication: Support for both server-side (API key) and client-side (JWT token) authentication
- 🌐 Universal: Works in both browser and Node.js environments
- 📱 Offline-First: Built-in offline queue with automatic sync when connection is restored
- ⚡ Real-time Events: WebSocket and Server-Sent Events support for live updates
- 🔄 Auto-Retry: Intelligent retry logic with exponential backoff for transient errors
- 🎯 TypeScript: Full type safety with comprehensive TypeScript definitions
- 🧪 Sandbox Mode: Built-in mock data for development and testing
- 📊 Trust Scoring: Advanced AI-powered fraud detection and trust scoring
- 🤖 AI-Enhanced: Optional Groq API integration for advanced fraud detection and behavioral analysis
- 🧠 Smart Insights: Real-time AI analysis of verification patterns and anomaly detection
- 🏘️ Community-First Verification: Revolutionary system that verifies identity through community trust networks
- 🛰️ Satellite Verification: Geospatial analysis for livelihood and location verification
- 🌾 Livelihood-Based Identity: Verify farmers, traders, and artisans through their economic activity
- 👥 Progressive Trust Building: Bronze, Silver, Gold trust levels with expanding service access
Installation
npm install credence-sdkyarn add credence-sdkpnpm add credence-sdkQuick Start
Server-side Usage (Node.js)
import { CredenceSDK } from 'credence-sdk';
// Initialize with API key for server-side operations
const credence = new CredenceSDK({
apiKey: 'your-api-key',
sandbox: true, // Use sandbox environment for testing
// AI Enhancement (optional)
ai: {
enabled: true,
groqApiKey: 'your-groq-api-key', // Get from https://console.groq.com
model: 'llama3-8b-8192' // Fast and accurate model
}
});
// Initialize a verification session
const verification = await credence.initVerification({
userId: 'user-123',
rulesProfile: 'banking',
callbackUrl: 'https://your-app.com/webhook'
});
console.log('Verification ID:', verification.id);
console.log('Client Token:', verification.clientToken);Client-side Usage (Browser)
import { CredenceSDK } from 'credence-sdk';
// Initialize with client token (obtained from your server)
const credence = new CredenceSDK({
clientToken: 'client-jwt-token-from-server',
sandbox: true
});
// Upload biometric data
const fileInput = document.getElementById('selfie') as HTMLInputElement;
const file = fileInput.files[0];
await credence.uploadBiometric(
'verification-id',
file,
'selfie',
{
userAgent: navigator.userAgent,
screenResolution: `${screen.width}x${screen.height}`,
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
language: navigator.language,
platform: navigator.platform
}
);Configuration Options
interface CredenceConfig {
// Authentication (choose one)
apiKey?: string; // For server-side operations
clientToken?: string; // For client-side operations
// Environment
baseUrl?: string; // Custom API base URL
sandbox?: boolean; // Use sandbox environment (default: false)
mock?: boolean; // Enable mock responses (default: false)
// Hooks for debugging and monitoring
onRequest?: (config: RequestConfig) => void | Promise<void>;
onResponse?: (response: Response) => void | Promise<void>;
onError?: (error: CredenceError) => void | Promise<void>;
}Environment URLs
- Production:
https://api.credence.xyz/v1 - Sandbox:
https://sandbox.api.credence.xyz/v1
API Methods
Verification Management
initVerification(payload) (Server-side only)
Initialize a new verification session.
const verification = await credence.initVerification({
userId: 'user-123',
rulesProfile: 'banking', // 'banking' | 'marketplace' | 'micro-lending'
metadata: {
customerType: 'premium',
riskLevel: 'low'
},
callbackUrl: 'https://your-app.com/webhook',
expiresAt: '2024-01-01T00:00:00Z'
});getVerificationStatus(id)
Get the current status of a verification.
const status = await credence.getVerificationStatus('verification-id');
console.log('Status:', status.status);
console.log('Completed steps:', status.completedSteps);
console.log('Trust score:', status.trustScore);searchVerifications(query) (Server-side only)
Search and filter verifications.
const results = await credence.searchVerifications({
userId: 'user-123',
status: 'completed',
createdAfter: '2023-01-01T00:00:00Z',
limit: 50,
offset: 0
});Biometric Verification
uploadBiometric(id, file, type, deviceFingerprint?, signedAttestation?)
Upload biometric data for verification.
// Browser example
const file = document.getElementById('selfie').files[0];
await credence.uploadBiometric(
'verification-id',
file,
'selfie', // 'selfie' | 'liveness' | 'voice' | 'fingerprint'
{
userAgent: navigator.userAgent,
screenResolution: `${screen.width}x${screen.height}`,
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
language: navigator.language,
platform: navigator.platform,
hardwareConcurrency: navigator.hardwareConcurrency,
deviceMemory: (navigator as any).deviceMemory,
colorDepth: screen.colorDepth,
pixelRatio: window.devicePixelRatio
}
);
// Node.js example
import fs from 'fs';
const imageBuffer = fs.readFileSync('selfie.jpg');
await credence.uploadBiometric('verification-id', imageBuffer, 'selfie');Device Fingerprinting
uploadDeviceFingerprint(id, payload)
Upload device fingerprint data.
await credence.uploadDeviceFingerprint('verification-id', {
userAgent: navigator.userAgent,
screenResolution: `${screen.width}x${screen.height}`,
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
language: navigator.language,
platform: navigator.platform,
hardwareConcurrency: navigator.hardwareConcurrency,
deviceMemory: (navigator as any).deviceMemory,
colorDepth: screen.colorDepth,
pixelRatio: window.devicePixelRatio,
touchSupport: 'ontouchstart' in window,
webglVendor: getWebGLVendor(),
webglRenderer: getWebGLRenderer(),
audioFingerprint: await generateAudioFingerprint(),
canvasFingerprint: generateCanvasFingerprint(),
fontsFingerprint: generateFontsFingerprint()
});Address Verification
uploadAddress(id, payloadOrFile)
Upload address verification document or extracted data.
// Upload document file
const file = document.getElementById('utility-bill').files[0];
await credence.uploadAddress('verification-id', {
type: 'utility_bill',
file: file
});
// Upload extracted data
await credence.uploadAddress('verification-id', {
type: 'utility_bill',
extractedData: {
fullName: 'John Doe',
address: '123 Main St',
city: 'New York',
state: 'NY',
postalCode: '10001',
country: 'US',
documentDate: '2023-12-01'
}
});Micro-Transaction Verification
initMicroTx(id, payload)
Initialize micro-transaction verification.
const microTx = await credence.initMicroTx('verification-id', {
walletAddress: '0x742d35Cc6634C0532925a3b8D4C9db96DfbBfC88',
blockchain: 'ethereum', // 'ethereum' | 'polygon' | 'bsc' | 'arbitrum'
amount: '1000000000000000' // Optional: amount in wei (default: 0.001 ETH)
});
console.log('Send', microTx.amount, 'wei to', microTx.toAddress);
console.log('Transaction ID:', microTx.txId);checkMicroTx(id, txId)
Check micro-transaction status.
const status = await credence.checkMicroTx('verification-id', 'tx-id');
console.log('Status:', status.status);
console.log('Transaction Hash:', status.transactionHash);
console.log('Confirmations:', status.confirmations);Trust Scoring
getTrustScore(id)
Get AI-powered trust score and factors.
const trustScore = await credence.getTrustScore('verification-id');
console.log('Score:', trustScore.score);
console.log('Factors:', trustScore.factors);
trustScore.factors.forEach(factor => {
console.log(`${factor.type}: ${factor.value} (weight: ${factor.weight})`);
console.log(`Description: ${factor.description}`);
});AI Insights (Optional)
getAIInsights(id)
Get AI-powered fraud detection insights.
const insights = await credence.getAIInsights('verification-id');
console.log('Risk Score:', insights.riskScore);
console.log('Confidence:', insights.confidence);
insights.fraudSignals.forEach(signal => {
console.log(`${signal.type} (${signal.severity}): ${signal.description}`);
});
console.log('Recommendations:', insights.recommendations);Offline-First Mode
The SDK includes built-in offline support for areas with poor connectivity.
Offline Capture Methods
// Capture data offline (stored in local queue)
await credence.captureSelfie(blob);
await credence.captureGPS(latitude, longitude);
await credence.captureDocs(file, 'passport');
// Sync when connection is restored
const result = await credence.sync();
console.log('Synced', result.synced, 'items');Manual Sync
// Get queued actions
const queue = await credence.offlineQueue.getQueuedActions();
console.log('Queued actions:', queue.length);
// Sync specific verification
await credence.syncOffline('verification-id', queue);
// Clear queue after successful sync
await credence.offlineQueue.clearQueue();Real-time Events
Subscribe to real-time updates via WebSocket or Server-Sent Events.
// Subscribe to verification updates
credence.subscribe('verification.updated', (event) => {
console.log('Verification updated:', event.data);
// Update UI with new status
});
// Subscribe to trust score updates
credence.subscribe('trustscore.updated', (event) => {
console.log('Trust score updated:', event.data);
// Update trust score display
});
// Unsubscribe
credence.unsubscribe('verification.updated');
// Check connection status
const status = credence.eventManager.getConnectionStatus();
console.log('Connected:', status.connected);
console.log('Connection type:', status.type); // 'websocket' | 'sse'Error Handling
The SDK provides comprehensive error handling with custom error types.
import { CredenceError, ERROR_CODES } from 'credence-sdk';
try {
await credence.getTrustScore('invalid-id');
} catch (error) {
if (error instanceof CredenceError) {
console.log('Error code:', error.code);
console.log('Status code:', error.statusCode);
console.log('Details:', error.details);
switch (error.code) {
case ERROR_CODES.VERIFICATION_NOT_FOUND:
// Handle not found
break;
case ERROR_CODES.RATE_LIMITED:
// Handle rate limiting
break;
case ERROR_CODES.UNAUTHORIZED:
// Handle auth error
break;
}
}
}Error Codes
Common error codes include:
INVALID_CONFIG- SDK configuration errorUNAUTHORIZED- Authentication failedFORBIDDEN- Insufficient permissionsVALIDATION_ERROR- Request validation failedVERIFICATION_NOT_FOUND- Verification ID not foundVERIFICATION_EXPIRED- Verification session expiredRATE_LIMITED- Rate limit exceededNETWORK_ERROR- Network connectivity issueINTERNAL_SERVER_ERROR- Server error
Retry Logic
The SDK automatically retries transient errors with exponential backoff:
import { RetryManager, DEFAULT_RETRY_OPTIONS } from 'credence-sdk';
// Custom retry configuration
const customRetryOptions = {
maxAttempts: 5,
baseDelay: 2000,
maxDelay: 30000,
backoffFactor: 2,
retryableErrors: [
ERROR_CODES.NETWORK_ERROR,
ERROR_CODES.RATE_LIMITED,
ERROR_CODES.INTERNAL_SERVER_ERROR
]
};
// Use with any async operation
const result = await RetryManager.withRetry(
() => credence.getTrustScore('verification-id'),
customRetryOptions
);AI-Enhanced Features
The Credence SDK supports optional AI enhancement through Groq API integration for advanced fraud detection and behavioral analysis.
Setup AI Integration
import { CredenceSDK } from 'credence-sdk';
const credence = new CredenceSDK({
apiKey: 'your-credence-api-key',
sandbox: true,
ai: {
enabled: true,
groqApiKey: 'your-groq-api-key', // Get from https://console.groq.com
model: 'llama3-8b-8192' // Fast model for real-time analysis
}
});AI-Powered Fraud Detection
// Get comprehensive AI fraud analysis
const insights = await credence.getAIInsights('verification-id');
console.log('AI Analysis Results:');
console.log(`Risk Score: ${insights.riskScore}/100`);
console.log(`Confidence: ${(insights.confidence * 100).toFixed(1)}%`);
insights.fraudSignals.forEach(signal => {
console.log(`${signal.type} (${signal.severity}): ${signal.description}`);
});
console.log('Recommendations:', insights.recommendations);Enhanced Trust Scoring
// AI-enhanced trust score calculation
const trustScore = await credence.getTrustScore('verification-id');
console.log(`Trust Score: ${trustScore.score}/100`);
trustScore.factors.forEach(factor => {
console.log(`${factor.type}: ${factor.score}/100 (weight: ${factor.weight})`);
});Behavioral Pattern Analysis
// Analyze user behavior for anomalies
const behavioral = await credence.analyzeBehavioralPatterns('verification-id');
console.log(`Anomaly Score: ${behavioral.anomalyScore}/100`);
console.log('Detected Patterns:', behavioral.patterns);
console.log(`Confidence: ${(behavioral.confidence * 100).toFixed(1)}%`);AI Models Available
- llama3-8b-8192: Fast, efficient model for real-time analysis
- llama3-70b-8192: More powerful model for complex risk assessment
- mixtral-8x7b-32768: Balanced performance for comprehensive analysis
Fallback Behavior
When AI is unavailable, the SDK automatically falls back to:
- Rule-based fraud detection
- Traditional trust scoring algorithms
- Server-side analysis endpoints
Community-First Verification
The revolutionary feature that verifies identity through community trust networks instead of government IDs.
The Problem We Solve
Traditional KYC excludes millions of people who lack:
- Government-issued IDs
- Formal addresses
- Bank account history
- Credit records
Our Solution: Community Trust Networks
Instead of asking "Do you have government ID?", we ask "Can your community vouch for you?"
Setup Community Verification
import { CredenceSDK } from 'credence-sdk';
const credence = new CredenceSDK({
apiKey: 'your-credence-api-key',
sandbox: true
});
// Step 1: Register a community
const community = await credence.registerCommunity({
name: 'Kura Farming Community',
type: 'village',
location: {
state: 'Kano',
lga: 'Kura',
coordinates: { latitude: 11.0041, longitude: 7.7829 }
},
trustAnchors: []
});
// Step 2: Verify community trust anchor (village head/chief)
const trustAnchor = await credence.verifyTrustAnchor({
userId: 'chief-kura-001',
role: 'traditional_ruler',
title: 'Village Head',
communityId: community.id,
verificationMethod: 'government_id'
});Community Member Verification
// Step 3: Submit verification request for community member
const verificationRequest = await credence.submitCommunityVerificationRequest({
userId: 'farmer-amina-001',
communityId: community.id,
requestType: 'new_member',
requestedLevel: 'bronze',
supportingData: {
personalInfo: {
fullName: 'Amina Ibrahim',
phoneNumber: '+2348123456789'
},
residenceInfo: {
address: 'Near the big baobab tree, Kura village',
duration: 60, // 5 years
landmarks: ['Baobab tree', 'Village well', 'Primary school']
},
livelihoodInfo: {
type: 'farming',
description: 'Rice and millet farming',
location: {
coordinates: { latitude: 11.0041, longitude: 7.7829 },
landmarks: ['River bend', 'Old mosque']
},
duration: 36, // 3 years farming
seasonalPatterns: {
busyMonths: [5, 6, 7, 10, 11],
slowMonths: [12, 1, 2, 3],
peakActivity: 'Rice harvest in November'
}
}
},
requestedAttestations: [
{
attesterId: 'chief-kura-001',
relationship: 'community_member',
requestMessage: 'Village head, please confirm you know Amina Ibrahim'
},
{
attesterId: 'neighbor-fatima-001',
relationship: 'neighbor',
requestMessage: 'Fatima, please confirm I am your neighbor'
}
]
});Community Attestations
// Community members vouch for each other
const attestation = await credence.submitCommunityAttestation({
attesterId: 'chief-kura-001',
subjectId: 'farmer-amina-001',
communityId: community.id,
attestationType: 'identity',
relationship: 'community_member',
relationshipDuration: 60, // months
confidence: 'high',
details: {
howTheyKnow: 'She has lived in our village for 5 years',
howLongKnown: 60,
frequencyOfInteraction: 'monthly',
specificKnowledge: [
'Lives near the baobab tree',
'Married to Ibrahim the carpenter',
'Active in women farmers group'
]
}
});Livelihood Verification
// Verify livelihood through satellite imagery and economic activity
const livelihoodVerification = await credence.verifyLivelihood(
'farmer-amina-001',
{
type: 'farming',
description: 'Rice and millet farming',
location: {
coordinates: { latitude: 11.0041, longitude: 7.7829 },
landmarks: ['River bend', 'Old mosque']
},
duration: 36,
seasonalPatterns: {
busyMonths: [5, 6, 7, 10, 11],
slowMonths: [12, 1, 2, 3],
peakActivity: 'Rice harvest in November'
},
economicConnections: {
suppliers: ['Kano Seeds Cooperative'],
customers: ['Local rice mill'],
colleagues: ['Women farmers group'],
competitors: []
},
verificationEvidence: {
satelliteImagery: true,
marketPresence: true,
skillDemonstration: true,
economicActivity: true
}
}
);
console.log('Livelihood verified:', livelihoodVerification.verified);
console.log('Confidence:', livelihoodVerification.confidence);Satellite & Geospatial Verification
// Verify farming activity through satellite analysis
const farmingVerification = await credence.verifyFarmingActivity(
'farmer-amina-001',
{ latitude: 11.0041, longitude: 7.7829 },
'rice',
36 // months farming
);
// Verify market trader activity
const traderVerification = await credence.verifyMarketTraderActivity(
'trader-usman-001',
{ latitude: 11.0041, longitude: 7.7829, name: 'Kura Central Market' },
['monday', 'wednesday', 'friday'],
24 // months trading
);
// Generate location-based challenges
const locationChallenges = await credence.generateLocationChallenges(
{ latitude: 11.0041, longitude: 7.7829 },
'landmarks'
);Progressive Trust Levels
// Check user's trust level and progress
const trustLevel = await credence.getUserTrustLevel('farmer-amina-001');
console.log('Current Level:', trustLevel.currentLevel); // bronze, silver, gold
console.log('Progress:', trustLevel.progress);
console.log('Next Level Requirements:', trustLevel.nextLevelRequirements);
console.log('Estimated Time to Next Level:', trustLevel.estimatedTimeToNextLevel);Trust Level Benefits
Bronze Level (Basic Services)
- Basic savings account
- Small mobile money transactions
- Microinsurance enrollment
Silver Level (Expanded Services)
- Larger transaction limits
- Basic credit products
- Business account opening
- Remittance services
Gold Level (Full Services)
- Full banking services
- Investment products
- Business loans
- International transfers
Development and Testing
Sandbox Mode
Enable sandbox mode for development:
const credence = new CredenceSDK({
apiKey: 'your-sandbox-api-key',
sandbox: true,
mock: true // Enable mock responses for faster development
});Mock Mode
When mock: true is enabled, the SDK returns realistic mock data without making API calls:
const credence = new CredenceSDK({
apiKey: 'test-key',
sandbox: true,
mock: true
});
// Returns mock data instantly
const verification = await credence.initVerification({
userId: 'test-user'
});
// verification.id = 'mock-verification-1234567890'
// verification.clientToken = 'mock-client-token-abc123'Debugging
Use hooks to monitor SDK behavior:
const credence = new CredenceSDK({
apiKey: 'your-api-key',
onRequest: (config) => {
console.log('Request:', config.method, config.url);
},
onResponse: (response) => {
console.log('Response:', response.status, response.statusText);
},
onError: (error) => {
console.error('SDK Error:', error.code, error.message);
}
});TypeScript Support
The SDK is written in TypeScript and provides comprehensive type definitions:
import {
CredenceSDK,
CredenceConfig,
InitVerificationPayload,
VerificationStatus,
TrustScoreResponse,
BiometricType,
RulesProfile
} from 'credence-sdk';
// Full type safety
const config: CredenceConfig = {
apiKey: 'your-api-key',
sandbox: true
};
const sdk = new CredenceSDK(config);
// Typed responses
const verification: InitVerificationResponse = await sdk.initVerification({
userId: 'user-123',
rulesProfile: 'banking' as RulesProfile
});Browser Support
- Chrome 60+
- Firefox 55+
- Safari 12+
- Edge 79+
Node.js Support
- Node.js 16+
License
MIT License - see LICENSE file for details.
📚 Documentation
SDK Documentation
This README provides comprehensive SDK usage examples and configuration options.
API Documentation
Complete OpenAPI/Swagger documentation is available:
- Interactive API Docs: Open
docs/index.htmlin your browser - OpenAPI Spec:
docs/openapi.yaml- Complete API specification - Documentation Guide:
docs/README.md- Detailed API documentation
Viewing API Documentation
# Serve interactive documentation
npm run docs:serve
# Build static HTML documentation
npm run docs:build
# Validate API specification
npm run docs:validate
# Start mock API server for testing
npm run docs:mockThe API documentation includes:
- Complete endpoint reference with examples
- Authentication guides (API key + Bearer token)
- Request/response schemas with validation
- Real-time event streaming documentation
- Offline synchronization patterns
- AI insights and fraud detection endpoints
Support
- SDK Documentation: This README and inline code comments
- API Documentation:
docs/directory with OpenAPI specification - Live API Reference: https://api.credence.xyz/docs
- Developer Portal: https://docs.credence.xyz
- Support: [email protected]
- Issues: GitHub Issues
Contributing
We welcome contributions! Please see our Contributing Guide for details.
Made with ❤️ by the Credence team
