> ## Documentation Index
> Fetch the complete documentation index at: https://docs.txcloud.thetekcircle.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Fraud Detection

> Protect your platform from fraud with TXCloud FraudShield

## Overview

FraudShield provides comprehensive fraud detection capabilities including device fingerprinting, duplicate detection, velocity controls, and custom rules.

## Key Features

<CardGroup cols={2}>
  <Card title="Device Intelligence" icon="mobile">
    Fingerprint devices and detect emulators, VPNs, and suspicious patterns
  </Card>

  <Card title="Duplicate Detection" icon="clone">
    Find when the same document or face is used across accounts
  </Card>

  <Card title="Velocity Controls" icon="gauge-high">
    Prevent abuse with rate limiting and pattern detection
  </Card>

  <Card title="Custom Rules" icon="gavel">
    Create rules tailored to your business logic
  </Card>
</CardGroup>

## Device Fingerprinting

Register and track devices to identify suspicious patterns:

<CodeGroup>
  ```javascript JavaScript theme={null}
  // Register a device fingerprint
  const device = await txcloud.fraud.devices.register({
    fingerprint: {
      user_agent: navigator.userAgent,
      screen_resolution: `${screen.width}x${screen.height}`,
      timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
      language: navigator.language,
      platform: navigator.platform,
      canvas_hash: await getCanvasHash(),
      webgl_hash: await getWebGLHash()
    },
    ip_address: clientIp,
    user_id: userId
  });

  console.log('Device ID:', device.id);
  console.log('Risk Score:', device.risk_score);
  console.log('Risk Level:', device.risk_level);

  // Check for suspicious signals
  if (device.signals.is_vpn) {
    console.log('VPN detected');
  }
  if (device.signals.is_emulator) {
    console.log('Emulator detected');
  }
  ```

  ```python Python theme={null}
  device = txcloud.fraud.devices.register(
      fingerprint={
          "user_agent": user_agent,
          "screen_resolution": screen_resolution,
          "timezone": timezone,
          "language": language,
          "platform": platform,
          "canvas_hash": canvas_hash,
          "webgl_hash": webgl_hash
      },
      ip_address=client_ip,
      user_id=user_id
  )

  print(f"Device ID: {device.id}")
  print(f"Risk Score: {device.risk_score}")

  if device.signals.is_vpn:
      print("VPN detected")
  ```
</CodeGroup>

### Device Response

```json theme={null}
{
  "id": "dev_a1b2c3d4e5f6",
  "risk_score": 250,
  "risk_level": "medium",
  "is_new": false,
  "first_seen": "2024-12-01T08:00:00Z",
  "times_seen": 47,
  
  "signals": {
    "is_bot": false,
    "is_emulator": false,
    "is_vpn": true,
    "is_proxy": false,
    "is_tor": false,
    "is_datacenter": false,
    "timezone_mismatch": false
  },
  
  "ip_analysis": {
    "ip": "102.45.67.89",
    "country": "MA",
    "city": "Casablanca",
    "isp": "Maroc Telecom",
    "is_vpn": true,
    "vpn_provider": "NordVPN"
  },
  
  "linked_users": ["usr_123", "usr_456"],
  "linked_accounts": 2
}
```

<Warning>
  A device linked to multiple accounts may indicate account sharing or fraud.
</Warning>

## Duplicate Detection

Find if a document or face has been used before:

```javascript theme={null}
// Search for duplicates
const duplicates = await txcloud.fraud.duplicates.search({
  type: 'face',  // or 'document'
  image: selfieBase64,
  threshold: 0.85  // similarity threshold
});

if (duplicates.matches.length > 0) {
  console.log('Duplicate found!');
  
  for (const match of duplicates.matches) {
    console.log(`Match ID: ${match.id}`);
    console.log(`Similarity: ${match.similarity}`);
    console.log(`Original verification: ${match.verification_id}`);
  }
}
```

### Response

```json theme={null}
{
  "id": "dup_a1b2c3d4",
  "type": "face",
  "matches_found": true,
  "matches": [
    {
      "id": "match_xyz789",
      "verification_id": "ver_abc123",
      "similarity": 0.94,
      "created_at": "2024-11-15T10:00:00Z",
      "user_id": "usr_different_user"
    }
  ]
}
```

## Velocity Controls

Prevent abuse with rate-based rules:

```javascript theme={null}
// Check velocity before allowing action
const velocityCheck = await txcloud.fraud.velocity.check({
  user_id: userId,
  action: 'verification_attempt',
  window: '1h',
  ip_address: clientIp,
  device_id: deviceId
});

if (!velocityCheck.allowed) {
  console.log('Rate limit exceeded');
  console.log(`Retry after: ${velocityCheck.retry_after}s`);
  throw new Error('Too many attempts. Please try again later.');
}
```

### Create Velocity Rules

```javascript theme={null}
// Create a velocity rule
await txcloud.fraud.velocity.rules.create({
  name: 'Verification Limit',
  description: 'Max 3 verification attempts per hour',
  action: 'verification_attempt',
  limit: 3,
  window: '1h',
  scope: 'user_id',  // or 'ip_address', 'device_id'
  on_exceed: 'block',
  cooldown: '30m'
});
```

## Custom Fraud Rules

Create rules tailored to your business:

```javascript theme={null}
// Create a custom rule
const rule = await txcloud.fraud.rules.create({
  name: 'High Risk New User',
  description: 'Flag new users with VPN and high-value transactions',
  condition: `
    user.age_days < 7 AND 
    device.is_vpn = true AND 
    transaction.amount > 10000
  `,
  action: 'flag',
  score_adjustment: 300,
  enabled: true
});
```

### Rule Conditions

| Variable                  | Description             |
| ------------------------- | ----------------------- |
| `user.age_days`           | Days since registration |
| `user.verification_count` | Number of verifications |
| `device.is_vpn`           | VPN detected            |
| `device.is_emulator`      | Emulator detected       |
| `device.linked_accounts`  | Accounts using device   |
| `transaction.amount`      | Transaction amount      |
| `velocity.daily_count`    | Actions today           |

### Rule Actions

| Action      | Description                     |
| ----------- | ------------------------------- |
| `flag`      | Add flag, continue processing   |
| `review`    | Queue for manual review         |
| `block`     | Block the action                |
| `challenge` | Require additional verification |

## Blocklist Management

Manage blocked entities:

```javascript theme={null}
// Add to blocklist
await txcloud.fraud.blocklist.add({
  type: 'device',
  value: deviceId,
  reason: 'confirmed_fraud',
  expires_in: null  // permanent
});

// Check blocklist
const check = await txcloud.fraud.blocklist.check({
  type: 'device',
  value: deviceId
});

if (check.blocked) {
  console.log('Device is blocked');
  console.log(`Reason: ${check.reason}`);
}
```

### Blocklist Types

| Type       | Example               |
| ---------- | --------------------- |
| `device`   | Device fingerprint ID |
| `ip`       | IP address or CIDR    |
| `email`    | Email address         |
| `phone`    | Phone number          |
| `document` | Document number       |

## Fraud Signals

Report and track fraud signals:

```javascript theme={null}
// Report a fraud signal
const signal = await txcloud.fraud.signals.report({
  type: 'chargeback',
  user_id: userId,
  verification_id: verificationId,
  details: {
    amount: 5000,
    currency: 'MAD',
    transaction_id: 'txn_123'
  }
});

// Later, confirm or dismiss
await txcloud.fraud.signals.confirm(signal.id, {
  notes: 'Confirmed chargeback from bank'
});

// Or dismiss false positive
await txcloud.fraud.signals.dismiss(signal.id, {
  notes: 'Customer resolved dispute'
});
```

## Integration with Identity

FraudShield integrates automatically with Identity verification:

```javascript theme={null}
// Fraud signals are included in verification response
const verification = await txcloud.identity.verify({
  document_front: doc,
  country: 'MA',
  checks: ['ocr', 'face_match', 'liveness', 'fraud']
});

// Access fraud signals
console.log('Fraud check:', verification.checks.fraud);
// {
//   status: 'passed',
//   risk_score: 150,
//   duplicate_detected: false,
//   device_risk: 'low',
//   signals: ['known_device', 'normal_velocity']
// }
```

## Analytics

Monitor fraud patterns:

```javascript theme={null}
const summary = await txcloud.fraud.analytics.summary({
  period: '30d'
});

console.log('Total signals:', summary.signals.total);
console.log('Confirmed fraud:', summary.signals.confirmed);
console.log('False positive rate:', summary.false_positive_rate);

// Get trends
const trends = await txcloud.fraud.analytics.trends({
  period: '30d',
  granularity: 'daily'
});
```

## Best Practices

<AccordionGroup>
  <Accordion title="Layer Your Defenses" icon="layer-group">
    Use multiple fraud signals together:

    * Device fingerprinting
    * Velocity controls
    * Duplicate detection
    * Custom rules
  </Accordion>

  <Accordion title="Tune Your Thresholds" icon="sliders">
    Start conservative and adjust based on data:

    * Week 1-2: Log all flags, don't block
    * Week 3-4: Analyze patterns
    * Week 5+: Implement blocking rules
  </Accordion>

  <Accordion title="Monitor False Positives" icon="chart-line">
    Track and minimize false positives:

    * Review blocked users regularly
    * Provide appeal process
    * Adjust rules based on feedback
  </Accordion>

  <Accordion title="Feed Back Confirmed Fraud" icon="rotate">
    Report confirmed fraud to improve detection:

    * Use signals.report() for new fraud
    * Confirm or dismiss flagged signals
    * This trains the ML models
  </Accordion>
</AccordionGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Transaction Monitoring" icon="credit-card" href="/guides/transaction-monitoring">
    Add real-time transaction scoring
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference/overview">
    Explore FraudShield endpoints
  </Card>
</CardGroup>
