npm package: @forticonsole/forticonsole-client-sdk
Description: Client-side behavior analytics SDK for e-commerce fraud detection
Author: FortiConsole
Latest version: 1.0.3

# FortiConsole Client SDK

A robust, modular JavaScript SDK for collecting comprehensive client-side behavior data from e-commerce websites. Built with TypeScript and Vite, this SDK provides advanced fraud detection capabilities through behavioral analytics with enhanced device fingerprinting.

## Features

### User Identification
- **Advanced Device Fingerprinting**: 
  - Canvas fingerprinting
  - WebGL fingerprinting
  - Audio context fingerprinting
  - Browser plugin detection
  - Font detection
  - Hardware capabilities analysis
- **Session Management**: Tracks user sessions with configurable timeout (default: 1 hour)

### Interaction Metrics
- **Copy-paste Detection**: Monitors clipboard usage in form fields
- **Field Focus Tracking**: Records focus timing and refocus counts
- **Typing Cadence Analysis**:
  - Keystroke dwell time mean
  - Keystroke flight time standard deviation
  - Typing speed z-score calculation
- **Mouse Behavior Tracking**:
  - Movement speed and trajectory
  - Total distance traveled
  - Maximum acceleration
  - Stop count detection

### Page & Session Metrics
- **Page-level Tracking**: Initialize and track specific page types
- **Navigation Detection**: Automatic detection of page changes
- **Navigation Timing**: Performance API integration
- **Page Dwell Time**: Time spent on each page
- **Tab Switch Detection**: Monitor user attention
- **Session Entropy Scoring**: Behavioral pattern analysis
- **Time of Day Categorization**: Morning, afternoon, evening, night

## Installation

### Public Package
```bash
npm install forticonsole-client-sdk
```

### Private Scoped Package
```bash
# Configure npm for private scope
npm config set @forticonsole:registry https://registry.npmjs.org/

# Install private package
npm install @forticonsole/client-sdk
```

## Quick Start

```javascript
import FortiConsoleSDK, { PageType } from 'forticonsole-client-sdk';

// Initialize the SDK with your API key
const sdk = new FortiConsoleSDK({
  apiKey: 'YOUR_API_KEY_HERE', // Required
  sessionTimeout: 3600000,      // Optional: 1 hour (default)
  inactivityTimeout: 300000,    // Optional: 5 minutes (default)
  debug: true                   // Optional: Enable debug logging
});

// Start collecting data
sdk.init();

// Initialize page tracking
sdk.initializePage({
  pageType: PageType.PRODUCT_LIST,
  pageUrl: window.location.href,
  pageTitle: 'Products',
  categoryId: 'electronics'     // Optional custom data
});

// Get user identifiers
const userId = await sdk.getUserId();
const sessionId = sdk.getSessionId();
const clientId = sdk.getClientId();
```

## API Reference

### Configuration

The SDK requires an API key and accepts optional timeout configurations:

```javascript
const sdk = new FortiConsoleSDK({
  apiKey: 'YOUR_API_KEY_HERE',    // Required
  sessionTimeout: 3600000,         // Optional: milliseconds (default: 1 hour)
  inactivityTimeout: 300000,       // Optional: milliseconds (default: 5 minutes)
  debug: false                     // Optional: Enable debug logging
});
```

### Page Types

Use the `PageType` enum to categorize pages:

```javascript
import { PageType } from 'forticonsole-client-sdk';

PageType.HOME                  // Home page
PageType.PRODUCT_LIST          // Product listing page
PageType.PRODUCT_DETAIL        // Product detail page
PageType.CART                  // Shopping cart
PageType.CHECKOUT              // Checkout page
PageType.PAYMENT               // Payment page
PageType.ORDER_CONFIRMATION    // Order confirmation
PageType.ACCOUNT               // User account page
PageType.SEARCH                // Search results
PageType.OTHER                 // Other pages
```

### Core Methods

#### `init()`
Initializes the SDK and starts data collection.

```javascript
sdk.init();
```

#### `initializePage(pageInfo)`
Initialize tracking for a specific page. Call this when navigating to a new page in single-page applications.

```javascript
sdk.initializePage({
  pageType: PageType.PRODUCT_DETAIL,
  pageUrl: '/product/123',
  pageTitle: 'Wireless Headphones',
  productId: '123',              // Optional
  categoryId: 'audio',           // Optional
  searchQuery: 'headphones',     // Optional
  customData: { brand: 'Sony' }  // Optional
});
```

#### `sendPaymentIntent(paymentData)`
Send payment intent data during checkout.

```javascript
sdk.sendPaymentIntent({
  customerFullName: 'John Doe',
  email: 'john@example.com',
  phoneNumber: '+1234567890',
  shippingAddress: '123 Main St, City, State 12345',
  mailingAddress: '123 Main St, City, State 12345',
  cardBin: '123456',           // First 6 digits of card
  amount: 99.99,
  numberOfItemsInCart: 3
});
```

#### `getUserId()`
Returns the unique user identifier (Promise). Note: This is now async due to enhanced fingerprinting.

```javascript
const userId = await sdk.getUserId();
```

#### `getSessionId()`
Returns the current session identifier.

#### `getClientId()`
Returns the client identifier.

#### `forceAnalyticsTransmission()`
Forces immediate transmission of collected analytics data.

#### `destroy()`
Cleans up event listeners and sends final analytics data.

## Data Collection

### Analytics Payload Structure

Analytics data is automatically sent with a structured format separating numerical and boolean metrics:

```json
{
  "clientFingerprint": "unique-device-id",
  "timeOfDay": "afternoon",
  "pageInfo": {
    "pageType": "product_detail",
    "pageUrl": "/product/123",
    "pageTitle": "Wireless Headphones"
  },
  "numericalMetrics": {
    "totalMouseDistance": 15420,
    "averageMouseSpeed": 234.56,
    "maximumMouseAcceleration": 1024.33,
    "mouseStopCount": 42,
    "keystrokeDwellMean": 145,
    "keystrokeFlightTimeStandardDeviation": 23.45,
    "pasteEventRatio": 0.05,
    "tabSwitchCount": 3,
    "fieldRefocusCount": 2,
    "sessionDuration": 300000,
    "browsingPageTime": 285000,
    "velocityScore": 45.2,
    "typingSpeedZScore": 0.85,
    "sessionEntropyScore": 2.34
  },
  "booleanMetrics": {
    "hasMouseActivity": true,
    "hasKeyboardActivity": true,
    "hasCopyPasteActivity": false,
    "hasTabSwitchActivity": true,
    "isIncognitoMode": false,
    "isTouchDevice": false,
    "hasAdBlocker": false
  },
  "sessionId": "session-123",
  "clientId": "client-456",
  "timestamp": 1680000000000
}
```

### Device Fingerprinting Behavior

**Important**: Device fingerprints are unique per browser and browsing mode by design:
- Different browsers (Chrome vs Firefox) generate different fingerprints
- Incognito/Private mode generates different fingerprints
- This respects user privacy and helps detect suspicious behavior

For cross-browser user tracking, implement server-side authentication instead.

### Data Transmission

- **Endpoint**: `https://api.forticonsole.com/analytics`
- **Method**: `navigator.sendBeacon` (with fetch fallback)
- **Triggers**: 
  - 5 minutes of inactivity
  - Page navigation
  - Manual transmission

## React Example (TypeScript)

A complete e-commerce demo application is included in the `example/` directory.

### Running the Example

```bash
# 1. Build the SDK first
npm install
npm run build

# 2. Run the example app
cd example
npm install
npm run dev
```

### Example Features

- Full e-commerce flow (browse → cart → checkout)
- TypeScript implementation
- All SDK features demonstrated
- Real-time behavior tracking visualization

See [example/README.md](./example/README.md) for detailed instructions.

## Performance Considerations

- **Event Throttling**: Mouse movements throttled to 50ms intervals
- **Memory Management**: Limited storage of historical data points
- **Non-blocking**: Uses `navigator.sendBeacon` for data transmission
- **Automatic Cleanup**: Event listeners removed on destroy
- **Efficient Fingerprinting**: Fingerprint calculated once and cached

## Browser Support

- Chrome 60+
- Firefox 55+
- Safari 11+
- Edge 79+

## Security & Privacy

- **No PII in Fingerprinting**: Device fingerprinting uses only technical characteristics
- **Secure Transmission**: All data sent over HTTPS
- **No Full Card Numbers**: Only card BIN (first 6 digits) collected
- **Session Isolation**: Each session has unique identifiers
- **Local Storage**: Minimal use with automatic cleanup

## Development

### Building the SDK

```bash
# Install dependencies
npm install

# Build for production
npm run build

# Run development server (for SDK development)
npm run dev

# Run the TypeScript React example
cd example
npm install
npm run dev
```

### Important: Building Before Testing

The SDK must be built before it can be used in the example app or installed as a package:

```bash
# Always build first
npm run build

# Then you can test locally
cd example
npm run dev
```

### Publishing to NPM

```bash
# Login to NPM
npm login

# Build and publish public package
npm run build
npm publish

# For private scoped package
npm run build
npm publish --access restricted
```

### CI/CD Pipelines

The SDK includes GitHub Actions workflows for:

1. **SDK Publishing** (`publish-sdk.yml`):
   - Automatically publishes to npm on changes to `src/`
   - Supports manual version bumping (patch/minor/major)
   - Creates GitHub releases

2. **Example App Deployment** (`deploy-example.yml`):
   - Deploys to Azure Static Web Apps
   - Automatic preview deployments for PRs
   - Production deployment on merge to main

See [CI/CD Setup Guide](./docs/CICD_SETUP.md) for detailed configuration.

## Demo

Live demo: [https://forticonsole-sdk-demo.azurestaticapps.net](https://forticonsole-sdk-demo.azurestaticapps.net)

(Configure Azure Static Web Apps to enable)

## License

MIT License - See LICENSE file for details

## Support

For issues, questions, or contributions, please visit our [GitHub repository](https://github.com/forticonsole/client-sdk).