@corsa-labs/sdk
TypeScript icon, indicating that this package has built-in type declarations

3.4.0 • Public • Published

@corsa-labs/sdk

npm version

SDK for integrating with Corsa API

Table of Contents

Installation

You can install the package using npm or yarn:

npm install @corsa-labs/sdk
# or
yarn add @corsa-labs/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:

import { ComplianceClient, OpenAPI } from '@corsa-labs/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

import { ClientRiskDto, ComplianceClient, CreateIndividualClientDto, IndividualClientCustomFieldDataDto, IndividualClientGeneralInformationDto } from "@corsa-labs/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.

import { verifyWebhookSignature } from '@corsa-labs/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 @corsa-labs/sdk.

For a practical example of how to set up a webhook handler, see the Webhook Example.


Development

Building

To build the project locally:

yarn install
yarn build

Testing

Run the tests using:

yarn test

Contributing

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

License

MIT

Readme

Keywords

none

Package Sidebar

Install

npm i @corsa-labs/sdk

Weekly Downloads

27

Version

3.4.0

License

MIT

Unpacked Size

211 kB

Total Files

242

Last publish

Collaborators

  • yarintweed