# Vesant Compliance SDK

> TypeScript SDK for Vesant Compliance Platform - Geolocation Verification, Risk Profiling, KYC, and Compliance Orchestration

## Features

- **Geolocation Compliance** - IP verification, VPN/proxy detection, jurisdiction checks, device fingerprinting
- **CipherText** - Encrypted device/location data collection with GPS auto-detection
- **Risk Profiling** - Customer risk profile creation and management
- **KYC** - Document verification, submission links, and status tracking
- **Compliance Orchestration** - Unified registration, login, and transaction verification
- **Live Location Requests** - Request and capture GPS location from customers via SMS/email
- **React Hooks** - Ready-to-use hooks for all compliance workflows
- **Interceptors** - Request/response interceptors for logging, auth, and custom logic
- **AbortController** - Cancel in-flight requests
- **Structured Logging** - Pluggable logger interface
- **Tree-Shakeable** - Import only what you need
- **Type-Safe** - Full TypeScript support with detailed type definitions

## Installation

```bash
npm install vesant-sdk
# or
yarn add vesant-sdk
# or
pnpm add vesant-sdk
```

## Quick Start

### Initialize the SDK

```typescript
import { ComplianceClient } from 'vesant-sdk';

const sdk = new ComplianceClient({
  baseURL: process.env.VESANT_API_URL,
  tenantId: process.env.VESANT_TENANT_ID,
  apiKey: process.env.VESANT_API_KEY,
});
```

### Registration Verification

```typescript
const result = await sdk.verifyAtRegistration({
  customerId: 'CUST-12345',
  fullName: 'John Doe',
  emailAddress: 'john@example.com',
  ipAddress: req.ip,
  deviceFingerprint: {
    device_id: deviceId,
    user_agent: req.headers['user-agent'],
    platform: 'web',
  },
});

if (result.allowed) {
  console.log('Registration approved');
  console.log('Customer profile:', result.profile);

  if (result.requiresKYC) {
    // Redirect to KYC flow
  }
} else {
  console.log('Registration blocked:', result.blockReasons);
}
```

### Login Verification

```typescript
const result = await sdk.verifyAtLogin({
  customerId: 'CUST-12345',
  ipAddress: req.ip,
  deviceFingerprint: getDeviceFingerprint(),
});

if (result.allowed) {
  if (result.requiresStepUp) {
    // Trigger MFA/2FA
  } else {
    // Allow login
  }
} else {
  console.log('Login blocked:', result.blockReasons);
}
```

### Transaction Verification

```typescript
const result = await sdk.verifyAtTransaction({
  customerId: 'CUST-12345',
  ipAddress: req.ip,
  amount: 5000,
  currency: 'USD',
  transactionType: 'withdrawal',
});

if (result.allowed) {
  // Process transaction
} else if (result.requiresApproval) {
  // Queue for manual review
} else {
  console.log('Transaction blocked:', result.blockReasons);
}
```

### CipherText (Client-Side Device Fingerprinting)

```typescript
import { generateCipherText } from 'vesant-sdk/geolocation';

// Collect device fingerprint + optional GPS on the client
const result = await generateCipherText({
  reason: 'login',
  requestLocation: true,
});

// Send to your backend
await fetch('/api/login', {
  body: JSON.stringify({ email, password, cipherText: result.cipherText }),
});
```

### Live Location Requests

```typescript
// Request a customer's live GPS location via SMS
const result = await sdk.requestCustomerLocation({
  customerId: 'CUST-12345',
  channel: 'sms',
  phone: '+1234567890',
  reason: 'Transaction verification',
});

console.log('Share link sent:', result.shareLink);
```

## Module-Specific Imports

Import only what you need to reduce bundle size:

### Geolocation Only

```typescript
import { GeolocationClient } from 'vesant-sdk/geolocation';

const geoClient = new GeolocationClient({
  baseURL: process.env.VESANT_API_URL,
  tenantId: process.env.VESANT_TENANT_ID,
  apiKey: process.env.VESANT_API_KEY,
});

const verification = await geoClient.verifyIP({
  ip_address: '8.8.8.8',
  user_id: 'user-123',
  event_type: 'login',
});

console.log('Country:', verification.location.country_iso);
console.log('Is VPN:', verification.location.is_vpn);
console.log('Risk level:', verification.risk_level);
```

### Risk Profile Only

```typescript
import { RiskProfileClient } from 'vesant-sdk/risk-profile';

const riskClient = new RiskProfileClient({
  baseURL: process.env.VESANT_API_URL,
  tenantId: process.env.VESANT_TENANT_ID,
  apiKey: process.env.VESANT_API_KEY,
});

const profile = await riskClient.getProfile('CUST-12345');
console.log('Risk score:', profile.risk_score);
console.log('Risk category:', profile.risk_category);
```

### KYC Only

```typescript
import { KycClient } from 'vesant-sdk/kyc';

const kycClient = new KycClient({
  baseURL: process.env.VESANT_API_URL,
  tenantId: process.env.VESANT_TENANT_ID,
  apiKey: process.env.VESANT_API_KEY,
});

const { link, kyc_id } = await kycClient.requestKycSubmitLink({
  user_id: 'user-123',
  redirect_url: 'https://yourapp.com/kyc-complete',
});
```

## React Hooks

```typescript
import {
  useRegistration,
  useLoginVerification,
  useTransactionVerification,
  useCipherText,
  useCustomerProfile,
} from 'vesant-sdk/react';

function RegistrationForm() {
  const { verifyRegistration, loading, error } = useRegistration(sdk, {
    onSuccess: (result) => {
      console.log('Registration approved!', result.profile);
      navigate('/dashboard');
    },
    onBlocked: (result) => {
      alert(`Registration blocked: ${result.blockReasons.join(', ')}`);
    },
  });

  const handleSubmit = async (formData) => {
    await verifyRegistration({
      customerId: formData.customerId,
      fullName: formData.fullName,
      emailAddress: formData.email,
      ipAddress: await getClientIP(),
    });
  };

  return (
    <form onSubmit={handleSubmit}>
      {/* Form fields */}
      <button disabled={loading}>
        {loading ? 'Verifying...' : 'Register'}
      </button>
      {error && <ErrorMessage>{error.message}</ErrorMessage>}
    </form>
  );
}
```

## Interceptors

```typescript
const sdk = new ComplianceClient({
  baseURL: process.env.VESANT_API_URL,
  tenantId: process.env.VESANT_TENANT_ID,
  apiKey: process.env.VESANT_API_KEY,
  interceptors: [
    {
      onRequest: (url, options) => {
        console.log(`[SDK] ${options.method || 'GET'} ${url}`);
        return options;
      },
      onResponse: (url, data) => {
        console.log(`[SDK] Response from ${url}`);
        return data;
      },
      onError: (url, error) => {
        console.error(`[SDK] Error from ${url}:`, error.message);
      },
    },
  ],
});
```

## AbortController

```typescript
const controller = new AbortController();

// Cancel after 5 seconds
setTimeout(() => controller.abort(), 5000);

const result = await sdk.verifyAtLogin(
  { customerId: 'CUST-12345', ipAddress: req.ip },
  { signal: controller.signal }
);
```

## Configuration

```typescript
interface ComplianceClientConfig {
  baseURL: string;              // Vesant API Gateway URL
  tenantId: string;             // Your tenant ID
  apiKey?: string;              // Your API key
  timeout?: number;             // Request timeout in ms (default: 10000)
  retries?: number;             // Retry attempts (default: 3)
  debug?: boolean;              // Enable debug logging (default: false)
  autoCreateProfiles?: boolean; // Auto-create risk profiles (default: true)
  interceptors?: Interceptor[]; // Request/response interceptors
  logger?: Logger;              // Custom logger instance
}
```

## API Methods

### ComplianceClient

| Method | Description |
|--------|-------------|
| `verifyAtRegistration(request)` | Verify new user registration |
| `verifyAtLogin(request)` | Verify user login |
| `verifyAtTransaction(request)` | Verify financial transaction |
| `verifyEvent(request)` | Generic event verification |
| `requestCustomerLocation(input)` | Request live GPS location from customer |
| `getLocationRequest(requestId)` | Get location request status |
| `listLocationRequests(filters)` | List location requests |
| `cancelLocationRequest(requestId)` | Cancel a pending location request |
| `updateCurrencyRates(rates)` | Update exchange rates for transaction risk |

### GeolocationClient

| Method | Description |
|--------|-------------|
| `verifyIP(request)` | Verify IP address and check compliance (**use this for allowed/blocked decisions**) |
| `checkCompliance(countryISO)` | Check jurisdiction compliance |
| `validateCipherText(cipherText, userId, eventType)` | Validate device fingerprint integrity (does **not** check jurisdiction rules) |
| `validateAndVerify(cipherText, ip, userId, eventType)` | Combined cipherText validation + IP verification |
| `getGPSConfig()` | Get GPS requirement config per event type |
| `createLocationRequest(request)` | Create a live location request |
| `captureLocation(token, capture)` | Submit location capture (customer-facing) |

> **Which API should I use?** For registration, login, and transaction flows, use `ComplianceClient` methods (`verifyAtRegistration`, `verifyAtLogin`, `verifyAtTransaction`). These orchestrate geolocation + risk profiling and return a single `allowed` decision. Only use `GeolocationClient` directly if you need low-level access to individual APIs.

### RiskProfileClient

| Method | Description |
|--------|-------------|
| `createProfile(request)` | Create customer risk profile |
| `getProfile(customerId)` | Get profile by customer ID (exact match) |
| `updateProfile(profileId, updates)` | Update customer profile |
| `getOrCreateProfile(customerId, request)` | Idempotent get-or-create |

### KycClient

| Method | Description |
|--------|-------------|
| `requestKycSubmitLink(request)` | Generate a KYC submission link |
| `checkKycStatus(request)` | Check KYC verification status |
| `submitVerification(request)` | Submit document verification |
| `listKycRequests(filters)` | List KYC requests |
| `getPreferences()` | Get KYC preferences |
| `listAlerts(filters)` | List KYC alerts |

## Documentation

For detailed documentation, see the [docs](./docs) directory:

- [Quick Start](./docs/getting-started/quick-start.md)
- [Configuration](./docs/getting-started/configuration.md)
- [Authentication](./docs/getting-started/authentication.md)
- [Registration Flow](./docs/guides/registration.md)
- [Transaction Verification](./docs/guides/transactions.md)
- [Next.js Integration](./docs/guides/nextjs.md)
- [React Hooks](./docs/react-hooks/overview.md)
- [Error Handling & Types](./docs/advanced/types.md)
- [Security](./docs/advanced/security.md)

## License

MIT

## Support

For support, contact your Vesant account representative.
