npm package: @keverdjs/fraud-sdk
Description: Vanilla JavaScript SDK for Keverd fraud detection and device fingerprinting
Author: Keverd
Latest version: 2.0.1

# @keverdjs/fraud-sdk

Vanilla JavaScript SDK for Keverd fraud detection and device fingerprinting. Works in any JavaScript environment (browser, Node.js, etc.).

## ✨ Features

- **Custom Fingerprinting System**: Built from scratch with 15+ fingerprint collectors (no external dependencies)
- **Stable Visitor ID**: Deterministic device identification across browsers
- **Behavioral Biometrics**: Typing patterns, mouse movements, swipe gestures
- **Privacy Signals**: Incognito mode, VPN, automation detection
- **Use-Case Specific**: Login, checkout, registration, password reset, account change verification
- **Zero Dependencies**: No external libraries required

## Installation

```bash
npm install @keverdjs/fraud-sdk
```

## Quick Start

```javascript
import { Keverd } from '@keverdjs/fraud-sdk';

// Initialize with API key
Keverd.init('your-api-key');

// Get visitor data and risk assessment
const result = await Keverd.get();

console.log('Risk Score:', result.risk_score);
console.log('Action:', result.action);
console.log('Session ID:', result.session_id);
```

### With Configuration Object

```javascript
import { Keverd } from '@keverdjs/fraud-sdk';

// Initialize with configuration
Keverd.init({
  apiKey: 'your-api-key',
  endpoint: 'https://api.keverd.com', // Optional: override API endpoint
  debug: true, // Optional: enable debug logging
});

// Get visitor data
const result = await Keverd.get();
```

## API Reference

### `Keverd.init(config)`

Initialize the SDK with your API key.

**Parameters:**
- `config` (string | SDKConfig): API key string or configuration object

**Example:**
```javascript
// Simple initialization
Keverd.init('your-api-key');

// With options
Keverd.init({
  apiKey: 'your-api-key',
  userId: 'optional-user-id',
  endpoint: 'https://api.keverd.com',
  debug: false
});
```

### Local Development Endpoint

```javascript
Keverd.init({
  apiKey: 'your-local-api-key',
  endpoint: 'http://localhost:8000'
});
```

If `endpoint` is not provided, the SDK falls back to `NEXT_PUBLIC_API_URL` when available, then `https://api.keverd.com`.

### `Keverd.get()`

Get visitor data and risk assessment. This is the main method for fraud detection.

**Returns:** Promise<FingerprintResponse>

**Example:**
```javascript
const result = await Keverd.get();

// Result structure:
// {
//   risk_score: 25,           // 0-100
//   score: 0.25,              // 0.0-1.0
//   action: 'allow',          // 'allow' | 'soft_challenge' | 'hard_challenge' | 'block'
//   reason: ['new_user'],     // Array of risk reasons
//   session_id: 'uuid',       // Session identifier
//   requestId: 'uuid',        // Request identifier
//   sim_swap_engine: {...}    // SIM swap detection results (null for web)
// }
```

### `Keverd.getVisitorData()`

Legacy alias for `Keverd.get()`. Existing integrations continue to work.

### `Keverd.getDeviceId()`

Returns the current stable device/session identifier.

```javascript
const deviceId = await Keverd.getDeviceId();
```

### `Keverd.createTransactionID(metadata?)`

Legacy method for backward compatibility. Returns the session ID from `get()`.

**Parameters:**
- `metadata` (TransactionMetadata, optional): Transaction metadata

**Returns:** Promise<string> - Session ID

**Example:**
```javascript
const transactionId = await Keverd.createTransactionID({
  amount: 1000,
  currency: 'KES',
  recipient: '254712345678'
});
```

### `Keverd.verifyLogin(userId?, metadata?)`

Verify user identity during login attempts. Optimized for detecting account takeover and credential stuffing.

**Parameters:**
- `userId` (string, optional): User identifier
- `metadata` (Record<string, unknown>, optional): Additional metadata

**Returns:** Promise<FingerprintResponse>

**Example:**
```javascript
const result = await Keverd.verifyLogin('user-123', {
  email: 'user@example.com',
  loginAttempt: 1
});

if (result.action === 'block') {
  // Block login attempt
  showError('Login blocked due to security concerns');
} else if (result.action === 'hard_challenge') {
  // Require MFA
  await requestMFA();
}
```

### `Keverd.verifyRegistration(metadata?)`

Verify new account registrations with enhanced behavioral monitoring. Detects bot signups, fake accounts, and mid-session behavior changes.

**Parameters:**
- `metadata` (Record<string, unknown>, optional): Additional metadata (e.g., email, username)

**Returns:** Promise<FingerprintResponse> with enhanced fields:
- `behavior_change`: Behavioral analysis vs baseline
- `adaptive_response`: Recommended challenges (MFA, CAPTCHA)

**Example:**
```javascript
// Call when user submits registration form
const result = await Keverd.verifyRegistration({
  email: userEmail,
  username: userName
});

// Handle adaptive responses
if (result.action === 'allow') {
  // Low risk - proceed with registration
  await createUserAccount(userData);
} else if (result.action === 'soft_challenge') {
  // Medium risk - show recommended challenges
  const challenges = result.adaptive_response?.challenges || [];
  
  if (challenges.includes('captcha')) {
    await showCaptcha();
  }
  
  if (challenges.includes('mfa')) {
    await sendVerificationCode(userEmail);
  }
  
  // After challenge completion, verify again
  const recheck = await Keverd.verifyRegistration();
  if (recheck.action === 'allow') {
    await createUserAccount(userData);
  }
} else if (result.action === 'block') {
  // High risk - block registration
  showError('Registration blocked due to security concerns');
}
```

### `Keverd.verifyCheckout(amount, currency, metadata?)`

Verify user during checkout/payment flows. Detects payment fraud and stolen card usage.

**Parameters:**
- `amount` (number): Transaction amount
- `currency` (string): Currency code (e.g., 'KES', 'USD')
- `metadata` (Record<string, unknown>, optional): Additional metadata

**Returns:** Promise<FingerprintResponse>

**Example:**
```javascript
const result = await Keverd.verifyCheckout(5000, 'KES', {
  paymentMethod: 'card',
  cardLast4: '1234'
});

if (result.action === 'block') {
  // Block transaction
  showError('Transaction blocked');
} else if (result.action === 'hard_challenge') {
  // Require 2FA for payment
  await requestPayment2FA();
}
```

### `Keverd.verifyPasswordReset(email?, metadata?)`

Verify password reset requests. High-risk use case requiring enhanced security checks.

**Parameters:**
- `email` (string, optional): User email
- `metadata` (Record<string, unknown>, optional): Additional metadata

**Returns:** Promise<FingerprintResponse>

**Example:**
```javascript
const result = await Keverd.verifyPasswordReset(userEmail);

if (result.action === 'block') {
  // Block password reset - potential account takeover
  showError('Password reset blocked');
  logSecurityEvent('blocked_password_reset', result);
}
```

### `Keverd.verifyAccountChange(changeType?, metadata?)`

Verify sensitive account changes (email, phone, password). Detects unauthorized account modifications.

**Parameters:**
- `changeType` (string, optional): Type of change ('email', 'phone', 'password')
- `metadata` (Record<string, unknown>, optional): Additional metadata

**Returns:** Promise<FingerprintResponse>

**Example:**
```javascript
const result = await Keverd.verifyAccountChange('email', {
  oldEmail: currentEmail,
  newEmail: newEmail
});

if (result.action === 'hard_challenge') {
  // Require strong verification for account changes
  await sendVerificationCode(currentEmail);
  await sendVerificationCode(newEmail);
}
```

### `Keverd.destroy()`

Destroy the SDK instance and stop all data collection.

**Example:**
```javascript
Keverd.destroy();
```

## Use Cases

### Registration Flow

The SDK automatically collects behavioral data from the moment it's initialized. For registration flows, call `verifyRegistration()` when the user submits the form:

```javascript
import { Keverd } from '@keverdjs/fraud-sdk';

// Initialize early in your app (e.g., on page load)
Keverd.init('your-api-key');

// Later, when user submits registration form
async function handleRegistrationSubmit(formData) {
  // Verify registration with behavioral analysis
  const result = await Keverd.verifyRegistration({
    email: formData.email,
    username: formData.username
  });
  
  // Check risk level
  if (result.action === 'allow') {
    // Low risk - create account
    await createAccount(formData);
  } else if (result.action === 'soft_challenge') {
    // Medium risk - show challenges
    const challenges = result.adaptive_response?.challenges || [];
    if (challenges.includes('captcha')) {
      await showCaptcha();
    }
    if (challenges.includes('mfa')) {
      await sendEmailVerification(formData.email);
    }
  } else if (result.action === 'block') {
    // High risk - block registration
    showError('Registration blocked. Please contact support.');
  }
}
```

### Login Flow

```javascript
async function handleLogin(email, password) {
  // Verify login attempt
  const result = await Keverd.verifyLogin(email);
  
  if (result.action === 'block') {
    // Block login - potential account takeover
    showError('Login blocked due to security concerns');
    return;
  }
  
  // Proceed with authentication
  const authResult = await authenticateUser(email, password);
  
  if (result.action === 'hard_challenge' && authResult.success) {
    // Require MFA even after successful password
    await requestMFA();
  }
}
```

### Checkout Flow

```javascript
async function handleCheckout(cart, paymentMethod) {
  // Verify checkout
  const result = await Keverd.verifyCheckout(
    cart.total,
    cart.currency,
    {
      paymentMethod: paymentMethod.type,
      items: cart.items.length
    }
  );
  
  if (result.action === 'block') {
    // Block transaction
    showError('Transaction blocked');
    return;
  }
  
  if (result.action === 'hard_challenge') {
    // Require payment verification
    await requestPayment2FA();
  }
  
  // Proceed with payment
  await processPayment(cart, paymentMethod);
}
```

## Data Collection

The SDK automatically collects comprehensive behavioral and device data:

### Device Information
- Screen resolution, timezone, language, user agent
- Device fingerprint (canvas, WebGL, fonts, etc.)
- Browser capabilities and hardware signals

### Behavioral Data
- **Mouse movements**: Velocity, acceleration, patterns
- **Keyboard patterns**: Typing speed, dwell time, flight time
- **Page interactions**: Clicks, scrolls, time on page
- **Form interactions**: Focus, blur, copy/paste, autofill detection

### Privacy Signals
- Incognito mode detection
- VPN/proxy detection
- Automation/bot detection
- Ad blocker detection

All data collection happens automatically in the background. You don't need to manually collect or send any signals - the SDK handles everything.

## Response Structure

```typescript
interface FingerprintResponse {
  risk_score: number;        // 0-100 risk score
  score: number;             // 0.0-1.0 normalized score
  action: 'allow' | 'soft_challenge' | 'hard_challenge' | 'block';
  reason: string[];          // Array of risk reasons
  session_id: string;        // UUID session identifier
  requestId: string;         // UUID request identifier
  
  // Enhanced fields for registration verification
  behavior_change?: {
    baseline_available: boolean;
    behavior_changed: boolean;
    change_score: number;      // 0-100
    change_reasons: string[];
    similarity_score: number;  // 0-100
  };
  
  adaptive_response?: {
    recommended_action: string;
    challenges: string[];      // ['captcha', 'mfa', 'email_verification']
    reason: string;
    confidence: number;        // 0.0-1.0
  };
  
  sim_swap_engine?: {        // SIM swap detection (null for web SDKs)
    userId?: string;
    risk: number;
    flags: {
      sim_changed?: boolean;
      device_changed?: boolean;
      behavior_anomaly?: boolean;
      time_anomaly?: boolean;
      velocity_anomaly?: boolean;
    };
    updatedProfile?: Record<string, unknown>;
  };
}
```

## Browser Support

- Chrome (latest)
- Firefox (latest)
- Safari (latest)
- Edge (latest)

## License

MIT

## Support

For issues, questions, or contributions, please visit the [GitHub repository](https://github.com/keverd/keverd-fraud-sdk-web).