npm package: @paytweed/compliance-sdk
Description: SDK for Compliance API
Latest version: 3.0.0

# @paytweed/compliance-sdk

[![npm version](https://badge.fury.io/js/%40paytweed%2Fcompliance-sdk.svg)](https://badge.fury.io/js/%40paytweed%2Fcompliance-sdk)

SDK for Compliance API

## Table of Contents

- [Installation](#installation)
- [API Client Usage](#api-client-usage)
  - [Configuration](#configuration)
  - [Available Services](#available-services)
  - [Working Example For API requests](#working-example-for-api-requests)
- [Webhook Handling](#webhook-handling)
  - [Webhook Headers](#webhook-headers)
  - [Verifying Signatures](#verifying-signatures)
  - [Event Types](#event-types)
- [Development](#development)
  - [Building](#building)
  - [Testing](#testing)
- [Contributing](#contributing)
- [License](#license)

## Installation

You can install the package using npm or yarn:

```bash
npm install @paytweed/compliance-sdk
# or
yarn add @paytweed/compliance-sdk
```

---

## API Client Usage

This section covers how to use the SDK to interact with the Compliance API endpoints.

### Configuration

First, import the `ComplianceClient` and configure it with your API details:

```typescript
import { ComplianceClient, OpenAPI } from '@paytweed/compliance-sdk';

// Configure API key (or other authentication methods) via Headers
// OpenAPI.TOKEN = 'YOUR_API_KEY'; // Deprecated: Use HEADERS instead

// Configure the base URL
OpenAPI.BASE = 'https://api-compliance.prod.paytweed.com'; 

// Configure Headers for Authentication (Recommended)
OpenAPI.HEADERS = {
  "Authorization": `Bearer ${process.env.API_TOKEN}` 
};

const client = new ComplianceClient();

// Or configure directly in the constructor
const clientWithConfig = new ComplianceClient({
    BASE: "https://api-compliance.prod.paytweed.com",
    HEADERS: {
        "Authorization": `Bearer ${process.env.API_TOKEN}`
    }
});
```

### Available Services

The SDK provides access to the following services via the `ComplianceClient` instance:

*   `client.alerts`: Manage compliance alerts.
*   `client.clients`: Manage individual and corporate clients.
*   `client.health`: Check the health status of the API.
*   `client.operations`: Manage financial operations (deposits, withdrawals, trades).
*   `client.transactions`: Manage transactions.

Each service exposes methods corresponding to the API endpoints. Refer to the type definitions (exported from `index.ts` and within the `models/` and `services/` directories) for detailed request and response structures.

### Working Example For API requests
```ts
import { ClientRiskDto, ComplianceClient, CreateIndividualClientDto, IndividualClientCustomFieldDataDto, IndividualClientGeneralInformationDto } from "@paytweed/compliance-sdk";
import { v4 as uuidv4 } from 'uuid';

async function main() {
    const client = new ComplianceClient({
        BASE: "https://api-compliance.prod.paytweed.com",
        HEADERS: {
            "Authorization": `Bearer ${process.env.API_TOKEN}` // Use Authorization header
        }
    });

    const referenceId = uuidv4();
    const { id } = await client.clients.createIndividualClient({
        referenceId,
        activityStatus: CreateIndividualClientDto.activityStatus.ACTIVE,
        accountStatus: CreateIndividualClientDto.accountStatus.APPROVED,
        currentRisk: {
            score: 75,
            level: ClientRiskDto.level.HIGH,
            reason: "Multiple high-value transactions in high-risk jurisdictions",
            calculatedAt: "2023-08-15T14:30:00Z"
        },
        tags: ["high-value", "vip-client"],
        controls: ["enhanced-due-diligence", "quarterly-review"],
        address: {
            addressLine1: "123 Main Street",
            addressLine2: "Apt 4B",
            city: "New York",
            country: "USA",
            postalCode: "10001"
        },
        adverseMedia: {
            isAdverseMedia: false
        },
        application: {
            submittedAt: "2023-08-15T10:30:00Z",
            onboardedAt: "2023-08-20T14:00:00Z",
            onboardingRisk: {
                score: 75,
                level: ClientRiskDto.level.HIGH,
                reason: "Multiple high-value transactions in high-risk jurisdictions",
                calculatedAt: "2023-08-15T14:30:00Z"
            },
            nextPeriodicReview: "2024-08-20T14:00:00Z"
        },
        riskHistory: [{
            score: 75,
            level: ClientRiskDto.level.HIGH,
            reason: "Multiple high-value transactions in high-risk jurisdictions",
            calculatedAt: "2023-08-15T14:30:00Z"
        }],
        contact: {
            emailAddress: "john.doe@example.com",
            phoneNumber: "+1-555-123-4567"
        },
        customFields: {
            additionalProp1: {
                label: "Preferred Contact Time",
                value: "Morning",
                category: IndividualClientCustomFieldDataDto.category.GENERAL
            },
            additionalProp2: {
                label: "Preferred Contact Time",
                value: "Morning",
                category: IndividualClientCustomFieldDataDto.category.GENERAL
            },
            additionalProp3: {
                label: "Preferred Contact Time",
                value: "Morning",
                category: IndividualClientCustomFieldDataDto.category.GENERAL
            }
        },
        financial: {
            annualDepositEstimate: "100000"
        },
        general: {
            firstName: "Yarin SDK",
            lastName: "Test",
            gender: IndividualClientGeneralInformationDto.gender.MALE,
            dateOfBirth: "1980-01-15",
            citizenship: "USA",
            personalId: "123-45-6789"
        },
        politicalExposure: {
            isPoliticallyExposed: false
        },
        sanctions: {
            isSanctioned: false
        },
        work: {
            occupation: "Software Engineer"
        }
    });

    console.log(id);
    await client.clients.updateIndividualClient(id, {
        activityStatus: CreateIndividualClientDto.activityStatus.NOT_ACTIVE,
    });
}

main();
```

---

## Webhook Handling

The SDK provides utilities for handling webhooks sent from the Compliance API.

### Webhook Headers

When receiving webhooks, inspect the following HTTP headers:

*   `x-hub-signature-256`: The HMAC SHA256 signature of the request payload. Used for verifying the webhook's authenticity. (See Verifying Signatures below).
*   `x-tweed-event`: The type of event that triggered the webhook (e.g., `individual_client.created`).
*   `x-tweed-hook-id`: The unique identifier of the webhook configuration that sent this request.
*   `x-tweed-delivery`: A unique identifier for this specific delivery attempt.

### Verifying Signatures

It's crucial to verify the signature of incoming webhooks to ensure they originated from the Compliance API and were not tampered with. Use the `verifyWebhookSignature` function exported from the SDK.

```typescript
import { verifyWebhookSignature } from '@paytweed/compliance-sdk';

async function verifyWebhookRequest(request: Request) { // Assuming a standard Request object
  const signature = request.headers.get('x-hub-signature-256'); 
  const payload = await request.text(); // Raw request body
  const secret = process.env.WEBHOOK_SECRET; // Your webhook secret

  if (!signature || !secret) {
      console.error("Missing signature or secret");
      // Return an error response (e.g., HTTP 400 Bad Request)
      return false; 
  }

  const isValid = await verifyWebhookSignature(secret, payload, signature);

  if (!isValid) {
    console.error('Invalid webhook signature');
    // Return an error response (e.g., HTTP 401 Unauthorized)
    return false;
  }

  console.log("Webhook signature verified successfully!");
  // Signature is valid, proceed with processing the webhook payload
  // const webhookEvent = JSON.parse(payload);
  // console.log('Received valid webhook:', webhookEvent.type);
  // ... process event ...
  return true;
}
```

### Event Types

The following webhook event types are available (defined in `WebhookEventType`):

*   `individual_client.created`: Triggered when an individual client is created.
*   `individual_client.updated`: Triggered when an individual client is updated.
*   `corporate_client.created`: Triggered when a corporate client is created.
*   `corporate_client.updated`: Triggered when a corporate client is updated.
*   `alert.created`: Triggered when an alert is created.
*   `alert.updated`: Triggered when an alert is updated.
*   `case.created`: Triggered when a case is created.
*   `case.updated`: Triggered when a case is updated.

The payload structure for each event type (`WebhookEvent`, `EntityCreatedPayload`, `EntityUpdatedPayload`) and the `WebhookEventType` enum can be imported from `@paytweed/compliance-sdk`.

For a practical example of how to set up a webhook handler, see the [Webhook Example](./docs/WEBHOOK_EXAMPLE.md).

---

## Development

### Building

To build the project locally:

```bash
yarn install
yarn build
```

### Testing

Run the tests using:

```bash
yarn test
```

---

## Contributing

Contributions are welcome! Please follow standard practices for pull requests.

## License

[MIT](LICENSE)