npm package: @neuraldlp/sdk
Description: Official JavaScript/TypeScript SDK for NeuralDLP - AI Privacy & Security Layer
Author: NeuralDLP
Latest version: 1.0.0

# NeuralDLP JavaScript/TypeScript SDK

Official JavaScript/TypeScript SDK for [NeuralDLP](https://neuraldlp.com) - AI Privacy & Security Layer.

Protect your AI applications from data leakage, PII exposure, and security threats with real-time inspection, tokenization, and monitoring.

[![npm version](https://badge.fury.io/js/%40neuraldlp%2Fsdk.svg)](https://www.npmjs.com/package/@neuraldlp/sdk)
[![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## Features

- 🔍 **Real-time Inspection** - Detect PII, secrets, and threats in inputs/outputs
- 🔐 **Smart Tokenization** - Replace sensitive data with secure tokens
- 🔄 **Automatic Rehydration** - Restore original data when needed
- 🛡️ **Risk-Based Actions** - ALLOW, TOKENIZE, or BLOCK based on risk scores
- 📊 **Analytics & Monitoring** - Track usage, threats, and compliance
- ⚡ **High Performance** - Built with async/await, retry logic, and error handling
- 🎯 **TypeScript First** - Full type safety and IntelliSense support
- 🌐 **Universal** - Works in Node.js, browsers, and edge runtimes

## Installation

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

## Quick Start

```typescript
import { NeuralDLP } from '@neuraldlp/sdk';

// Initialize client
const client = new NeuralDLP({
  apiKey: 'your_api_key',
  baseUrl: 'https://api.neuraldlp.com',
});

// Inspect input for sensitive data
const result = await client.inspectInput('My SSN is 123-45-6789');

console.log(result.risk_score);          // 98
console.log(result.recommended_action);  // "BLOCK"
console.log(result.entities.length);     // 1

// Tokenize sensitive data
const tokenized = await client.tokenize(
  'My SSN is 123-45-6789',
  result.entities
);

console.log(tokenized.tokenized_text);   // "My SSN is SSN_ABC123"
console.log(tokenized.mapping_id);       // "map_xyz789"
```

## Core Concepts

### 1. Input Inspection

Analyze text before sending to AI models:

```typescript
const inspection = await client.inspectInput(
  'Contact me at john@example.com',
  {
    tenantId: 'your-tenant',
    context: { userId: 'user123' }
  }
);

// Check risk level
if (inspection.risk_score > 70) {
  console.log('High risk detected!');
}

// Check detected entities
inspection.entities.forEach(entity => {
  console.log(`${entity.type}: ${entity.value}`);
});
```

### 2. Tokenization

Replace sensitive data with secure tokens:

```typescript
// Inspect first
const inspection = await client.inspectInput(text);

// Tokenize if needed
if (inspection.recommended_action === 'TOKENIZE') {
  const tokenization = await client.tokenize(text, inspection.entities, {
    ttl: 3600,  // 1 hour
  });
  
  // Send tokenized text to AI
  const aiResponse = await callAI(tokenization.tokenized_text);
}
```

### 3. Output Inspection

Check AI responses for data leakage:

```typescript
const outputInspection = await client.inspectOutput(
  aiResponse,
  tokenization.mapping_id
);

if (outputInspection.leakage_detected) {
  console.warn('⚠️ AI leaked sensitive data!');
}
```

### 4. Rehydration

Restore original data in responses:

```typescript
const rehydrated = await client.rehydrate(
  tokenizedResponse,
  tokenization.mapping_id
);

console.log(rehydrated.original_text);  // Original data restored
console.log(rehydrated.confidence);     // 0.95
```

## Usage Examples

### OpenAI Integration

```typescript
import { NeuralDLP, InspectionResultHelper } from '@neuraldlp/sdk';
import OpenAI from 'openai';

const neuraldlp = new NeuralDLP({ apiKey: 'your_key' });
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

async function protectedChat(userMessage: string) {
  // 1. Inspect input
  const inspection = await neuraldlp.inspectInput(userMessage);
  
  // 2. Block if high risk
  if (InspectionResultHelper.isBlocked(inspection)) {
    throw new Error('Message blocked due to security policy');
  }
  
  // 3. Tokenize if needed
  let messageToSend = userMessage;
  let mappingId;
  
  if (InspectionResultHelper.shouldTokenize(inspection)) {
    const tokenization = await neuraldlp.tokenize(
      userMessage,
      inspection.entities
    );
    messageToSend = tokenization.tokenized_text;
    mappingId = tokenization.mapping_id;
  }
  
  // 4. Call OpenAI
  const completion = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: messageToSend }],
  });
  
  let response = completion.choices[0].message.content;
  
  // 5. Rehydrate response
  if (mappingId) {
    const rehydration = await neuraldlp.rehydrate(response, mappingId);
    response = rehydration.original_text;
  }
  
  return response;
}
```

### Express Middleware

```typescript
import express from 'express';
import { NeuralDLP, InspectionResultHelper } from '@neuraldlp/sdk';

const app = express();
const neuraldlp = new NeuralDLP({ apiKey: 'your_key' });

app.use(express.json());

// NeuralDLP middleware
app.use(async (req, res, next) => {
  if (!req.body?.message) return next();
  
  const inspection = await neuraldlp.inspectInput(req.body.message);
  
  // Block high-risk requests
  if (InspectionResultHelper.isBlocked(inspection)) {
    return res.status(403).json({
      error: 'Request blocked',
      risk_score: inspection.risk_score,
    });
  }
  
  // Attach inspection to request
  req.neuraldlp = { inspection };
  next();
});

app.post('/api/chat', (req, res) => {
  // Your route handler
  res.json({ message: 'Success' });
});

app.listen(3000);
```

### Batch Processing

```typescript
// Process multiple texts in parallel
const texts = [
  'Email: john@example.com',
  'SSN: 123-45-6789',
  'Safe message',
];

const results = await Promise.all(
  texts.map(text => client.inspectInput(text))
);

results.forEach((result, i) => {
  console.log(`Text ${i + 1}: Risk ${result.risk_score}`);
});
```

### Next.js API Route

```typescript
// pages/api/chat.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { NeuralDLP } from '@neuraldlp/sdk';

const neuraldlp = new NeuralDLP({
  apiKey: process.env.NEURALDLP_API_KEY!,
});

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const { message } = req.body;
  
  // Inspect input
  const inspection = await neuraldlp.inspectInput(message);
  
  if (inspection.risk_score > 70) {
    return res.status(403).json({ error: 'High risk detected' });
  }
  
  // Process message...
  res.json({ success: true });
}
```

### Cloudflare Workers

```typescript
import { NeuralDLP } from '@neuraldlp/sdk';

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const neuraldlp = new NeuralDLP({
      apiKey: env.NEURALDLP_API_KEY,
    });
    
    const { message } = await request.json();
    const inspection = await neuraldlp.inspectInput(message);
    
    return Response.json({
      risk_score: inspection.risk_score,
      action: inspection.recommended_action,
    });
  },
};
```

## API Reference

### Client Configuration

```typescript
interface NeuralDLPConfig {
  apiKey: string;              // Your API key (required)
  baseUrl?: string;            // API base URL (default: http://localhost:8000)
  timeout?: number;            // Request timeout in ms (default: 30000)
  tenantId?: string;           // Default tenant ID (default: 'default')
  retries?: number;            // Retry attempts (default: 3)
  retryDelay?: number;         // Delay between retries in ms (default: 1000)
}
```

### Methods

#### `inspectInput(text, options?)`

Inspect input text for sensitive data and threats.

```typescript
const result = await client.inspectInput('My SSN is 123-45-6789', {
  tenantId: 'your-tenant',
  policyIds: ['policy-1'],
  context: { userId: 'user123' }
});
```

#### `inspectOutput(text, mappingId?, options?)`

Inspect AI output for data leakage.

```typescript
const result = await client.inspectOutput(
  aiResponse,
  'map_xyz789'
);
```

#### `tokenize(text, entities, options?)`

Tokenize sensitive entities in text.

```typescript
const result = await client.tokenize(text, entities, {
  ttl: 3600,              // TTL in seconds
  preserveFormatting: true,
});
```

#### `rehydrate(text, mappingId, tenantId?)`

Rehydrate tokenized text back to original.

```typescript
const result = await client.rehydrate(
  tokenizedText,
  'map_xyz789'
);
```

#### `getMappingStatus(mappingId, tenantId?)`

Get status of a stored mapping.

```typescript
const status = await client.getMappingStatus('map_xyz789');
console.log(status.access_count);
console.log(status.is_expired);
```

#### `deleteMapping(mappingId, tenantId?)`

Delete a stored mapping.

```typescript
await client.deleteMapping('map_xyz789');
```

#### `getTenantStats(startDate, endDate, tenantId?)`

Get tenant usage statistics.

```typescript
const stats = await client.getTenantStats(
  '2025-01-01',
  '2025-01-31'
);
console.log(stats.total_inspections);
```

#### `health()`

Check API health.

```typescript
const isHealthy = await client.health();
```

### Helper Functions

```typescript
import { InspectionResultHelper } from '@neuraldlp/sdk';

InspectionResultHelper.isSafe(result);         // Check if ALLOW
InspectionResultHelper.shouldTokenize(result); // Check if TOKENIZE
InspectionResultHelper.isBlocked(result);      // Check if BLOCK
InspectionResultHelper.hasHighRisk(result);    // Check risk >= 70
InspectionResultHelper.hasPII(result);         // Check for PII
InspectionResultHelper.hasSecrets(result);     // Check for secrets
```

## Error Handling

```typescript
import {
  NeuralDLPError,
  AuthenticationError,
  RateLimitError,
  ValidationError,
  NotFoundError,
  NetworkError,
  ServerError,
  TimeoutError,
} from '@neuraldlp/sdk';

try {
  const result = await client.inspectInput(text);
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error('Invalid API key');
  } else if (error instanceof RateLimitError) {
    console.error('Rate limit exceeded');
    console.log(`Retry after ${error.retryAfter} seconds`);
  } else if (error instanceof ValidationError) {
    console.error('Invalid input:', error.details);
  } else if (error instanceof NetworkError) {
    console.error('Network error');
  }
}
```

## TypeScript Support

The SDK is written in TypeScript and provides full type definitions:

```typescript
import type {
  InspectionResult,
  TokenizationResult,
  RehydrationResult,
  Entity,
  Threat,
  MappingStatus,
  TenantStats,
} from '@neuraldlp/sdk';
```

## Environment Variables

```bash
# .env
NEURALDLP_API_KEY=your_api_key
NEURALDLP_BASE_URL=https://api.neuraldlp.com
NEURALDLP_TENANT_ID=your-tenant
```

## Best Practices

1. **Always inspect before sending to AI**
   ```typescript
   const inspection = await client.inspectInput(userInput);
   if (inspection.risk_score > 70) {
     // Handle high-risk content
   }
   ```

2. **Store mapping IDs for rehydration**
   ```typescript
   // Save mapping ID with session/context
   session.mappingId = tokenization.mapping_id;
   ```

3. **Check output for leakage**
   ```typescript
   const outputCheck = await client.inspectOutput(aiResponse, mappingId);
   if (outputCheck.leakage_detected) {
     // Log incident, notify security team
   }
   ```

4. **Use appropriate TTLs**
   ```typescript
   // Short sessions: 1 hour
   // Long sessions: 24 hours
   // Stored data: Custom based on retention policy
   const tokenized = await client.tokenize(text, entities, { ttl: 3600 });
   ```

5. **Implement error handling**
   ```typescript
   try {
     // NeuralDLP operations
   } catch (error) {
     // Graceful degradation or retry logic
   }
   ```

## Examples

Check out the [examples](./examples) directory for more:

- [Basic Usage](./examples/basic-usage.ts)
- [OpenAI Integration](./examples/openai-integration.ts)
- [Express Middleware](./examples/express-middleware.ts)
- [Batch Processing](./examples/batch-processing.ts)

## Development

```bash
# Install dependencies
npm install

# Build
npm run build

# Watch mode
npm run dev

# Run tests
npm test

# Lint
npm run lint

# Format
npm run format
```

## Troubleshooting

### API Returns 500 on Tokenize/Rehydrate

**Symptom:** `POST /v1/transform/tokenize` or `/v1/transform/rehydrate` returns 500 error

**Common Causes:**
1. **Invalid encryption key**: Ensure `ENCRYPTION_KEY` in `.env` is a valid 32-byte Fernet key
   ```bash
   python3 -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
   ```

2. **Redis connection failure**: Verify `REDIS_URL` is correct and Redis is running
   ```bash
   docker exec neuraldlp-redis redis-cli ping  # Should return PONG
   ```

3. **Environment not loaded**: Use `restart-api.sh` script which properly loads `.env` variables
   ```bash
   ./restart-api.sh
   ```

### Response Format Mismatches

The SDK includes automatic response normalization to handle API field name differences:
- API returns `transformed_text` → SDK provides `tokenized_text`
- API returns `rehydrated_text` → SDK provides `original_text`
- API returns `tokens` → SDK provides `placeholders`

This ensures consistent interface regardless of API version changes.

## Contributing

Contributions welcome! Please read our [Contributing Guide](CONTRIBUTING.md).

## License

MIT © [NeuralDLP](https://neuraldlp.com)

## Support

- 📧 Email: support@neuraldlp.com
- 💬 Discord: [discord.gg/neuraldlp](https://discord.gg/neuraldlp)
- 📖 Docs: [docs.neuraldlp.com](https://docs.neuraldlp.com)
- 🐛 Issues: [GitHub Issues](https://github.com/neuraldlp/neuraldlp-sdk-js/issues)

## Links

- [Website](https://neuraldlp.com)
- [Documentation](https://docs.neuraldlp.com)
- [API Reference](https://docs.neuraldlp.com/api)
- [Python SDK](https://github.com/neuraldlp/neuraldlp-sdk-python)
- [Go SDK](https://github.com/neuraldlp/neuraldlp-sdk-go)