# Prompt PII Redactor and Reversible Anonymizer (`n4d.h1dr/llm-pii-vault`) Actor

Scrubs emails, credit cards, phone numbers, API keys, and SSNs from LLM prompts and provides a reversible mapping table.

- **URL**: https://apify.com/n4d.h1dr/llm-pii-vault.md
- **Developed by:** [Nadim Hider](https://apify.com/n4d.h1dr) (community)
- **Security:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $1.50 / 1,000 prompt scrubbeds

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Prompt PII Redactor and Reversible Anonymizer

A deterministic, high-throughput security proxy Actor for Large Language Models (LLMs) and autonomous workflows. Automatically scrubs Personal Identifiable Information (PII) including emails, phone numbers, credit card numbers (verified via Luhn checksum), US Social Security Numbers (SSN), IPv4 addresses, and sensitive API keys.

***

### Why Use This Actor?

Sending customer personally identifiable information into public LLM APIs violates GDPR, HIPAA, and enterprise compliance standards.

This Actor provides reversible anonymization:

- Replaces PII entities with numbered tokens (`<EMAIL_1>`, `<PHONE_1>`, `<CREDIT_CARD_1>`).
- Returns a deterministic mapping dictionary alongside the sanitized prompt.
- Enables your downstream agent to substitute original values back into the LLM output.
- Operates locally with zero external network transmission.

***

### Dual Output Envelope (Agent Native)

Every response contains structured redactions and a markdown summary ready for context injection:

```json
{
  "id": "prompt-001",
  "success": true,
  "meta": {
    "processing_time_ms": 1.2,
    "items_count": 1
  },
  "data": {
    "sanitized_text": "Hello, my name is John Doe. My email is <EMAIL_1>, my phone number is <PHONE_1>, and my corporate card is <CREDIT_CARD_1>. Also here is my secret token: <API_KEY_1>.",
    "entities_found_count": 4,
    "entity_breakdown": {
      "EMAIL": 1,
      "PHONE": 1,
      "CREDIT_CARD": 1,
      "API_KEY": 1,
      "SSN": 0,
      "IP_ADDRESS": 0
    },
    "detected_types": ["EMAIL", "PHONE", "CREDIT_CARD", "API_KEY"],
    "mapping_table": {
      "<EMAIL_1>": "john.doe@enterprise.com",
      "<PHONE_1>": "+1-555-839-2918",
      "<CREDIT_CARD_1>": "4532-0150-1234-5678",
      "<API_KEY_1>": "sk-live-99a81b2c3d4e5f"
    }
  },
  "markdown_summary": "### PII Vault Scrubbing Summary\n- Total Entities Redacted: 4\n- Detected Types: EMAIL, PHONE, CREDIT_CARD, API_KEY\n- Latency: 1.2ms\n"
}
```

***

### Input Schema

| Field | Type | Default | Description |
|---|---|---|---|
| `items` | Array of Objects | *Sample Prompt* | Array of objects with `id` and `text` to scrub. |
| `mask_credit_cards` | Boolean | `true` | Validates numbers via Luhn checksum before masking. |
| `mask_api_keys` | Boolean | `true` | Detects OpenAI, AWS, GitHub, and Slack secret keys. |

***

### Pay-Per-Event (PPE) Pricing

- Primary Event: `prompt-scrubbed`
- Cost: **$0.0015 per prompt** ($1.50 per 1,000 prompts).
- Initial 5 seconds of compute are waived via `apify-actor-start`.

***

### Integration Code in 10+ Languages

#### cURL

```bash
curl -X POST "https://api.apify.com/v2/acts/n4d.h1dr~llm-pii-vault/runs?token=YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"items": [{"id": "p1", "text": "Contact me at alice@bank.com with card 4532015012345678"}]}'
```

#### Python

```python
from apify_client import ApifyClient

client = ApifyClient("YOUR_API_TOKEN")
run = client.actor("n4d.h1dr/llm-pii-vault").call(run_input={
    "items": [{"id": "p1", "text": "Call me at +1-555-234-5678"}]
})
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(item["data"]["sanitized_text"])
```

#### Node.js / TypeScript

```typescript
import { ApifyClient } from 'apify-client';

const client = new ApifyClient({ token: 'YOUR_API_TOKEN' });
const run = await client.actor('n4d.h1dr/llm-pii-vault').call({
  items: [{ id: 'p1', text: 'Email is user@example.com' }]
});
const { items } = await client.dataset(run.defaultDatasetId).listItems();
console.log(items[0].data.mapping_table);
```

#### Go

```go
package main
import (
    "bytes"
    "net/http"
)
func main() {
    url := "https://api.apify.com/v2/acts/n4d.h1dr~llm-pii-vault/runs?token=YOUR_API_TOKEN"
    payload := []byte(`{"items": [{"id": "p1", "text": "Email user@domain.com"}]}`)
    http.Post(url, "application/json", bytes.NewBuffer(payload))
}
```

#### Ruby

```ruby
require 'net/http'
require 'json'
uri = URI('https://api.apify.com/v2/acts/n4d.h1dr~llm-pii-vault/runs?token=YOUR_API_TOKEN')
req = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json')
req.body = { items: [{ id: 'p1', text: 'Email me at admin@corp.com' }] }.to_json
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }
```

#### PHP

```php
<?php
$ch = curl_init('https://api.apify.com/v2/acts/n4d.h1dr~llm-pii-vault/runs?token=YOUR_API_TOKEN');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
    'items' => [['id' => '1', 'text' => 'Call 555-123-4567']]
]));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res = curl_exec($ch);
```

#### Java

```java
import java.net.URI;
import java.net.http.*;
public class Main {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.apify.com/v2/acts/n4d.h1dr~llm-pii-vault/runs?token=YOUR_API_TOKEN"))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString("{\"items\": [{\"id\": \"1\", \"text\": \"Card 4532015012345678\"}]}"))
            .build();
        client.send(request, HttpResponse.BodyHandlers.ofString());
    }
}
```

#### C# (.NET)

```csharp
using System.Net.Http.Json;
var client = new HttpClient();
var payload = new { items = new[] { new { id = "1", text = "Card 4532015012345678" } } };
await client.PostAsJsonAsync("https://api.apify.com/v2/acts/n4d.h1dr~llm-pii-vault/runs?token=YOUR_API_TOKEN", payload);
```

#### Rust

```rust
use reqwest::Client;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new();
    let res = client.post("https://api.apify.com/v2/acts/n4d.h1dr~llm-pii-vault/runs?token=YOUR_API_TOKEN")
        .json(&serde_json::json!({"items": [{"id": "1", "text": "Call me"}]}))
        .send().await?;
    Ok(())
}
```

#### Swift

```swift
import Foundation
var request = URLRequest(url: URL(string: "https://api.apify.com/v2/acts/n4d.h1dr~llm-pii-vault/runs?token=YOUR_API_TOKEN")!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try? JSONSerialization.data(withJSONObject: ["items": [["id": "1", "text": "Sensitive data"]]])
URLSession.shared.dataTask(with: request).resume()
```

#### n8n / Make.com Webhook Node

Add an HTTP Request node in n8n or Make:

- Method: `POST`
- URL: `https://api.apify.com/v2/acts/n4d.h1dr~llm-pii-vault/runs?token=YOUR_API_TOKEN`
- Body Parameters: `{ "items": [ { "id": "={{ $json.id }}", "text": "={{ $json.user_prompt }}" } ] }`

# Actor input Schema

## `items` (type: `array`):

List of prompt objects containing raw text with sensitive personal identifiable information to scrub.

## `mask_credit_cards` (type: `boolean`):

Validates Visa, Mastercard, and Amex numbers via the Luhn checksum algorithm before masking.

## `mask_api_keys` (type: `boolean`):

Detects OpenAI sk-, AWS AKIA, GitHub ghp\_, and Slack xoxb tokens.

## Actor input object example

```json
{
  "items": [
    {
      "id": "prompt-001",
      "text": "Hello, my name is John Doe. My email is john.doe@enterprise.com, my phone number is +1-555-839-2918, and my corporate card is 4532-0150-1234-5678. Also here is my secret token: sk-live-99a81b2c3d4e5f."
    }
  ],
  "mask_credit_cards": true,
  "mask_api_keys": true
}
```

# Actor output Schema

## `results` (type: `string`):

No description

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "items": [
        {
            "id": "prompt-001",
            "text": "Hello, my name is John Doe. My email is john.doe@enterprise.com, my phone number is +1-555-839-2918, and my corporate card is 4532-0150-1234-5678. Also here is my secret token: sk-live-99a81b2c3d4e5f."
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("n4d.h1dr/llm-pii-vault").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "items": [{
            "id": "prompt-001",
            "text": "Hello, my name is John Doe. My email is john.doe@enterprise.com, my phone number is +1-555-839-2918, and my corporate card is 4532-0150-1234-5678. Also here is my secret token: sk-live-99a81b2c3d4e5f.",
        }] }

# Run the Actor and wait for it to finish
run = client.actor("n4d.h1dr/llm-pii-vault").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "items": [
    {
      "id": "prompt-001",
      "text": "Hello, my name is John Doe. My email is john.doe@enterprise.com, my phone number is +1-555-839-2918, and my corporate card is 4532-0150-1234-5678. Also here is my secret token: sk-live-99a81b2c3d4e5f."
    }
  ]
}' |
apify call n4d.h1dr/llm-pii-vault --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,n4d.h1dr/llm-pii-vault"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/lB5WK9TMduNpuaeTQ/builds/We58O0OKHxzjSTeK4/openapi.json
