UNPKG

@ipranker/sdk

Version:

Professional IP Intelligence and Device Fingerprinting SDK - Comprehensive fraud detection with single API call

544 lines (416 loc) 12.8 kB
<div align="center"> # @ipranker/sdk ### Professional IP Intelligence & Device Fingerprinting SDK [![npm version](https://img.shields.io/npm/v/@ipranker/sdk.svg?style=flat-square)](https://www.npmjs.com/package/@ipranker/sdk) [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg?style=flat-square)](https://opensource.org/licenses/MIT) [![TypeScript](https://img.shields.io/badge/TypeScript-5.0-blue?style=flat-square&logo=typescript)](https://www.typescriptlang.org/) **Single API call for comprehensive IP intelligence and fraud detection** </div> --- ## Overview IPRanker SDK provides a simple, one-line integration for advanced IP intelligence and fraud detection. With a single method call, you get comprehensive analysis including: - IP reputation and geolocation - Proxy, VPN, and Tor detection - Bot and automation detection - Device fingerprinting - Risk scoring ## Features - ✅ **Simple Integration** - One line of code to get started - ✅ **Comprehensive Analysis** - IP intelligence + device fingerprinting + behavioral analysis - ✅ **TypeScript Support** - Full type definitions included - ✅ **Lightweight** - ~3 KB gzipped - ✅ **Framework Agnostic** - Works with React, Vue, Angular, vanilla JS - ✅ **Privacy-Focused** - No PII collection, GDPR compliant ## Installation ### npm ```bash npm install @ipranker/sdk ``` ### yarn ```bash yarn add @ipranker/sdk ``` ### CDN ```html <script src="https://unpkg.com/@ipranker/sdk"></script> ``` ## Quick Start ```typescript import IPRanker from '@ipranker/sdk'; // Initialize with your API key const ipranker = new IPRanker('your-api-key-here'); // Analyze current visitor const result = await ipranker.analyze(); if (result.success) { console.log('Location:', result.data.location); console.log('Is Proxy:', result.data.proxy.isProxy); console.log('Is Bot:', result.data.bot.isBot); console.log('Reputation:', result.data.reputation); } ``` ## Usage Examples ### Vanilla JavaScript ```html <!DOCTYPE html> <html> <head> <script src="https://unpkg.com/@ipranker/sdk"></script> </head> <body> <button onclick="checkUser()">Analyze Visitor</button> <script> const ipranker = new IPRanker.IPRanker('your-api-key'); async function checkUser() { const result = await ipranker.analyze(); if (result.success) { const riskLevel = result.data.reputation.riskLevel; if (riskLevel === 'High' || riskLevel === 'Risky') { alert('High risk user detected!'); } else { console.log('User verified:', result.data); } } } </script> </body> </html> ``` ### React ```typescript import { useState, useEffect } from 'react'; import IPRanker from '@ipranker/sdk'; function App() { const [result, setResult] = useState(null); const [loading, setLoading] = useState(false); useEffect(() => { const ipranker = new IPRanker('your-api-key'); const analyzeUser = async () => { setLoading(true); try { const data = await ipranker.analyze(); setResult(data); } catch (error) { console.error('Analysis failed:', error); } finally { setLoading(false); } }; analyzeUser(); }, []); if (loading) return <div>Analyzing...</div>; return ( <div> {result && result.success && ( <> <p>IP: {result.data.ip}</p> <p>Country: {result.data.location.country_name}</p> <p>City: {result.data.location.city}</p> <p>Is Proxy: {result.data.proxy.isProxy ? 'Yes' : 'No'}</p> <p>Risk Level: {result.data.reputation.riskLevel}</p> </> )} </div> ); } ``` ### Vue 3 ```vue <template> <div> <div v-if="loading">Analyzing...</div> <div v-else-if="result && result.success"> <p>IP: {{ result.data.ip }}</p> <p>Country: {{ result.data.location.country_name }}</p> <p>City: {{ result.data.location.city }}</p> <p>Is Proxy: {{ result.data.proxy.isProxy ? 'Yes' : 'No' }}</p> <p>Risk Level: {{ result.data.reputation.riskLevel }}</p> </div> </div> </template> <script setup> import { ref, onMounted } from 'vue'; import IPRanker from '@ipranker/sdk'; const loading = ref(false); const result = ref(null); onMounted(async () => { const ipranker = new IPRanker('your-api-key'); loading.value = true; try { result.value = await ipranker.analyze(); } catch (error) { console.error('Analysis failed:', error); } finally { loading.value = false; } }); </script> ``` ### Angular ```typescript import { Component, OnInit } from '@angular/core'; import { CommonModule } from '@angular/common'; import IPRanker from '@ipranker/sdk'; @Component({ selector: 'app-visitor-analysis', standalone: true, imports: [CommonModule], template: ` <div> <button (click)="analyze()" [disabled]="loading"> {{ loading ? 'Analyzing...' : 'Analyze Visitor' }} </button> <div *ngIf="result && result.success"> <p>IP: {{ result.data.ip }}</p> <p>Country: {{ result.data.location.country_name }}</p> <p>City: {{ result.data.location.city }}</p> <p>Is Proxy: {{ result.data.proxy.isProxy ? 'Yes' : 'No' }}</p> <p>Risk Level: {{ result.data.reputation.riskLevel }}</p> </div> </div> ` }) export class VisitorAnalysisComponent implements OnInit { loading = false; result: any = null; private ipranker = new IPRanker('your-api-key'); async analyze() { this.loading = true; try { this.result = await this.ipranker.analyze(); } catch (error) { console.error('Analysis failed:', error); } finally { this.loading = false; } } } ``` ## 📚 More Framework Examples For complete, production-ready examples with services, guards, interceptors, and more: **[📖 View All Framework Examples on IPRanker Docs](https://ipranker.com/docs)** Interactive examples available for: - ✅ **Angular** - Service, components, route guards, HTTP interceptors - ✅ **React** - Hooks, context, custom hooks - ✅ **Vue** - Composition API, Options API - ✅ **Vanilla JS** - Plain JavaScript implementation ## API Reference ### Constructor ```typescript new IPRanker(apiKey: string, options?: IPRankerOptions) ``` #### Options | Option | Type | Default | Description | |--------|------|---------|-------------| | `collectBehavior` | `boolean` | `true` | Enable behavioral analysis | | `behaviorTimeout` | `number` | `5000` | Max time to collect behavior (ms) | | `cache` | `boolean` | `true` | Cache results locally | | `cacheTimeout` | `number` | `300000` | Cache expiration (ms) | | `debug` | `boolean` | `false` | Enable debug logging | #### Example ```typescript const ipranker = new IPRanker('your-api-key', { collectBehavior: true, behaviorTimeout: 3000, cache: false, debug: true }); ``` ### Methods #### `analyze(options?): Promise<AnalysisResult>` Analyzes the current visitor and returns comprehensive intelligence. **Parameters:** - `options` (optional): - `ip?: string` - Specific IP to analyze (otherwise auto-detected) - `includeRawData?: boolean` - Include detailed raw data in response **Returns:** `Promise<AnalysisResult>` **Example:** ```typescript // Basic usage const result = await ipranker.analyze(); // Analyze specific IP const result = await ipranker.analyze({ ip: '8.8.8.8' }); // Include raw data const result = await ipranker.analyze({ includeRawData: true }); ``` #### `clearCache(): void` Clears locally cached results. ```typescript ipranker.clearCache(); ``` #### `destroy(): void` Stops data collection and cleans up resources. ```typescript ipranker.destroy(); ``` ## Response Format ```typescript interface AnalysisResult { success: boolean; ip: string; // Geolocation location: { country: string; countryCode: string; city: string; region: string; latitude: number; longitude: number; timezone: string; isp: string; }; // Threat Detection threats: { isTor: boolean; isProxy: boolean; isVPN: boolean; isBot: boolean; isBlacklisted: boolean; }; // Risk Assessment riskScore: number; // 0-100 (higher = more risky) deviceTrust: number; // 0-100 (higher = more trustworthy) timestamp: number; } ``` ## Risk Score Interpretation | Score | Level | Description | Action | |-------|-------|-------------|--------| | 0-30 | Low | Trusted user | Allow | | 31-60 | Medium | Some suspicious signals | Monitor | | 61-80 | High | Multiple risk factors | Challenge (CAPTCHA, 2FA) | | 81-100 | Critical | Strong fraud indicators | Block or manual review | ## Use Cases ### Fraud Prevention ```typescript const result = await ipranker.analyze(); if (result.riskScore > 70) { // Show CAPTCHA or additional verification showCaptcha(); } else if (result.threats.isProxy || result.threats.isVPN) { // Log for review logSuspiciousActivity(result); } else { // Allow transaction processPayment(); } ``` ### Account Registration ```typescript const result = await ipranker.analyze(); if (result.threats.isBot) { return 'Bot detected. Please verify you are human.'; } if (result.riskScore > 60) { // Require email verification requireEmailVerification(); } // Proceed with registration createAccount(); ``` ### Content Access Control ```typescript const result = await ipranker.analyze(); if (result.threats.isTor) { return 'Access from Tor network is not allowed.'; } if (result.location.countryCode === 'CN') { // Apply geo-restrictions showGeoblockedMessage(); } // Grant access showContent(); ``` ## Event Callbacks ```typescript const ipranker = new IPRanker('your-api-key', { onReady: () => { console.log('SDK initialized'); }, onAnalyzing: () => { console.log('Analysis in progress...'); }, onComplete: (result) => { console.log('Analysis complete:', result); }, onError: (error) => { console.error('Analysis failed:', error); } }); ``` ## Browser Support | Browser | Minimum Version | |---------|----------------| | Chrome | 90+ | | Firefox | 88+ | | Safari | 14+ | | Edge | 90+ | | iOS Safari | 14+ | | Android Chrome | 90+ | ## Privacy & Compliance - ✅ **No PII Collection** - Only technical device characteristics - ✅ **GDPR Compliant** - Can be used with cookie consent - ✅ **No Permissions Required** - Works without browser prompts - ✅ **Secure** - HTTPS only, no data stored on client ## Performance - **Bundle Size**: ~3 KB gzipped - **Initialization**: < 10ms - **Analysis Time**: ~500ms average - **Memory Usage**: < 2 MB ## Error Handling ```typescript try { const result = await ipranker.analyze(); console.log(result); } catch (error) { if (error.message.includes('API key')) { console.error('Invalid API key'); } else if (error.message.includes('network')) { console.error('Network error - check connection'); } else { console.error('Analysis failed:', error); } } ``` ## TypeScript Support Full TypeScript definitions are included: ```typescript import IPRanker, { AnalysisResult, IPRankerOptions } from '@ipranker/sdk'; const options: IPRankerOptions = { collectBehavior: true, cache: false }; const ipranker = new IPRanker('api-key', options); const result: AnalysisResult = await ipranker.analyze(); ``` ## Troubleshooting ### "Invalid API key" Error Make sure you're using a valid API key. Contact support to get your key. ### Analysis Times Out Try increasing the timeout: ```typescript const ipranker = new IPRanker('api-key', { behaviorTimeout: 10000 // 10 seconds }); ``` ### CORS Errors Make sure your domain is whitelisted. Contact support to add your domain. ## Support ### Getting Help - 📧 **Email**: support@ipranker.com - 📚 **Documentation**: https://ipranker.com/docs - 🐛 **Issues**: Report bugs via support email ### Enterprise Support For enterprise plans, custom features, or consulting: - 📧 **Enterprise**: enterprise@ipranker.com - 💼 **Sales**: sales@ipranker.com ## Changelog See [CHANGELOG.md](./CHANGELOG.md) for version history and updates. ## License MIT © 2025 IPRanker --- <div align="center"> **Made with ❤️ by the IPRanker Team** </div>