npm package: @privacypal/sdk
Description: PrivacyPal SDK for encoding and decoding sensitive data using Privacy Twins
Author: PrivacyPal
Latest version: 1.0.1

# PrivacyPal SDK

Official JavaScript/TypeScript SDK for the PrivacyPal Data Twins API.

## Overview

PrivacyPal SDK provides a simple interface for encoding sensitive data into synthetic "privacy twins" and decoding them back to original values with proper authorization. This enables safe handling of PII (Personally Identifiable Information) in your agents and applications.

## Features

- 🔒 **Secure PII Handling** - Automatically detects and replaces sensitive data with synthetic twins
- 🔄 **Bidirectional Flow** - Encode sensitive data and decode it back when authorized
- 📦 **Batch Processing** - Process multiple records efficiently
- 🎯 **Type-Safe** - Full TypeScript support with comprehensive types
- 🚀 **Easy Integration** - Simple, intuitive API

## Installation

```bash
npm install @privacypal/sdk
```

## Quick Start

### Natural Language Prompts

PrivacyPal works seamlessly with **natural language prompts and instructions**:

```typescript
import { PrivacyPalClient } from '@privacypal/sdk';

// Initialize the client
const client = new PrivacyPalClient({
  apiUrl: 'https://api.privacypal.ai',
  apiKey: 'your-jwt-token'
});

// Your natural language prompt with embedded PII
const prompt = `
  I want to analyze the average credit debt that John Doe would experience 
  being that his credit is poor even though his income is high. When completed 
  draft an email to john@email.com so we can send this report to him.
`;

// Encode: Automatically detects and protects PII
const encodeResult = await client.encode({
  data: prompt,
  sourceContainer: "ai_prompts.credit_analysis"
});

console.log('Protected:', encodeResult.encodedData);
// "...analyze the average credit debt that Jane Smith would experience..."
// "...draft an email to jane.smith@example.com..."

console.log('Continuation ID:', encodeResult.continuationId);
console.log('PII Protected:', encodeResult.transformations.length, 'entities');

// Decode back to original (with authorization)
const decodeResult = await client.decode({
  continuationId: encodeResult.continuationId,
  data: encodeResult.encodedData,
  sensitiveHashes: encodeResult.transformations.map(t => t.originalHash),
  authorization: {
    token: 'your-jwt-token',
    purpose: 'Credit analysis report generation'
  }
});

console.log('Original:', decodeResult.decodedData);
// Exact original prompt perfectly restored
```

### Simple PII List

You can also encode simple lists of sensitive data:

```typescript
const simpleData = "John Doe, SSN: 123-45-6789, email: john@company.com";

const result = await client.encode({
  data: simpleData,
  sourceContainer: "customer_db.users",
  metadata: { rowId: "1001" }
});
```

## API Reference

### Client Initialization

```typescript
const client = new PrivacyPalClient({
  apiUrl: string,     // PrivacyPal API base URL
  apiKey: string,     // JWT access token
  timeout?: number    // Optional request timeout (default: 30000ms)
});
```

### Encoding

#### `encode(params: EncodeSingleParams): Promise<EncodeResponse>`

Encode a single data item containing sensitive information.

**Parameters:**
- `data` - Input text containing potential PII
- `sourceContainer` - Source identifier (e.g., "customer_db.users")
- `sourceElement` - Element identifier (e.g., "personal_info")
- `metadata` - Additional metadata (rowId, sourceTable, etc.)
- `scoreThreshold` - PII detection threshold (default: 0.35)
- `language` - Language code (default: "en")
- `continuationId` - Optional ID for correlation

**Returns:**
- `encodedData` - Data with PII replaced by synthetic twins
- `continuationId` - ID for later decoding
- `transformations` - Array of transformations applied
- `statistics` - Processing statistics

**Example:**
```typescript
const result = await client.encode({
  data: "Patient: Alice Johnson, DOB: 03/15/1985, SSN: 987-65-4321",
  sourceContainer: "medical_db.patients",
  metadata: {
    rowId: "P12345",
    recordType: "patient_intake"
  }
});
```

#### `encodeBatch(params: EncodeBatchParams): Promise<EncodeBatchResponse>`

Encode multiple data items in a single request. All items share the same continuationId.

**Example:**
```typescript
const result = await client.encodeBatch({
  items: [
    {
      data: "Employee: Bob Williams, SSN: 111-22-3333",
      sourceContainer: "hr_db.employees",
      metadata: { rowId: "E001" }
    },
    {
      data: "Employee: Carol Davis, SSN: 444-55-6666",
      sourceContainer: "hr_db.employees",
      metadata: { rowId: "E002" }
    }
  ]
});
```

### Decoding

#### `decode(params: DecodeParams): Promise<DecodeResponse>`

Decode synthetic twins back to original sensitive data (requires authorization).

**Parameters:**
- `continuationId` - ID from the encoding response
- `data` - Data containing synthetic twins
- `sensitiveHashes` - Array of original value hashes to decode
- `authorization` - Authorization object with token and purpose

**Returns:**
- `decodedData` - Data with twins replaced by originals
- `transformations` - Array of decoded transformations
- `auditLog` - Audit information
- `statistics` - Processing statistics

**Example:**
```typescript
const result = await client.decode({
  continuationId: "abc-123-def",
  data: encodeResult.encodedData,
  sensitiveHashes: encodeResult.transformations.map(t => t.originalHash),
  authorization: {
    token: 'jwt-token',
    purpose: 'Medical records review for patient care'
  }
});
```

### Dataset Management

#### `getDatasetTwins(continuationId: string): Promise<GetDatasetTwinsResponse>`

Retrieve all data twins for a specific dataset.

**Example:**
```typescript
const result = await client.getDatasetTwins("abc-123-def");
console.log(`Found ${result.count} twins`);
result.twins.forEach(twin => {
  console.log(twin.entityType, twin.catalogItemId);
});
```

### Configuration Methods

#### `updateApiKey(newApiKey: string): void`

Update the API key for authentication.

#### `updateApiUrl(newApiUrl: string): void`

Update the API base URL.

#### `getConfig(): Readonly<PrivacyPalConfig>`

Get the current configuration.

## Entity Types

The SDK detects and handles various PII entity types:

- `PERSON` - Person names
- `EMAIL_ADDRESS` - Email addresses
- `PHONE_NUMBER` - Phone numbers
- `US_SSN` - US Social Security Numbers
- `CREDIT_CARD` - Credit card numbers
- `LOCATION` - Addresses and locations
- `DATE_TIME` - Dates and timestamps
- `IP_ADDRESS` - IP addresses
- And more...

## Error Handling

The SDK throws descriptive errors for various scenarios:

```typescript
try {
  const result = await client.encode({ data: "..." });
} catch (error) {
  console.error('Encoding failed:', error.message);
}
```

## Best Practices

1. **Store Continuation IDs** - Always save the `continuationId` for later decoding
2. **Store Hashes** - Keep track of `originalHash` values from transformations for selective decoding
3. **Authorization Purpose** - Provide clear, specific purposes for audit trails
4. **Batch Processing** - Use `encodeBatch` for multiple records to improve performance
5. **Error Handling** - Always wrap API calls in try-catch blocks

## Performance

Typical latencies:
- **Encoding**: 70-280ms per record
- **Decoding**: 20-65ms per record
- **Batch Encoding**: 50-200ms average per record
- **Get Dataset Twins**: 10-30ms

## License

MIT

## Support

For issues and questions:
- GitHub: [privacypal-cloud](https://github.com/yourusername/privacypal-cloud)
- Documentation: [docs.privacypal.com](https://docs.privacypal.com)