@privacypal/sdk
v1.0.1
Published
PrivacyPal SDK for encoding and decoding sensitive data using Privacy Twins
Maintainers
Readme
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
npm install @privacypal/sdkQuick Start
Natural Language Prompts
PrivacyPal works seamlessly with natural language prompts and instructions:
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 [email protected] 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 [email protected]..."
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 restoredSimple PII List
You can also encode simple lists of sensitive data:
const simpleData = "John Doe, SSN: 123-45-6789, email: [email protected]";
const result = await client.encode({
data: simpleData,
sourceContainer: "customer_db.users",
metadata: { rowId: "1001" }
});API Reference
Client Initialization
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 PIIsourceContainer- 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 twinscontinuationId- ID for later decodingtransformations- Array of transformations appliedstatistics- Processing statistics
Example:
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:
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 responsedata- Data containing synthetic twinssensitiveHashes- Array of original value hashes to decodeauthorization- Authorization object with token and purpose
Returns:
decodedData- Data with twins replaced by originalstransformations- Array of decoded transformationsauditLog- Audit informationstatistics- Processing statistics
Example:
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:
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 namesEMAIL_ADDRESS- Email addressesPHONE_NUMBER- Phone numbersUS_SSN- US Social Security NumbersCREDIT_CARD- Credit card numbersLOCATION- Addresses and locationsDATE_TIME- Dates and timestampsIP_ADDRESS- IP addresses- And more...
Error Handling
The SDK throws descriptive errors for various scenarios:
try {
const result = await client.encode({ data: "..." });
} catch (error) {
console.error('Encoding failed:', error.message);
}Best Practices
- Store Continuation IDs - Always save the
continuationIdfor later decoding - Store Hashes - Keep track of
originalHashvalues from transformations for selective decoding - Authorization Purpose - Provide clear, specific purposes for audit trails
- Batch Processing - Use
encodeBatchfor multiple records to improve performance - 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
- Documentation: docs.privacypal.com
