npm package: @ismalicious/sdk
Description: Official JavaScript/TypeScript SDK for the isMalicious threat intelligence API
Author: isMalicious
Latest version: 0.1.0

# @ismalicious/sdk

[![npm version](https://img.shields.io/npm/v/@ismalicious/sdk.svg)](https://www.npmjs.com/package/@ismalicious/sdk)
[![npm downloads](https://img.shields.io/npm/dm/@ismalicious/sdk.svg)](https://www.npmjs.com/package/@ismalicious/sdk)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue.svg)](https://www.typescriptlang.org/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

Official JavaScript/TypeScript SDK for the [isMalicious](https://ismalicious.com) threat intelligence API.

## Installation

```bash
npm install @ismalicious/sdk
# or
yarn add @ismalicious/sdk
# or
pnpm add @ismalicious/sdk
```

## Quick Start

```typescript
import { IsMalicious } from "@ismalicious/sdk";

const client = new IsMalicious({
  apiKey: "your-api-key",
  apiSecret: "your-api-secret",
});

// Check if a domain is malicious
const result = await client.check("suspicious-domain.com");
console.log(result.malicious); // true or false
console.log(result.reputation); // 0-100 risk score
```

> **Note**: Get your API key and secret from your [isMalicious dashboard](https://ismalicious.com/app/account). The credentials are automatically Base64 encoded by the SDK for authentication.

## Features

- **Full TypeScript support** with comprehensive type definitions
- **Automatic retry** with exponential backoff
- **Rate limit handling** with built-in tracking
- **Multiple entity types**: domains, IPs, and file hashes
- **Enrichment levels**: basic, standard, and full intelligence

## Usage

### Check a Domain or IP

```typescript
// Basic check
const result = await client.check("example.com");

// With full enrichment
const enriched = await client.check("8.8.8.8", {
  enrichment: "full",
});

// Access detailed information
console.log(enriched.riskScore?.score); // Risk score 0-100
console.log(enriched.classification?.primary); // Threat category
console.log(enriched.confidence?.level); // 'low' | 'medium' | 'high'
```

### Check a File Hash

```typescript
// Supports MD5, SHA1, and SHA256
const hashResult = await client.checkHash("d41d8cd98f00b204e9800998ecf8427e");

console.log(hashResult.malicious);
console.log(hashResult.hashInfo?.fileType);
console.log(hashResult.hashInfo?.detectionStats);
```

### Bulk Check

```typescript
const bulkResult = await client.checkBulk([
  "suspicious-domain.com",
  "8.8.8.8",
  "d41d8cd98f00b204e9800998ecf8427e",
]);

console.log(
  `${bulkResult.maliciousCount} of ${bulkResult.totalChecked} are malicious`
);

for (const item of bulkResult.results) {
  console.log(`${item.entity}: ${item.malicious ? "MALICIOUS" : "clean"}`);
}
```

### Search

```typescript
const searchResult = await client.search("phishing");
console.log(searchResult.hits); // Array of matching domains
```

### Get Blocklist

```typescript
// Get blocklist in different formats
const hostsBlocklist = await client.getBlocklist({
  type: "malware",
  format: "hosts",
});

const adguardBlocklist = await client.getBlocklist({
  type: "phishing",
  format: "adguard",
});
```

## Configuration Options

```typescript
const client = new IsMalicious({
  // Required: Your API key
  apiKey: "your-api-key",

  // Required: Your API secret
  apiSecret: "your-api-secret",

  // Optional: Custom base URL (default: https://ismalicious.com/api)
  baseUrl: "https://ismalicious.com/api",

  // Optional: Request timeout in ms (default: 30000)
  timeout: 30000,

  // Optional: Number of retry attempts (default: 3)
  retries: 3,

  // Optional: Custom fetch implementation
  fetch: customFetch,
});
```

## Check Options

```typescript
interface CheckOptions {
  // Enrichment level: 'basic' | 'standard' | 'full'
  enrichment?: EnrichmentLevel;

  // Include IntelOwl analysis (slower, more comprehensive)
  intelowl?: boolean;

  // Track this request in your report history
  trackReports?: boolean;
}
```

## Error Handling

```typescript
import {
  IsMalicious,
  AuthenticationError,
  RateLimitError,
  ValidationError,
} from "@ismalicious/sdk";

try {
  const result = await client.check("example.com");
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error("Invalid API key");
  } else if (error instanceof RateLimitError) {
    console.error(`Rate limited. Retry after ${error.retryAfter} seconds`);
  } else if (error instanceof ValidationError) {
    console.error(`Invalid input: ${error.message}`);
  }
}
```

## Rate Limiting

The SDK automatically tracks rate limit information from API responses:

```typescript
// After making a request
const result = await client.check("example.com");

// Access rate limit info
const rateLimit = client.getRateLimitInfo();
console.log(
  `${rateLimit?.remaining} of ${rateLimit?.limit} requests remaining`
);
console.log(`Resets at: ${rateLimit?.reset}`);
```

## Response Types

### CheckResponse

```typescript
interface CheckResponse {
  malicious: boolean;
  reputation: number; // 0-100
  apiVersion: string;
  enrichmentLevel?: "basic" | "standard" | "full";
  processingTime?: number;
  sources?: MaliciousSource[];
  riskScore?: RiskScore;
  classification?: ThreatClassification;
  confidence?: ConfidenceScore;
  geo?: GeoLocation;
  whois?: WhoisInfo;
  certificates?: CertificateInfo[];
  hashInfo?: HashInfo;
  mitre?: MITREMapping;
}
```

## Modules

The SDK provides specialized modules for different API capabilities:

### Monitoring

Watch and unwatch domains/IPs for threat notifications:

```typescript
// Watch a domain
await client.monitoring.watch({
  entity: "suspicious-domain.com",
  type: "domain",
  notify: true,
});

// List watched entities
const watched = await client.monitoring.list();

// Unwatch an entity
await client.monitoring.unwatch({ entity: "suspicious-domain.com" });

// Toggle notifications
await client.monitoring.toggleNotify({
  entity: "suspicious-domain.com",
  notify: false,
});
```

### AI Analysis

Get AI-powered threat analysis with MITRE ATT&CK mapping:

```typescript
// Analyze a domain
const analysis = await client.ai.analyze({
  entity: "suspicious-domain.com",
  entityType: "domain",
  context: "Found in phishing email",
});

console.log(analysis.threatAssessment);
console.log(analysis.mitreTechniques);
console.log(analysis.recommendations);

// Stream analysis in real-time
const stream = await client.ai.analyzeStream({
  entity: "malware-site.com",
  entityType: "domain",
});

for await (const event of stream) {
  console.log(event.type, event.data);
}
```

### Real-time Stream

Subscribe to real-time threat feeds:

```typescript
// Subscribe to threat stream
const subscription = await client.stream.subscribe(
  {
    severity: ["critical", "high"],
    categories: ["malware", "ransomware"],
    entityTypes: ["domain", "ip"],
  },
  {
    onEvent: (event) => {
      console.log(`New threat: ${event.entity} - ${event.category}`);
    },
    onError: (error) => {
      console.error("Stream error:", error);
    },
  }
);

// Later: unsubscribe
subscription.unsubscribe();
```

### Ransomware Intelligence

Access ransomware victim data and statistics:

```typescript
// Get ransomware feed
const feed = await client.ransomware.getFeed({
  limit: 50,
  groups: ["lockbit", "blackcat"],
});

// Get statistics
const stats = await client.ransomware.getStats();
console.log(`Total victims: ${stats.totalVictims}`);

// Check if a domain was a ransomware victim
const check = await client.ransomware.check("company.com");
```

### CVE/Vulnerability Lookup

Search and retrieve CVE information:

```typescript
// Search CVEs
const results = await client.cve.search({
  query: "remote code execution",
  severity: "critical",
  limit: 10,
});

// Get recent CVEs
const recent = await client.cve.getRecent({ limit: 20 });

// Get specific CVE details
const cve = await client.cve.get("CVE-2024-1234");
```

### Webhooks

Manage webhook notifications:

```typescript
// Create a webhook
const webhook = await client.webhooks.create({
  url: "https://your-app.com/webhook",
  events: ["threat.new", "threat.updated"],
  secret: "your-webhook-secret",
});

// List webhooks
const webhooks = await client.webhooks.list();

// Update webhook
await client.webhooks.update(webhook.id, {
  events: ["threat.new"],
});

// Delete webhook
await client.webhooks.delete(webhook.id);
```

### Reports

Save and export threat reports:

```typescript
// Save a report
const report = await client.reports.save({
  entity: "malicious-domain.com",
  entityType: "domain",
  title: "Investigation Report",
  notes: "Found during incident response",
});

// List saved reports
const reports = await client.reports.list();

// Export report as PDF
const pdf = await client.reports.export(report.id, {
  format: "pdf",
});

// Delete report
await client.reports.delete(report.id);
```

### TAXII (STIX/TAXII 2.1)

Access threat intelligence in STIX format:

```typescript
// Get API root info
const apiRoot = await client.taxii.getApiRoot();

// List collections
const collections = await client.taxii.getCollections();

// Get objects from a collection
const objects = await client.taxii.getObjects("indicators", {
  type: ["indicator", "malware"],
  limit: 100,
});

// Get specific object
const indicator = await client.taxii.getObject(
  "indicators",
  "indicator--12345"
);
```

## Requirements

- Node.js 18+ (or provide a custom `fetch` implementation)

## License

MIT