# Anonymization

```typescript
import {
  Configuration,
  SensitiveDataProtectionApi,
} from "@quba/sensitive-data-protection"

const text = `Patient John Smith (SSN: 123-45-6789) was admitted to
  Dubai General Hospital on 2024-01-15. Contact: john.smith@email.com`

async function protectData(text: string) {
  // Pass your API key on every request via the x-api-key header.
  const api = new SensitiveDataProtectionApi(
    new Configuration({ headers: { "x-api-key": "quba_..." } }),
  )

  return await api.anonymizeText({
    text,
    rules: [
      {
        type: "replace",
        entities: [{ type: "model", value: "person" }],
        replacement: "[PATIENT]",
      },
      {
        type: "mask",
        entities: [{ type: "regex", value: "\\d{3}-\\d{2}-\\d{4}" }],
        masking_char: "*",
        chars_to_mask: 7,
        from_end: true,
      },
      {
        type: "redact",
        entities: [{ type: "model", value: "address" }],
      },
      {
        type: "sha256",
        entities: [{ type: "model", value: "email" }],
      },
    ],
  })
}

const response = await protectData(text)
console.log(response.text)
// Output: Patient [PATIENT] (SSN: ***-**-6789) was admitted to
// [REDACTED] on 2024-01-15. Contact: a1b2c3d4...
```

```python
from quba_sdp import Client, models
from quba_sdp.api import anonymize_text

text = """Patient John Smith (SSN: 123-45-6789) was admitted to
  Dubai General Hospital on 2024-01-15. Contact: john.smith@email.com"""

# base_url defaults to the production API; pass your key via headers.
client = Client(headers={"x-api-key": "quba_..."})

response = anonymize_text.sync(
    client=client,
    body=models.AnonymizeRequestBody(
        text=text,
        rules=[
            models.ReplaceRule(
                entities=[models.ModelEntity(value="person")],
                replacement="[PATIENT]",
            ),
            models.MaskRule(
                entities=[models.RegexEntity(value=r"\d{3}-\d{2}-\d{4}")],
                masking_char="*",
                chars_to_mask=7,
                from_end=True,
            ),
            models.RedactRule(entities=[models.ModelEntity(value="address")]),
            models.SHA256Rule(entities=[models.ModelEntity(value="email")]),
        ],
    ),
)

print(response.text)
# Output: Patient [PATIENT] (SSN: ***-**-6789) was admitted to
# [REDACTED] on 2024-01-15. Contact: a1b2c3d4...
```

Use `model` when you want the AI to find entity types automatically. Use `regex` when you need to target a specific pattern like an ID format or a date structure.

```typescript
// Model-based: AI finds the entity type
{ type: "model", value: "person" }

// Regex-based: matches your exact pattern
{ type: "regex", value: "\\d{3}-\\d{2}-\\d{4}" }
```

```python
# Model-based: AI finds the entity type
models.ModelEntity(value="person")

# Regex-based: matches your exact pattern
models.RegexEntity(value=r"\d{3}-\d{2}-\d{4}")
```

## Rules [#rules]

A rule tells the API **what to detect** and **how to anonymize it**. Every rule has two required parts:

* **`type`** — the anonymization operation to apply (`replace`, `redact`, `mask`, `sha256`, `sha512`, `encrypt`)
* **`entities`** — one or more targets to detect, each using either a model or a regex pattern

```typescript
{
  type: "replace",                                    // what to do
  entities: [{ type: "model", value: "person" }],     // what to find
  replacement: "[PATIENT]"                            // anonymization option
}
```

You pass an array of rules. Each rule is evaluated independently against the full text — multiple rules can match and anonymize different spans, including overlapping ones. Rules are applied in order.

### Entity Targets [#entity-targets]

Each entity in `entities` is either a model-based detection or a regex pattern:

| Type    | Description                   | Example                                            |
| ------- | ----------------------------- | -------------------------------------------------- |
| `model` | AI detects the entity type    | `{ type: "model", value: "person" }`               |
| `regex` | Your pattern matches the text | `{ type: "regex", value: "\\d{3}-\\d{2}-\\d{4}" }` |

A single rule can mix both:

```typescript
{
  type: "redact",
  entities: [
    { type: "model", value: "email" },
    { type: "regex", value: "[A-Z]{2}\\d{6}" },  // custom ID format
  ]
}
```

```python
models.RedactRule(
    entities=[
        models.ModelEntity(value="email"),
        models.RegexEntity(value=r"[A-Z]{2}\d{6}"),  # custom ID format
    ]
)
```

### Model Labels [#model-labels]

Model entities are plain labels in `snake_case`, such as `person`, `email`, `phone_number`, `address`, `card_number` or `api_key`. Common personal-data labels are detected most accurately; any other label also works, with less accuracy.

### Default Rules and Assigned Policies [#default-rules-and-assigned-policies]

`rules` is optional. Which rules run depends on the caller:

1. **An assigned policy.** An admin can assign a policy to an API key or a team member in the dashboard. It applies to every call made with that key or from the browser extension; a request that also sends `rules` or `confidence_threshold` is refused with `403`. The dashboard playground can still try other rules.
2. **The request's `rules`**, when nothing is assigned.
3. **The default rules**, when neither: personal, health, payment and credential identifiers, each replaced with its label in capitals and brackets, so `John Smith` becomes `[PERSON]`. `/scan` without `entities` detects the same labels. The default covers:

   * the HIPAA Safe Harbor identifiers found in text: names, addresses, dates and ages, phone and fax numbers, emails, IP addresses, URLs, ID, account, license, certificate, medical record and health plan numbers, vehicle and device identifiers, and biometric identifiers;
   * passport and tax ID numbers;
   * card numbers, CVVs and expiry dates, IBANs, bank accounts and routing numbers;
   * passwords, API keys, access tokens, secrets and recovery codes.

### Confidence Threshold [#confidence-threshold]

Model-based detections include a `score` (0.0–1.0) representing the AI's confidence. The `confidence_threshold` parameter filters out low-confidence detections.

```typescript
await api.anonymizeText({
  text: "...",
  rules: [...],
  confidence_threshold: 0.8, // only apply rules to high-confidence detections
})
```

```python
anonymize_text.sync(
    client=client,
    body=models.AnonymizeRequestBody(
        text="...",
        rules=[...],
        confidence_threshold=0.8,  # only apply rules to high-confidence detections
    ),
)
```

* Default: `0.5`
* Regex matches are always applied — threshold does not affect them
* Set higher (e.g. `0.8`) to reduce false positives; set lower to catch more entities

## Anonymization Types [#anonymization-types]

### Replace [#replace]

Replace detected entities with a custom string:

```typescript
{
  type: "replace",
  entities: [{ type: "model", value: "person" }],
  replacement: "[REDACTED]"   // default: "****"
}
```

```python
models.ReplaceRule(
    entities=[models.ModelEntity(value="person")],
    replacement="[REDACTED]",  # default: "****"
)
```

### Redact [#redact]

Remove detected entities entirely:

```typescript
{
  type: "redact",
  entities: [{ type: "model", value: "email" }]
}
```

```python
models.RedactRule(entities=[models.ModelEntity(value="email")])
```

### Mask [#mask]

Mask part of the detected entity:

```typescript
{
  type: "mask",
  entities: [{ type: "model", value: "phone_number" }],
  masking_char: "*",     // default: "*"
  chars_to_mask: 8,      // null = mask all characters
  from_end: true         // false = mask from start
}
// +1-555-123-4567 → +1-555-***-****
```

```python
models.MaskRule(
    entities=[models.ModelEntity(value="phone_number")],
    masking_char="*",      # default: "*"
    chars_to_mask=8,       # None = mask all characters
    from_end=True,         # False = mask from start
)
# +1-555-123-4567 → +1-555-***-****
```

### SHA256 / SHA512 [#sha256--sha512]

Hash detected entities:

```typescript
{
  type: "sha256",
  entities: [{ type: "model", value: "government_id" }]
}
```

```python
models.SHA256Rule(entities=[models.ModelEntity(value="government_id")])
# or models.SHA512Rule(...)
```

### Encrypt [#encrypt]

Encrypt detected entities with a key:

```typescript
{
  type: "encrypt",
  entities: [{ type: "model", value: "person" }],
  key: "your-encryption-key"   // default: ""
}
```

```python
models.EncryptRule(
    entities=[models.ModelEntity(value="person")],
    key="your-encryption-key",  # default: ""
)
```

## Regex Patterns [#regex-patterns]

You can also target text using regex patterns:

```typescript
{
  type: "replace",
  entities: [{ type: "regex", value: "\\d{4}-\\d{2}-\\d{2}" }],
  replacement: "[DATE]"
}
```

```python
models.ReplaceRule(
    entities=[models.RegexEntity(value=r"\d{4}-\d{2}-\d{2}")],
    replacement="[DATE]",
)
```

## Rule Application Results [#rule-application-results]

When anonymization runs, every entity that was detected and anonymized produces a result record. These records are returned in `response.results` as an ordered audit trail — one entry per matched span.

```typescript
const response = await api.anonymizeText({ text, rules })

console.log(response.text) // the anonymized string
console.log(response.results) // one record per anonymization applied
```

```python
response = anonymize_text.sync(
    client=client,
    body=models.AnonymizeRequestBody(text=text, rules=rules),
)

print(response.text)     # the anonymized string
print(response.results)  # one record per anonymization applied
```

Each result tells you:

* **which rule** was applied (`rule`)
* **what was detected** (`value` — entity type or regex pattern)
* **where it was** in the original text (`input`)
* **where it ended up** in the anonymized text (`output`)

A result is either a **model result** (AI detection) or a **regex result** (pattern match), identified by `type`:

### Model Result [#model-result]

```typescript
{
  type: "model",
  rule: "replace",            // rule type that was applied
  value: "PERSON",            // entity type the model detected
  score: 0.94,                // AI confidence (0.0–1.0)
  input:  { start: 8, end: 18, value: "John Smith" },   // position in original text
  output: { start: 8, end: 17, value: "[PATIENT]"  },   // position in result text
}
```

### Regex Result [#regex-result]

```typescript
{
  type: "regex",
  rule: "mask",                                          // rule type that was applied
  value: "\\d{3}-\\d{2}-\\d{4}",                        // pattern that matched
  input:  { start: 20, end: 31, value: "123-45-6789" }, // position in original text
  output: { start: 20, end: 31, value: "***-**-6789" }, // position in result text
}
```

### TextRange Fields [#textrange-fields]

| Field   | Type   | Description                        |
| ------- | ------ | ---------------------------------- |
| `start` | number | Start character offset (inclusive) |
| `end`   | number | End character offset (exclusive)   |
| `value` | string | The substring at `[start, end)`    |

Results are ordered by position in the output text. Use `input` offsets to map back to the original text, or `output` offsets to highlight spans in the anonymized result.
