Package Exports
- @udene/sdk
- @udene/sdk/dist/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@udene/sdk) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
@udene/sdk
A comprehensive fraud detection and security package for JavaScript applications.
Installation
npm install @udene/sdk
# or
yarn add @udene/sdkUsage
Basic Initialization
// ES Modules
import { UdeneClient } from '@udene/sdk';
// CommonJS
// const { UdeneClient } = require('@udene/sdk');
// Initialize with API key
const client = new UdeneClient('your_api_key');
// Or initialize with configuration object
const client = new UdeneClient({
apiKey: 'your_api_key',
baseURL: 'https://api.udene.net/v1', // Optional custom API URL
maxRetries: 5, // Optional retry count (default: 3)
disableLogging: false, // Optional logging flag
logger: (message, error) => { // Optional custom logger
console.warn(`Custom log: ${message}`, error);
}
});Fraud Metrics
Get real-time fraud metrics for your application:
async function getFraudMetrics() {
try {
const metrics = await client.getMetrics();
console.log(`Current risk score: ${metrics.riskScore}`);
console.log(`Active users: ${metrics.activeUsers}`);
console.log(`Alert count: ${metrics.alertCount}`);
console.log(`Model accuracy: ${metrics.accuracy}%`);
// Use metrics to update your dashboard or trigger alerts
if (metrics.riskScore > 75) {
triggerHighRiskAlert();
}
return metrics;
} catch (error) {
console.error('Failed to fetch metrics:', error);
}
}Track User Interactions
Monitor user behavior for suspicious patterns:
async function trackUserLogin(userId, ipAddress, deviceInfo) {
try {
const result = await client.trackInteraction({
userId: userId,
action: 'login',
metadata: {
ipAddress: ipAddress,
deviceId: deviceInfo.id,
browser: deviceInfo.browser,
location: deviceInfo.location,
timestamp: new Date().toISOString()
}
});
console.log(`Interaction tracked with ID: ${result.transactionId}`);
return result;
} catch (error) {
console.error('Failed to track interaction:', error);
// Handle validation errors
if (error.message.includes('Invalid input')) {
// Show appropriate error to user
}
}
}Analyze Transactions
Detect fraudulent transactions in real-time:
async function processPayment(userId, paymentDetails) {
try {
// First analyze the transaction for fraud
const analysis = await client.analyzeTransaction({
transactionId: paymentDetails.id,
userId: userId,
amount: paymentDetails.amount,
currency: paymentDetails.currency,
paymentMethod: paymentDetails.method,
timestamp: new Date().toISOString(),
metadata: {
productIds: paymentDetails.items.map(item => item.id),
shippingAddress: paymentDetails.shippingAddress,
billingAddress: paymentDetails.billingAddress,
isRecurring: paymentDetails.isSubscription
}
});
// Handle the result based on risk assessment
switch (analysis.recommendation) {
case 'approve':
return processApprovedPayment(paymentDetails);
case 'review':
flagForManualReview(paymentDetails, analysis.reasons);
return {
status: 'pending_review',
message: 'Your payment is being reviewed for security purposes.'
};
case 'deny':
logRejectedPayment(paymentDetails, analysis.reasons);
return {
status: 'rejected',
message: 'Payment could not be processed. Please contact support.'
};
}
} catch (error) {
console.error('Transaction analysis failed:', error);
throw new Error('Payment processing failed. Please try again.');
}
}Device Fingerprinting
Identify suspicious devices and prevent account takeovers:
async function checkDeviceTrust() {
try {
const deviceInfo = await client.getDeviceFingerprint();
// Log device information
console.log(`Device ID: ${deviceInfo.deviceId}`);
console.log(`Browser: ${deviceInfo.browser}`);
console.log(`OS: ${deviceInfo.os}`);
console.log(`Trust score: ${deviceInfo.trustScore}`);
// Take action based on trust score
if (deviceInfo.trustScore < 30) {
// High risk device - require additional verification
return {
requiresVerification: true,
riskFactors: deviceInfo.riskFactors
};
}
return {
requiresVerification: false
};
} catch (error) {
console.error('Failed to get device fingerprint:', error);
// Fail open or closed depending on your security posture
return { requiresVerification: true, error: true };
}
}Activity Monitoring
Monitor suspicious activities across your platform:
async function monitorActivity() {
try {
const activityData = await client.getActivity();
// Process suspicious activities
const suspiciousActivities = activityData.activities.filter(
activity => activity.type === 'suspicious'
);
if (suspiciousActivities.length > 0) {
console.warn(`Found ${suspiciousActivities.length} suspicious activities`);
// Take action on suspicious activities
suspiciousActivities.forEach(activity => {
logSecurityEvent({
id: activity.id,
description: activity.description,
timestamp: activity.timestamp
});
});
}
return activityData;
} catch (error) {
console.error('Failed to fetch activity data:', error);
}
}React Integration Example
import React, { useEffect, useState } from 'react';
import { UdeneClient } from '@udene/sdk';
// Initialize the client outside component to avoid recreation on renders
const fraudClient = new UdeneClient('your_api_key');
function PaymentForm({ userId, amount, onComplete }) {
const [isProcessing, setIsProcessing] = useState(false);
const [error, setError] = useState(null);
const [requiresVerification, setRequiresVerification] = useState(false);
// Check device trust on component mount
useEffect(() => {
async function checkDevice() {
try {
const deviceCheck = await fraudClient.getDeviceFingerprint();
if (deviceCheck.trustScore < 40) {
setRequiresVerification(true);
}
// Track page view
await fraudClient.trackInteraction({
userId,
action: 'payment_page_view',
metadata: { amount }
});
} catch (err) {
console.error('Device check failed:', err);
}
}
checkDevice();
}, [userId, amount]);
const handleSubmit = async (e) => {
e.preventDefault();
setIsProcessing(true);
setError(null);
try {
// Get form data
const formData = new FormData(e.target);
const paymentMethod = formData.get('payment_method');
// Generate transaction ID
const transactionId = `txn_${Date.now()}`;
// Analyze transaction
const analysis = await fraudClient.analyzeTransaction({
transactionId,
userId,
amount: parseFloat(amount),
currency: 'USD',
paymentMethod,
timestamp: new Date().toISOString()
});
if (analysis.recommendation === 'approve') {
// Process payment
onComplete({ success: true, transactionId });
} else if (analysis.recommendation === 'review') {
setRequiresVerification(true);
setError('Additional verification required for this transaction.');
} else {
setError('This transaction cannot be processed. Please contact support.');
}
} catch (err) {
setError('Payment processing failed. Please try again.');
console.error('Payment error:', err);
} finally {
setIsProcessing(false);
}
};
return (
<div className="payment-form">
{requiresVerification && (
<div className="verification-notice">
For security reasons, additional verification is required.
<button onClick={() => /* Show verification UI */ null}>
Verify Identity
</button>
</div>
)}
<form onSubmit={handleSubmit}>
{/* Payment form fields */}
<select name="payment_method">
<option value="credit_card">Credit Card</option>
<option value="paypal">PayPal</option>
</select>
<button type="submit" disabled={isProcessing}>
{isProcessing ? 'Processing...' : `Pay $${amount}`}
</button>
{error && <div className="error-message">{error}</div>}
</form>
</div>
);
}API Reference
UdeneClient
The main client for accessing fraud detection services.
Constructor
new UdeneClient(apiKeyOrConfig, baseURL)apiKeyOrConfig(required) - Your API key as a string, or a configuration objectbaseURL(optional) - Custom API base URL if needed (ignored if config object is provided)
Configuration Object Properties:
{
apiKey: 'your_api_key', // Required
baseURL: 'https://api.example.com', // Optional
maxRetries: 3, // Optional (default: 3)
disableLogging: false, // Optional (default: false)
logger: function(message, error) {} // Optional custom logger
}Methods
| Method | Description | Parameters | Return Type |
|---|---|---|---|
getMetrics() |
Get fraud metrics for the current user/session | None | Promise<MetricsResponse> |
getActivity() |
Get activity data for analysis | None | Promise<ActivityResponse> |
trackInteraction(data) |
Track a user interaction for fraud analysis | TrackInteractionRequest | Promise<TrackInteractionResponse> |
analyzeTransaction(transaction) |
Analyze a transaction for fraud | TransactionAnalysisRequest | Promise<TransactionAnalysisResponse> |
getDeviceFingerprint() |
Get device fingerprint information | None | Promise<DeviceFingerprintResponse> |
Type Definitions
// For TypeScript users, these interfaces are exported from the package
interface MetricsResponse {
riskScore: number;
activeUsers: number;
alertCount: number;
apiCalls: number;
accuracy: number;
falsePositiveRate: number;
avgProcessingTime: number;
concurrentCalls: number;
}
interface ActivityItem {
id: string;
type: 'suspicious' | 'normal';
description: string;
timestamp: string;
}
interface ActivityResponse {
activities: ActivityItem[];
}
interface TrackInteractionRequest {
userId: string;
action: string;
metadata?: Record<string, any>;
}
interface TrackInteractionResponse {
success: boolean;
transactionId: string;
}
interface TransactionAnalysisRequest {
transactionId: string;
userId: string;
amount?: number;
currency?: string;
paymentMethod?: string;
timestamp?: string;
metadata?: Record<string, any>;
}
interface TransactionAnalysisResponse {
riskScore: number;
recommendation: 'approve' | 'review' | 'deny';
reasons?: string[];
transactionId: string;
}
interface DeviceFingerprintResponse {
deviceId: string;
browser: string;
os: string;
ip: string;
location?: {
country?: string;
city?: string;
};
riskFactors?: string[];
trustScore?: number;
}Error Handling
The SDK includes built-in error handling with automatic retries for network issues and server errors (5xx). You can customize retry behavior and logging through the configuration options.
try {
const result = await client.analyzeTransaction(data);
} catch (error) {
// Handle specific error types
if (error.message.includes('Invalid input')) {
// Handle validation errors
} else if (error.response && error.response.status === 429) {
// Handle rate limiting
console.log('Too many requests, please try again later');
} else {
// Handle other errors
console.error('Transaction analysis failed:', error);
}
}Advanced Usage
Custom Retry Logic
The SDK automatically retries failed requests with exponential backoff for network errors and 5xx server responses. You can customize this behavior:
const client = new UdeneClient({
apiKey: 'your_api_key',
maxRetries: 5, // Increase from default of 3
logger: (message, error) => {
// Custom retry logging
if (message.includes('Retrying request')) {
console.warn(message);
} else {
console.error(message, error);
}
}
});Disable Logging
For production environments, you might want to disable the default console logging:
const client = new UdeneClient({
apiKey: 'your_api_key',
disableLogging: true
});License
MIT