@neuraldlp/sdk
v1.0.0
Published
Official JavaScript/TypeScript SDK for NeuralDLP - AI Privacy & Security Layer
Maintainers
Readme
NeuralDLP JavaScript/TypeScript SDK
Official JavaScript/TypeScript SDK for NeuralDLP - AI Privacy & Security Layer.
Protect your AI applications from data leakage, PII exposure, and security threats with real-time inspection, tokenization, and monitoring.
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
npm install @neuraldlp/sdk
# or
yarn add @neuraldlp/sdk
# or
pnpm add @neuraldlp/sdkQuick Start
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:
const inspection = await client.inspectInput(
'Contact me at [email protected]',
{
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:
// 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:
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:
const rehydrated = await client.rehydrate(
tokenizedResponse,
tokenization.mapping_id
);
console.log(rehydrated.original_text); // Original data restored
console.log(rehydrated.confidence); // 0.95Usage Examples
OpenAI Integration
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
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
// Process multiple texts in parallel
const texts = [
'Email: [email protected]',
'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
// 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
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
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.
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.
const result = await client.inspectOutput(
aiResponse,
'map_xyz789'
);tokenize(text, entities, options?)
Tokenize sensitive entities in text.
const result = await client.tokenize(text, entities, {
ttl: 3600, // TTL in seconds
preserveFormatting: true,
});rehydrate(text, mappingId, tenantId?)
Rehydrate tokenized text back to original.
const result = await client.rehydrate(
tokenizedText,
'map_xyz789'
);getMappingStatus(mappingId, tenantId?)
Get status of a stored mapping.
const status = await client.getMappingStatus('map_xyz789');
console.log(status.access_count);
console.log(status.is_expired);deleteMapping(mappingId, tenantId?)
Delete a stored mapping.
await client.deleteMapping('map_xyz789');getTenantStats(startDate, endDate, tenantId?)
Get tenant usage statistics.
const stats = await client.getTenantStats(
'2025-01-01',
'2025-01-31'
);
console.log(stats.total_inspections);health()
Check API health.
const isHealthy = await client.health();Helper Functions
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 secretsError Handling
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:
import type {
InspectionResult,
TokenizationResult,
RehydrationResult,
Entity,
Threat,
MappingStatus,
TenantStats,
} from '@neuraldlp/sdk';Environment Variables
# .env
NEURALDLP_API_KEY=your_api_key
NEURALDLP_BASE_URL=https://api.neuraldlp.com
NEURALDLP_TENANT_ID=your-tenantBest Practices
Always inspect before sending to AI
const inspection = await client.inspectInput(userInput); if (inspection.risk_score > 70) { // Handle high-risk content }Store mapping IDs for rehydration
// Save mapping ID with session/context session.mappingId = tokenization.mapping_id;Check output for leakage
const outputCheck = await client.inspectOutput(aiResponse, mappingId); if (outputCheck.leakage_detected) { // Log incident, notify security team }Use appropriate TTLs
// Short sessions: 1 hour // Long sessions: 24 hours // Stored data: Custom based on retention policy const tokenized = await client.tokenize(text, entities, { ttl: 3600 });Implement error handling
try { // NeuralDLP operations } catch (error) { // Graceful degradation or retry logic }
Examples
Check out the examples directory for more:
Development
# Install dependencies
npm install
# Build
npm run build
# Watch mode
npm run dev
# Run tests
npm test
# Lint
npm run lint
# Format
npm run formatTroubleshooting
API Returns 500 on Tokenize/Rehydrate
Symptom: POST /v1/transform/tokenize or /v1/transform/rehydrate returns 500 error
Common Causes:
Invalid encryption key: Ensure
ENCRYPTION_KEYin.envis a valid 32-byte Fernet keypython3 -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"Redis connection failure: Verify
REDIS_URLis correct and Redis is runningdocker exec neuraldlp-redis redis-cli ping # Should return PONGEnvironment not loaded: Use
restart-api.shscript which properly loads.envvariables./restart-api.sh
Response Format Mismatches
The SDK includes automatic response normalization to handle API field name differences:
- API returns
transformed_text→ SDK providestokenized_text - API returns
rehydrated_text→ SDK providesoriginal_text - API returns
tokens→ SDK providesplaceholders
This ensures consistent interface regardless of API version changes.
Contributing
Contributions welcome! Please read our Contributing Guide.
License
MIT © NeuralDLP
Support
- 📧 Email: [email protected]
- 💬 Discord: discord.gg/neuraldlp
- 📖 Docs: docs.neuraldlp.com
- 🐛 Issues: GitHub Issues
