npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@udene/sdk

v1.0.1

Published

Udene Fraud Detection SDK for JavaScript

Readme

@udene/sdk

A comprehensive fraud detection and security package for JavaScript applications.

Installation

npm install @udene/sdk
# or
yarn add @udene/sdk

Usage

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 object
  • baseURL (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