## Helper Library for CTX Cyber Threat Intelligence API

Node.js TypeScript unofficial helper library for CTX Cyber Threat Intelligence API

## Disclaimer

- Unofficial helper library: This project is community-maintained and not affiliated with ctx.io.
- Use of this library requires a valid ctx.io account and acceptance of ctx.io’s API Terms of Service. This library does not grant rights to ctx.io’s API or data.
- Trademarks and brand names belong to their respective owners.

## Installation

```bash
npm install libctx
```

## Quick Start

```typescript
import { CTXClient } from 'libctx';

const client = new CTXClient({ apiKey: 'your-api-key' });

// Get file report by hash
const report = await client.ioc.getFileReport('sha256-hash');
console.log(report.detect, report.threatTypes);

// Get IP report
const ipReport = await client.ioc.getIPReport('156.236.72.121');
console.log(ipReport.aptThreatActors);

// Get domain report
const domainReport = await client.ioc.getDomainReport('malicious.com');
console.log(domainReport.aptCampaigns);
```

## Configuration

```typescript
const client = new CTXClient({
  apiKey: 'your-api-key',      // Required
  baseUrl: 'https://api.ctx.io/v1',  // Optional (default)
  timeout: 30000,              // Optional (default: 30s)
});
```

## Modules

### IoC Intelligence (`client.ioc`)

File, IP, and Domain analysis with IoC relationships.

```typescript
// File operations
await client.ioc.uploadFile('./malware.exe');
await client.ioc.uploadFile(buffer, { fileName: 'sample.exe' });
await client.ioc.downloadFile('sha256-hash');
await client.ioc.getFileReport('sha256-hash');

// IP/Domain reports
await client.ioc.getIPReport('1.2.3.4');
await client.ioc.getDomainReport('example.com');

// Similar files & IoC relationships
await client.ioc.getSimilarFiles('sha256-hash');
await client.ioc.getAssociatedIoCs('sha256-hash');
await client.ioc.getIPAssociatedIoCs('1.2.3.4');
await client.ioc.getDomainAssociatedIoCs('example.com');

// Search by tag
await client.ioc.searchByTag('ransomware', { limit: 100 });
await client.ioc.searchByTag(['trojan', 'downloader']);
```

### APT Intelligence (`client.apt`)

Campaign reports and threat actor information.

```typescript
// Campaign report
await client.apt.getCampaignReport('threat--uuid');

// Campaigns by IoC
await client.apt.getFileCampaigns('sha256-hash');
await client.apt.getDomainCampaigns('malicious.com');

// Campaigns by threat actor (name or MITRE ATT&CK G-ID)
await client.apt.getThreatActorCampaigns('Lazarus Group');
await client.apt.getThreatActorCampaigns('G0032');

// Campaigns by country
await client.apt.getAttackerCountryCampaigns('KP');  // North Korea
await client.apt.getVictimCountryCampaigns('KR');    // South Korea

// Search campaigns by tag
await client.apt.searchCampaignsByTags('ransomware');
await client.apt.searchCampaignsByTags(['apt', 'backdoor']);
```

### Total Intelligence (`client.total`)

Combined IoC + APT intelligence in a single request.

```typescript
// Get complete intelligence report
const fileReport = await client.total.getFileReport('sha256-hash');
console.log(fileReport.ioc);  // IoC intelligence
console.log(fileReport.apt);  // APT intelligence

const ipReport = await client.total.getIPReport('1.2.3.4');
const domainReport = await client.total.getDomainReport('example.com');
```

### Search (`client.search`)

Advanced search capabilities.

```typescript
// Submit search request
const result = await client.search.advancedSearch({
  iocType: 'file',  // 'file' | 'ip' | 'domain'
  query: 'tags:Ransomware AND threat_types:Trojan',
  cursor: 'optional-cursor-for-pagination',
});

console.log(result.reqId);      // Request ID for retrieving results
console.log(result.totalCount); // Total matching results
console.log(result.files);      // File results (when iocType is 'file')

// Get search results by request ID
const results = await client.search.getSearchResults(result.reqId);
```

### Feed (`client.feed`)

Threat intelligence feeds by date. Feed data is returned in NDJSON format.

**Date Formats:** `YYYY-MM-DD HH`, `YYYYMMDDHH`, `YYYY-MM-DD HH:mm`, `YYYYMMDDHHmm`

```typescript
// IoC Feeds
const files = await client.feed.getFileFeed('2024-04-09 11');
const domains = await client.feed.getDomainFeed('2024040911');
const urls = await client.feed.getURLFeed('2024-04-09 11:30');

// File feed contains rich data
files.items.forEach((file) => {
  console.log(file.hash.sha256);
  console.log(file.detect);
  console.log(file.attackTechniques);      // MITRE ATT&CK
  console.log(file.iocRelation);           // Related IPs, domains, files
  console.log(file.aptThreatActors);       // Associated threat actors
  console.log(file.aptCampaigns);          // Associated campaigns
});

// Campaign Feeds
await client.feed.getThreatActorFeed('G0032', '2024-04-09 11');
await client.feed.getAttackerCountryFeed('KP', '2024-04-09 11');
await client.feed.getVictimCountryFeed('KR', '2024-04-09 11');
await client.feed.getCampaignTagFeed('ransomware', '2024-04-09 11');
```

## API Reference

### IoC Intelligence

| Method | Description |
|--------|-------------|
| `uploadFile(path \| buffer, options?)` | Upload file for analysis |
| `downloadFile(hash)` | Download file by hash |
| `getFileReport(hash)` | Get file analysis report |
| `getIPReport(ip)` | Get IP analysis report |
| `getDomainReport(domain)` | Get domain analysis report |
| `getSimilarFiles(hash)` | Get similar files by hash |
| `getAssociatedIoCs(hash)` | Get IoCs associated with file |
| `getIPAssociatedIoCs(ip)` | Get IoCs associated with IP |
| `getDomainAssociatedIoCs(domain)` | Get IoCs associated with domain |
| `searchByTag(tags, options?)` | Search files by tag(s) |

### APT Intelligence

| Method | Description |
|--------|-------------|
| `getCampaignReport(ctxId)` | Get campaign report by ID |
| `getFileCampaigns(hash)` | Get campaigns associated with file |
| `getDomainCampaigns(domain)` | Get campaigns associated with domain |
| `getThreatActorCampaigns(actor)` | Get campaigns by threat actor |
| `getAttackerCountryCampaigns(country)` | Get campaigns by attacker country |
| `getVictimCountryCampaigns(country)` | Get campaigns targeting country |
| `searchCampaignsByTags(tags)` | Search campaigns by tag(s) |

### Total Intelligence

| Method | Description |
|--------|-------------|
| `getFileReport(hash)` | Get combined IoC + APT report for file |
| `getIPReport(ip)` | Get combined IoC + APT report for IP |
| `getDomainReport(domain)` | Get combined IoC + APT report for domain |

### Search

| Method | Description |
|--------|-------------|
| `advancedSearch(options)` | Submit advanced search query |
| `getSearchResults(reqId)` | Get search results by request ID |

### Feed

| Method | Description |
|--------|-------------|
| `getFileFeed(date)` | Get malicious file feed |
| `getDomainFeed(date)` | Get malicious domain feed |
| `getURLFeed(date)` | Get malicious URL feed |
| `getThreatActorFeed(actor, date)` | Get campaigns by threat actor |
| `getAttackerCountryFeed(country, date)` | Get campaigns by attacker country |
| `getVictimCountryFeed(country, date)` | Get campaigns targeting country |
| `getCampaignTagFeed(tag, date)` | Get campaigns by tag |

## Error Handling

```typescript
import { CTXClient, ApiError, ValidationError, TimeoutError } from 'libctx';

try {
  const report = await client.ioc.getFileReport('invalid-hash');
} catch (error) {
  if (error instanceof ValidationError) {
    console.log('Invalid input:', error.message);
  } else if (error instanceof ApiError) {
    console.log('API error:', error.message, error.statusCode);
  } else if (error instanceof TimeoutError) {
    console.log('Request timed out');
  }
}
```

## Types

All types are exported from the package:

```typescript
import {
  // Client & Config
  CTXClient,
  CTXConfig,

  // Errors
  CTXError,
  ApiError,
  ValidationError,
  TimeoutError,

  // IoC Types
  FileReportResult,
  IPReportResult,
  DomainReportResult,
  AttackTechnique,
  SimilarFile,
  AssociatedFile,
  AssociatedIP,
  AssociatedDomain,

  // APT Types
  CampaignReportResult,
  CampaignThreatActor,
  CampaignVictims,
  FileCampaignsResult,
  ThreatActorCampaignsResult,

  // Total Types
  TotalFileReportResult,
  TotalIPReportResult,
  TotalDomainReportResult,

  // Search Types
  AdvancedSearchRequestOptions,
  AdvancedSearchRequestResult,
  AdvancedSearchResponseResult,

  // Feed Types
  FileFeedResult,
  DomainFeedResult,
  URLFeedResult,
  ThreatActorFeedResult,
  AttackerCountryFeedResult,
  VictimCountryFeedResult,
  CampaignTagFeedResult,
} from 'libctx';
```

## Licensing & Compliance

- Project license: MIT (see LICENSE).
- Dependencies: `form-data` (MIT), `typescript` (Apache-2.0), `@types/node` (MIT) — all compatible with MIT.
- API Terms: Use of this SDK and any data retrieved is subject to ctx.io’s API Terms of Service.

## License

MIT — see LICENSE
