@udene/react-native-sdk
Version:
Udene Fraud Detection SDK for React Native
229 lines (182 loc) • 7.1 kB
Markdown
# @udene/react-native-sdk
A comprehensive fraud detection and security package for React Native applications.
## Installation
```sh
npm install @udene/react-native-sdk @react-native-async-storage/async-storage
# or
yarn add @udene/react-native-sdk @react-native-async-storage/async-storage
```
## Usage
### Basic Usage with Provider
```jsx
import { FraudProvider, useFraud } from '@udene/react-native-sdk';
import Config from 'react-native-config'; // For secure API key storage (optional)
// Wrap your app with the provider
export default function App() {
return (
<FraudProvider
apiKey={Config.UDENE_API_KEY} // Use environment variables for API keys
maxRetries={5}
disableLogging={false}
logger={(message, error) => {
// Custom logging implementation
console.warn(`[Udene]: ${message}`, error);
}}
>
<YourApp />
</FraudProvider>
);
}
// Use the hook in your components
function YourComponent() {
const {
trackInteraction,
getMetrics,
analyzeTransaction,
getDeviceFingerprint
} = useFraud();
useEffect(() => {
// Example: Track user interaction
trackInteraction({
action: 'view_product',
metadata: { productId: '123' }
});
// Example: Get device fingerprint
getDeviceFingerprint().then(deviceInfo => {
if (deviceInfo.trustScore < 30) {
// Implement additional verification
}
});
}, []);
const handlePurchase = async (transactionData) => {
try {
const analysis = await analyzeTransaction({
transactionId: 'txn_123456',
userId: 'user_123',
amount: 1000,
currency: 'USD',
paymentMethod: 'credit_card',
timestamp: new Date().toISOString(),
metadata: {
productIds: ['prod_1', 'prod_2'],
shippingAddress: '123 Main St, New York, NY',
billingAddress: '123 Main St, New York, NY',
isRecurring: false
}
});
// Handle the result based on risk assessment
switch (analysis.recommendation) {
case 'approve':
// Process the transaction
break;
case 'review':
// Flag for manual review
break;
case 'deny':
// Reject the transaction
break;
}
} catch (error) {
// Handle errors
}
};
return <View>...</View>;
}
```
### Direct Client Usage
```jsx
import { UdeneClient } from '@udene/react-native-sdk';
import Config from 'react-native-config'; // For secure API key storage (optional)
// Initialize the client
const client = new UdeneClient({
apiKey: Config.UDENE_API_KEY, // Use environment variables for API keys
baseURL: 'https://api.udene.net/v1',
maxRetries: 5,
disableLogging: false,
logger: (message, error) => {
console.warn(`Custom log: ${message}`, error);
}
});
// Get fraud metrics
const metrics = await client.getMetrics();
console.log(`Current risk score: ${metrics.riskScore}`);
console.log(`Active users: ${metrics.activeUsers}`);
console.log(`Alert count: ${metrics.alertCount}`);
// Track user interaction
const result = await client.trackInteraction({
userId: 'user_123',
action: 'login',
metadata: {
ipAddress: '192.168.1.1',
deviceId: 'device_456',
browser: 'Chrome',
location: 'New York',
timestamp: new Date().toISOString()
}
});
// Analyze a transaction
const analysis = await client.analyzeTransaction({
transactionId: 'txn_123456',
userId: 'user_123',
amount: 1000,
currency: 'USD',
paymentMethod: 'credit_card',
timestamp: new Date().toISOString(),
metadata: {
productIds: ['prod_1', 'prod_2'],
shippingAddress: '123 Main St, New York, NY',
billingAddress: '123 Main St, New York, NY',
isRecurring: false
}
});
// Get device fingerprint
const deviceInfo = await client.getDeviceFingerprint();
console.log(`Device ID: ${deviceInfo.deviceId}`);
console.log(`Trust score: ${deviceInfo.trustScore}`);
```
## API Reference
### UdeneClient
The main client for accessing fraud detection services.
#### Constructor Options
- `apiKey` (required) - Your Udene API key
- `baseURL` (optional) - Custom API base URL (default: 'https://api.udene.net/v1')
- `platform` (optional) - Device platform (auto-detected from React Native)
- `maxRetries` (optional) - Maximum number of retries for failed requests (default: 3)
- `disableLogging` (optional) - Disable logging of API requests and responses (default: false)
- `logger` (optional) - Custom logger function (default: console.warn)
#### Methods
- `getMetrics()` - Get fraud metrics for the current user/device
- `getActivity()` - Get activity data for analysis
- `trackInteraction(data)` - Track a user interaction for fraud analysis
- `analyzeBEC(emailData)` - Analyze an email for Business Email Compromise (BEC) threats
- `analyzeTransaction(transactionData)` - Analyze a transaction for fraud detection
- `getDeviceFingerprint()` - Get device fingerprint information for trust assessment
### FraudProvider
React context provider for fraud detection services.
#### Props
- `apiKey` (required) - Your API key for the fraud detection service
- `baseURL` (optional) - Custom API base URL if needed
- `maxRetries` (optional) - Maximum number of retries for failed requests
- `disableLogging` (optional) - Disable logging of API requests and responses
- `logger` (optional) - Custom logger function
- `children` (required) - Child components
### useFraud
React hook for accessing fraud detection functionality within components.
#### Returns
- `client` - The UdeneClient instance
- `trackInteraction` - Function to track user interactions
- `getMetrics` - Function to get fraud metrics
- `getActivity` - Function to get user activity data
- `analyzeBEC` - Function to analyze emails for BEC threats
- `analyzeTransaction` - Function to analyze transactions
- `getDeviceFingerprint` - Function to get device fingerprint information
## Security Best Practices
1. **API Key Storage**: Never hardcode API keys in your application. Use environment variables or secure storage solutions.
2. **Data Sanitization**: The SDK automatically sanitizes data to remove sensitive information, but you should also validate user inputs.
3. **Error Handling**: Implement proper error handling to avoid exposing sensitive information to users.
4. **Keep Updated**: Always use the latest version of the SDK to benefit from security updates.
5. **Secure Communication**: The SDK uses HTTPS for all API requests. Ensure your app has proper network security configurations.
6. **Permissions**: Only request necessary permissions in your app to minimize security risks.
7. **Device Verification**: Use the `getDeviceFingerprint()` method to verify device trustworthiness before processing sensitive operations.
## License
MIT