# 🛡️ VulnCheck SDK

**The definitive TypeScript/JavaScript SDK for the VulnCheck API**

[![npm version](https://badge.fury.io/js/vulncheck-sdk.svg)](https://badge.fury.io/js/vulncheck-sdk)
[![TypeScript](https://img.shields.io/badge/TypeScript-007ACC?style=flat&logo=typescript&logoColor=white)](https://www.typescriptlang.org/)
[![License: ISC](https://img.shields.io/badge/License-ISC-blue.svg)](https://opensource.org/licenses/ISC)
[![Test Status](https://img.shields.io/badge/tests-20%2F20%20passing-brightgreen)](https://github.com/vulncheck/vulncheck-sdk)

> **Comprehensive vulnerability intelligence at your fingertips**  
> Access enriched CVE data, threat intelligence, and security tooling with full TypeScript support and production-ready error handling.

---

## 🚀 **Quick Start**

```bash
# Install the SDK
npm install vulncheck-sdk

# Or with yarn
yarn add vulncheck-sdk
```

```typescript
import { VulnCheckClient } from 'vulncheck-sdk';

// Initialize the client
const client = new VulnCheckClient({
  apiKey: process.env.VULNCHECK_API_KEY,
  timeout: 30000,
  cache: true
});

// Get CVE details
const cve = await client.getCVE('CVE-2021-44228');
console.log(`${cve.id}: ${cve.descriptions[0].value}`);

// Search for Apache vulnerabilities
const apacheVulns = await client.getCVEsByCPE('cpe:2.3:a:apache:http_server:*');
console.log(`Found ${apacheVulns.data.length} Apache vulnerabilities`);

// Check npm package vulnerabilities
const npmVulns = await client.getCVEsByPURL('pkg:npm/lodash@4.17.20');
console.log(`Found ${npmVulns.data.cves.length} CVEs in lodash@4.17.20`);
```

---

## 📋 **Table of Contents**

- [Features](#-features)
- [Installation](#-installation)
- [Authentication](#-authentication)
- [API Coverage](#-api-coverage)
- [Usage Examples](#-usage-examples)
- [Advanced Features](#-advanced-features)
- [Error Handling](#-error-handling)
- [Testing](#-testing)
- [TypeScript Support](#-typescript-support)
- [Contributing](#-contributing)
- [License](#-license)

---

## ✨ **Features**

### 🔧 **Production Ready**
- **Full TypeScript support** with comprehensive type definitions
- **ESM & CommonJS** compatible for maximum compatibility
- **Comprehensive error handling** with specific error types
- **Automatic retries** with exponential backoff for resilience
- **Rate limiting protection** with built-in retry logic

### 🎯 **Complete API Coverage**
- **CVE Data Retrieval** - Get enriched vulnerability details
- **CPE & PURL Lookups** - Search by component identifiers
- **Index Management** - Access vulnerability databases
- **Backup & Bulk Data** - Download complete datasets
- **Threat Intelligence** - Security rules and IP/DNS intel
- **Utility Endpoints** - OpenAPI specs and metadata

### 🛡️ **Developer Experience**
- **Zero-config setup** with intelligent defaults
- **Comprehensive validation** for all inputs
- **Detailed error messages** with actionable information
- **Cursor-based pagination** for efficient data access
- **100% test coverage** with integration tests

---

## 📦 **Installation**

```bash
# Using npm
npm install vulncheck-sdk

# Using yarn
yarn add vulncheck-sdk

# Using pnpm
pnpm add vulncheck-sdk
```

### **Requirements**
- Node.js 16+ or modern browser
- Deno 1.0+ (full ES module support)
- VulnCheck API key ([get yours here](https://vulncheck.com))

### **Deno Support**
This SDK is fully compatible with Deno runtime. Import directly from npm:

```typescript
import { VulnCheckClient } from "npm:vulncheck-sdk@^0.1.3";

const client = new VulnCheckClient({
  apiKey: Deno.env.get("VULNCHECK_API_KEY")!
});

// Works exactly the same as Node.js
const cve = await client.getCVE('CVE-2021-44228');
```

---

## 🔐 **Authentication**

### **Environment Variables (Recommended)**
```bash
# .env file
VULNCHECK_API_KEY=your_api_key_here
VULNCHECK_BASE_URL=https://api.vulncheck.com  # optional
```

```typescript
import { VulnCheckClient } from 'vulncheck-sdk';

const client = new VulnCheckClient({
  apiKey: process.env.VULNCHECK_API_KEY!
});
```

### **Direct Configuration**
```typescript
const client = new VulnCheckClient({
  apiKey: 'your-api-key-here',
  baseURL: 'https://api.vulncheck.com', // optional
  timeout: 30000,                       // optional
  retryAttempts: 3,                     // optional
  cache: true                           // optional
});
```

---

## 🎯 **API Coverage**

### **CVE Data Retrieval**
```typescript
// Get specific CVE details
const cve = await client.getCVE('CVE-2021-44228');

// Get CVEs from specific index
const cves = await client.getCVEsFromIndex('vulncheck-nvd2', { limit: 100 });
```

### **CPE & PURL Lookups**
```typescript
// Find CVEs by CPE
const cpeResults = await client.getCVEsByCPE('cpe:2.3:a:apache:*');

// Find CVEs by Package URL
const purlResults = await client.getCVEsByPURL('pkg:npm/lodash@4.17.20');

// Search CPEs by criteria
const cpeSearch = await client.searchCPEs({ 
  vendor: 'apache', 
  product: 'http_server' 
});
```

### **Index Management**
```typescript
// List available indexes
const indexes = await client.getIndexes();

// Query specific index
const indexData = await client.queryIndex('adobe', { limit: 50 });
```

### **Backup & Bulk Data**
```typescript
// List available backups
const backups = await client.getBackups();

// Download backup data
const backupData = await client.downloadBackup('vulncheck-nvd2');
```

### **Threat Intelligence**
```typescript
// Get security rules
const rules = await client.getInitialAccessRules('malware');

// Get IP intelligence
const ipIntel = await client.getIPsByTags('malicious');

// Get DNS intelligence
const dnsIntel = await client.getDNSByTags('phishing');
```

### **Utility Endpoints**
```typescript
// Get OpenAPI specification
const apiSpec = await client.getOpenAPISpec();
```

---

## 💡 **Usage Examples**

### **Security Monitoring Dashboard**
```typescript
import { VulnCheckClient } from 'vulncheck-sdk';

class SecurityMonitor {
  private client: VulnCheckClient;

  constructor(apiKey: string) {
    this.client = new VulnCheckClient({ apiKey });
  }

  async checkPackageVulnerabilities(packageUrl: string) {
    try {
      const result = await this.client.getCVEsByPURL(packageUrl);
      
      return {
        package: packageUrl,
        vulnerabilities: result.data.cves.length,
        fixedIn: result.data.vulnerabilities.map(v => v.fixed_version),
        riskLevel: this.calculateRiskLevel(result.data.cves.length)
      };
    } catch (error) {
      console.error(`Error checking ${packageUrl}:`, error.message);
      return null;
    }
  }

  private calculateRiskLevel(vulnCount: number): 'low' | 'medium' | 'high' {
    if (vulnCount === 0) return 'low';
    if (vulnCount <= 2) return 'medium';
    return 'high';
  }
}

// Usage
const monitor = new SecurityMonitor(process.env.VULNCHECK_API_KEY!);
const result = await monitor.checkPackageVulnerabilities('pkg:npm/express@4.17.1');
```

### **Vulnerability Intelligence Pipeline**
```typescript
import { VulnCheckClient, CVEDetails } from 'vulncheck-sdk';

class VulnIntelligence {
  private client: VulnCheckClient;

  constructor(apiKey: string) {
    this.client = new VulnCheckClient({ apiKey });
  }

  async getHighSeverityVulns(limit: number = 100): Promise<CVEDetails[]> {
    const results = await this.client.getCVEsFromIndex('vulncheck-kev', { limit });
    
    return results.data.filter(cve => {
      // Filter for high severity vulnerabilities
      return cve.cisaExploitAdd || cve.vulncheckKEVExploitAdd;
    });
  }

  async enrichCVEData(cveId: string) {
    const cve = await this.client.getCVE(cveId);
    
    return {
      id: cve.id,
      description: cve.descriptions[0]?.value || 'No description',
      severity: cve.cisaVulnerabilityName ? 'CRITICAL' : 'HIGH',
      published: new Date(cve.published),
      exploitAvailable: !!cve.cisaExploitAdd,
      references: cve.references.map(ref => ref.url)
    };
  }
}
```

### **Automated Compliance Checking**
```typescript
import { VulnCheckClient } from 'vulncheck-sdk';

class ComplianceChecker {
  private client: VulnCheckClient;

  constructor(apiKey: string) {
    this.client = new VulnCheckClient({ apiKey });
  }

  async auditInfrastructure(components: string[]) {
    const results = await Promise.all(
      components.map(async (component) => {
        try {
          const vulns = await this.client.getCVEsByCPE(component);
          return {
            component,
            vulnerabilities: vulns.data.length,
            compliant: vulns.data.length === 0
          };
        } catch (error) {
          return {
            component,
            vulnerabilities: -1,
            compliant: false,
            error: error.message
          };
        }
      })
    );

    return {
      totalComponents: components.length,
      compliantComponents: results.filter(r => r.compliant).length,
      totalVulnerabilities: results.reduce((sum, r) => sum + Math.max(0, r.vulnerabilities), 0),
      results
    };
  }
}
```

---

## 🚀 **Advanced Features**

### **Pagination with Cursors**
```typescript
// Paginate through large datasets
let cursor: string | undefined;
const allResults = [];

do {
  const page = await client.getCVEsByCPE('cpe:2.3:a:apache:*', { 
    limit: 100, 
    cursor 
  });
  
  allResults.push(...page.data);
  cursor = page._meta.next_cursor;
} while (cursor);

console.log(`Retrieved ${allResults.length} total vulnerabilities`);
```

### **Error Handling with Retries**
```typescript
import { 
  VulnCheckClient, 
  VulnCheckRateLimitError,
  VulnCheckAuthError 
} from 'vulncheck-sdk';

const client = new VulnCheckClient({
  apiKey: process.env.VULNCHECK_API_KEY!,
  retryAttempts: 5,  // Retry up to 5 times
  timeout: 60000     // 60 second timeout
});

try {
  const cve = await client.getCVE('CVE-2021-44228');
  console.log('Success:', cve.id);
} catch (error) {
  if (error instanceof VulnCheckRateLimitError) {
    console.log(`Rate limited. Retry after ${error.retryAfter}ms`);
  } else if (error instanceof VulnCheckAuthError) {
    console.error('Authentication failed. Check your API key.');
  } else {
    console.error('Unexpected error:', error.message);
  }
}
```

### **Batch Operations**
```typescript
// Process multiple CVEs efficiently
const cveIds = ['CVE-2021-44228', 'CVE-2021-45046', 'CVE-2021-45105'];

const results = await Promise.allSettled(
  cveIds.map(id => client.getCVE(id))
);

results.forEach((result, index) => {
  if (result.status === 'fulfilled') {
    console.log(`${cveIds[index]}: ${result.value.descriptions[0]?.value}`);
  } else {
    console.error(`${cveIds[index]}: ${result.reason.message}`);
  }
});
```

---

## 🚨 **Error Handling**

The SDK provides comprehensive error handling with specific error types:

### **Error Types**
```typescript
import {
  VulnCheckError,           // Base error class
  VulnCheckAuthError,       // 401 authentication errors
  VulnCheckRateLimitError,  // 429 rate limiting errors
  VulnCheckNotFoundError,   // 404 not found errors
  VulnCheckValidationError, // 400 validation errors
  VulnCheckServerError      // 5xx server errors
} from 'vulncheck-sdk';
```

### **Error Handling Patterns**
```typescript
try {
  const cve = await client.getCVE('CVE-2021-44228');
} catch (error) {
  if (error instanceof VulnCheckRateLimitError) {
    // Handle rate limiting
    const retryAfter = error.retryAfter || 5000;
    await new Promise(resolve => setTimeout(resolve, retryAfter));
    // Retry the request
  } else if (error instanceof VulnCheckAuthError) {
    // Handle authentication error
    console.error('Check your API key');
  } else if (error instanceof VulnCheckValidationError) {
    // Handle validation error
    console.error('Invalid input:', error.message);
  } else {
    // Handle other errors
    console.error('Unexpected error:', error.message);
  }
}
```

---

## 🧪 **Testing**

### **Running Tests**
```bash
# Unit tests
npm test

# Integration tests (requires API key)
npm run test:integration

# All tests
npm run test:all

# Watch mode
npm run test:watch
```

### **Setting up Integration Tests**
```bash
# Create .env file
echo "VULNCHECK_API_KEY=your_api_key_here" > .env

# Run integration tests
npm run test:integration
```

### **Test Coverage**
The SDK includes comprehensive test coverage:
- ✅ **Unit tests** for all client methods
- ✅ **Integration tests** against live API
- ✅ **Error handling tests** for all error scenarios
- ✅ **Type validation tests** for TypeScript compatibility
- ✅ **Performance tests** for rate limiting and timeouts

---

## 🔷 **TypeScript Support**

### **Full Type Safety**
```typescript
import { VulnCheckClient, CVEDetails, PURLResults } from 'vulncheck-sdk';

// All methods are fully typed
const client = new VulnCheckClient({ apiKey: 'key' });

// TypeScript knows the exact shape of responses
const cve: CVEDetails = await client.getCVE('CVE-2021-44228');
const purlResult: PURLResults = await client.getCVEsByPURL('pkg:npm/lodash@4.17.20');

// Intellisense works perfectly
console.log(cve.id);                    // ✅ TypeScript knows this exists
console.log(cve.descriptions[0].value); // ✅ Nested properties are typed
console.log(purlResult.data.cves);      // ✅ Array types are correct
```

### **Generic Types**
```typescript
// Generic response type for custom processing
import { VulnCheckResponse } from 'vulncheck-sdk';

type CustomData = {
  id: string;
  name: string;
};

// Type-safe custom endpoint handling
const customResponse: VulnCheckResponse<CustomData> = await client.queryIndex('custom-index');
```

---

## 🎨 **Configuration Options**

```typescript
interface VulnCheckClientConfig {
  apiKey: string;           // Required: Your VulnCheck API key
  baseURL?: string;         // Optional: API base URL (default: https://api.vulncheck.com)
  timeout?: number;         // Optional: Request timeout in ms (default: 30000)
  retryAttempts?: number;   // Optional: Max retry attempts (default: 3)
  cache?: boolean;          // Optional: Enable response caching (default: false)
}
```

---

## 📖 **API Reference**

### **Client Methods**

| Method | Description | Returns |
|--------|-------------|---------|
| `getCVE(id)` | Get CVE details by ID | `Promise<CVEDetails>` |
| `getCVEsFromIndex(index, options?)` | Get CVEs from specific index | `Promise<CVESearchResults>` |
| `getCVEsByCPE(cpe, options?)` | Find CVEs by CPE | `Promise<CVESearchResults>` |
| `getCVEsByPURL(purl, options?)` | Find CVEs by Package URL | `Promise<PURLResults>` |
| `searchCPEs(criteria, options?)` | Search CPEs by criteria | `Promise<CPESearchResults>` |
| `getIndexes()` | List available indexes | `Promise<IndexList>` |
| `queryIndex(name, options?)` | Query specific index | `Promise<IndexResults>` |
| `getBackups()` | List available backups | `Promise<BackupList>` |
| `downloadBackup(name)` | Download backup data | `Promise<BackupData>` |
| `getInitialAccessRules(rules)` | Get security rules | `Promise<SecurityRules>` |
| `getIPsByTags(filter, options?)` | Get IP intelligence | `Promise<IPIntelligence>` |
| `getDNSByTags(filter, options?)` | Get DNS intelligence | `Promise<DNSIntelligence>` |
| `getOpenAPISpec()` | Get OpenAPI specification | `Promise<OpenAPIDocument>` |

### **Response Types**

All responses follow the VulnCheck API format:
```typescript
interface VulnCheckResponse<T> {
  _benchmark: number;
  _meta: {
    timestamp: string;
    index: string;
    limit: number;
    total_documents: number;
    sort: string;
    next_cursor?: string;
  };
  data: T[];
}
```

---

## 🌟 **Examples Repository**

Check out our [examples repository](https://github.com/vulncheck/vulncheck-sdk-examples) for real-world usage patterns:

- 🔍 **Security Scanning Tools**
- 📊 **Vulnerability Dashboards**
- 🤖 **Automated Compliance Checking**
- 📈 **Threat Intelligence Feeds**
- 🔔 **Alert Systems**

---

## 🤝 **Contributing**

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

### **Development Setup**
```bash
# Clone the repository
git clone https://github.com/vulncheck/vulncheck-sdk.git
cd vulncheck-sdk

# Install dependencies
npm install

# Build the project
npm run build

# Run tests
npm test

# Run integration tests (requires API key)
npm run test:integration
```

### **Development Commands**
```bash
npm run build        # Build the project
npm run dev          # Watch mode development
npm run test         # Run unit tests
npm run test:all     # Run all tests
npm run lint         # Run linting
npm run typecheck    # Run TypeScript checks
```

---

## 📄 **License**

This project is licensed under the ISC License - see the [LICENSE](LICENSE) file for details.

---

## 🆘 **Support**

- 📚 **Documentation**: [API Documentation](https://docs.vulncheck.com)
- 💬 **Community**: [Discord Server](https://discord.gg/vulncheck)
- 🐛 **Bug Reports**: [GitHub Issues](https://github.com/vulncheck/vulncheck-sdk/issues)
- 📧 **Email Support**: [support@vulncheck.com](mailto:support@vulncheck.com)

---

## 🎯 **Roadmap**

- [ ] **WebSocket Support** for real-time updates
- [ ] **CLI Tool** for command-line usage
- [ ] **Browser Optimization** for frontend applications
- [ ] **GraphQL Support** for flexible queries
- [ ] **Caching Layer** for improved performance
- [ ] **Plugin System** for custom extensions

---

<div align="center">

**Made with ❤️ by hrbrmstr**

[🌐 Website](https://vulncheck.com) • [📖 Docs](https://docs.vulncheck.com) • [💬 Discord](https://discord.gg/vulncheck) • [🐦 Twitter](https://twitter.com/vulncheck)

</div>
