Metadata-Version: 2.5
Name: privacy-gateway
Version: 0.2.0
Summary: Offline pseudonymization gateway between documents and external LLMs
Project-URL: Homepage, https://github.com/j911si/local-privacy-gateway
Project-URL: Repository, https://github.com/j911si/local-privacy-gateway
Project-URL: Issues, https://github.com/j911si/local-privacy-gateway/issues
Author: Michael Jung
License-Expression: MIT
License-File: LICENSE
Keywords: anthropic,gdpr,llm,pii,privacy,proxy,pseudonymization
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: MacOS :: MacOS X
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Security
Requires-Python: >=3.12
Requires-Dist: cryptography>=42
Requires-Dist: pyyaml>=6
Description-Content-Type: text/markdown

# Local Privacy Gateway

**International by Design. Local by Policy. Privacy by Default.**

A local, offline gateway that removes sensitive data from text before it reaches an external
LLM and puts it back afterwards. Detection is deterministic and rule-based; every detected value
is replaced by a reversible token such as `<IBAN_001>`, the mapping is stored AES-256-GCM-encrypted
in a local SQLite vault, and the pseudonymized text is re-scanned before it is released — if
anything survived, the run fails closed and produces no output at all. It ships as a Python
library, a `pgw` CLI, and a local HTTP proxy (`pgw-proxy`) that sits between Claude Code (or any
Anthropic SDK client) and `api.anthropic.com`. It is **not** an NER model and makes **no
guarantee** for data shapes its rules do not describe: unknown formats, lowercased names and
free-form prose about a person are not detected. Because the process is reversible, it is
pseudonymization, not anonymization — secrets that must never come back use irreversible redaction
(`<API_KEY_REDACTED>`).

Tested on macOS and Linux. The library and the `pgw` CLI are plain Python. The bundled service
installer is launchd-only; a systemd user unit for Linux is documented below, with a Tailscale variant that binds to a private-network address so several machines can share one proxy. Every
request to `/v1/messages` also writes an audit entry without any values. Per field it says what was replaced
and what was forwarded unchecked, and it records whether a final rescan of the outgoing body found
anything.

## Design principles

These principles guide the project. The second column says how far each one is implemented
in 0.2.0; the [roadmap](ROADMAP.md) has the planned work.

| Principle | In 0.2.0 |
|---|---|
| International by Design | Every rule runs on every text; no detector depends on the language of the text. Global formats (IBAN, cards, e-mail, IP addresses, phone numbers with a country code, cloud keys, labelled secrets) work everywhere. Country-specific identifiers and the vocabulary for names, labels and addresses cover German and English only. Country and language packs are planned. |
| Local by Policy | Detection, the vault and all logs stay on your machine. The core package has no network code, and a test enforces that. The proxy sends only the pseudonymized request to the upstream you configure. |
| Privacy by Default | Fail closed when a known value survives. Sensitive findings in fields the proxy cannot change block the request. Tool calls get placeholders unless a rule allows a value. A proxy off loopback needs a token. None of this is a guarantee for data the rules do not describe. |
| Provider Independent | The library and the CLI work on any text for any model. The proxy speaks the Anthropic Messages API only. |
| Extensible by Design | Classes, patterns, context words and dictionaries can be added in a YAML layer without code changes. New check-digit validators still need code. |
| Transparent by Design | A value-free log line per request shows what was replaced and what went out unchecked. The [coverage register](docs/COVERAGE.md) and the [known limits](#known-limits) say what is not found. |
| Open Source | MIT license. Contributions for new countries and languages: [CONTRIBUTING.md](CONTRIBUTING.md#contributing-a-recognizer). |

The configuration defines 141 entity classes. Many of them are only found behind a label or
through your own dictionary, and some have no default rule at all. The
[coverage register](docs/COVERAGE.md) sorts them by evidence.

---

## Table of contents

- [Design principles](#design-principles)
- [How it works](#how-it-works)
- [Installation](#installation)
- [CLI usage](#cli-usage)
- [Library usage](#library-usage)
- [Proxy for Claude Code and the Anthropic API](#proxy-for-claude-code-and-the-anthropic-api)
- [Configuration](#configuration)
- [Security model and known limits](#security-model-and-known-limits)
- [Troubleshooting](#troubleshooting)
- [Automated installation with a coding agent](#automated-installation-with-a-coding-agent)
- [Development](#development)
- [License](#license)

---

## How it works

```
ORIGINAL
   → LOCAL DETECTION
   → LOCAL PSEUDONYMIZATION
   → LOCAL LEAKAGE VALIDATION
   → AI/LLM
   → LOCAL RESTORATION
   → OUTPUT
```

The gateway itself never opens a network connection. A test in
`tests/integration/test_no_network.py` statically forbids `privacy_gateway` from importing
`socket`, `http`, `urllib.request`, `requests`, `httpx`, `aiohttp`, `ssl`, `ftplib` or `smtplib`.
Network code exists only in the separate `privacy_gateway_proxy` package.

### Detection pipeline

Text runs through a fixed stage order, defined in exactly one place
(`privacy_gateway/detect/__init__.py`):

| Step | What it does |
|---|---|
| **Normalization** | NFC per grapheme cluster, `Cf` format characters (zero-width, soft hyphen) dropped, `Zs` separators folded to a plain space. An offset map carries every span back to the original text, so spans stay valid. |
| **StructuredStage** | Parses first, classifies components second: URLs (host, path, query parameters, embedded credentials, signature parameters), e-mail addresses, JWTs, PEM private-key blocks, database connection strings, HTTP headers and cookies. |
| **PatternStage** | One regex set per class where a format exists: IBAN, BIC, credit card, IPv4/IPv6, MAC, GPS, phone numbers, dates, tax and social-security IDs, VIN, vehicle registration, cloud keys (`AKIA…`, `ghp_…`, `glpat-…`, `sk-ant-…`, `xox…`). Each candidate must pass its validator — Luhn, IBAN MOD-97, `ipaddress`, VIN check digit, calendar date — or it is dropped. |
| **DictionaryStage** | Exact and case-insensitive multi-word matching against configured lists plus bundled first/last-name and city lists. Bundled name hits are low-confidence candidates; they only become findings when a context rule or correlation confirms them. |
| **ContextStage** | Deterministic markers: salutations (`Frau`, `Herr`, `Mr`, `Mrs`, `Ms`), `Kundennummer:`, `Konto`, `Vertrag`, `Ticket`, `namespace:`, `pod/`, `password`, `pin`, person labels (`Name:`, `Kontoinhaber`, `Customer:`), a birth date in front of `geboren`/`born`, address grammar, job and department markers. |
| **`correlate()`** | Gives every occurrence of the same value one `entity_id`, so repeated occurrences share a token. Each spelling of an entity gets its own token (`Anna`, `ANNA` and `anna` are one entity with three tokens), so every occurrence is restored byte for byte. |
| **`min_confidence` filter** | Drops everything below the configured threshold (default `0.5`). |
| **`resolve_overlaps()`** | Resolves overlapping findings by class priority, then span length, then stage order. |

### Tokens

Format `<{LABEL}_{NNN}>`, zero-padded to three digits, counted per label per session:
`<ACCOUNT_ID_001>`, `<IBAN_002>`. All `PERSON_*` classes share the label `PERSON`; when an explicit
salutation supplied a gender, the label carries it: `<PERSON_FEMALE_001>`, `<PERSON_MALE_002>`,
otherwise `<PERSON_001>`. Gender is **only** taken from a salutation word or from configuration,
never inferred from a first name.

### Vault

A SQLite file whose values are encrypted with AES-256-GCM. The 32-byte key lives in its own file,
created with `O_CREAT|O_EXCL` and mode `0600` inside a `0700` directory; a key file readable by
group or others is rejected with `VaultError`. The associated data of each ciphertext binds
`session_id | token`, so ciphertexts cannot be swapped between tokens. `purge` removes bytes, not
just rows: the connection runs with `PRAGMA secure_delete=ON` and every purge is followed by
`VACUUM`.

### Sessions

Every `pseudonymize()` call creates a fresh session (counters restart at `001`), so two documents
produce no cross-linkable tokens. A **named** session — `Gateway.session(key)`, `pgw pseudonymize
--session-key`, or one conversation in the proxy — keeps its mapping across calls: a value that
already has a token keeps it, new values continue the counter.

### Policies

| Policy | Effect |
|---|---|
| `tokenize` | Reversible. Value encrypted into the vault, replaced by `<CLASS_NNN>`. |
| `redact` | Irreversible. Replaced by `<CLASS_REDACTED>`, nothing is stored. Default for every `SECRET` class. |
| `ignore` | Detected and reported, left in the text unchanged. |

### Fail closed

Before any output is returned, the pseudonymized text is re-scanned with the full pipeline and
searched for every value stored in the session — exact, case-insensitive, whitespace-collapsed
and, for values with at least six digits, digits-only. Every `<…_NNN>` token in the output must
exist in the session mapping. Any hit raises `LeakageError`, the session is purged and **no text
is returned**. Any other exception in any stage aborts the same way. The proxy translates this
into HTTP 422 and sends nothing upstream.

### Example

`tests/fixtures/customer_letter_de.txt` with the bundled defaults:

```bash
uv run pgw pseudonymize tests/fixtures/customer_letter_de.txt \
  --session-file /tmp/sid --report text --out /tmp/letter.safe.txt
```

stderr:

```
session: e62175d58fb7417682a17ff43ea54e6c
ACADEMIC_TITLE: 1
ACCOUNT_ID: 1
ADDRESS: 1
CUSTOMER_ID: 1
DATE_OF_BIRTH: 1
EMAIL: 1
IBAN: 1
ORGANIZATION_NAME: 1
PERSON_FULL_NAME: 1
PERSON_LAST_NAME: 2
PHONE: 1
PLACE_OF_BIRTH: 1
SALUTATION: 2
tokens: 12
leakage: ok
```

Input (excerpt):

```
Musterbank AG
Kundenbetreuung
Lindenstraße 12, 40210 Düsseldorf

Sehr geehrte Frau Petersen,

Ihre Kundennummer: 884512
Ihr Konto 4711 bleibt unverändert bestehen.

Die Gutschrift über 240,00 EUR haben wir auf die IBAN DE89370400440532013000
angewiesen.

Sie erreichen uns telefonisch unter Tel. +49 211 5559021 oder per Mail an
betreuung@musterbank-beispiel.example.

Für unsere Unterlagen: geboren am 04.07.1979 in Bremen.

Bei Fragen zur Anlage wenden Sie sich bitte an Herrn Dr. Waldmann.

Mit freundlichen Grüßen

Anna Petersen
```

`/tmp/letter.safe.txt`:

```
<ORGANIZATION_NAME_001>
Kundenbetreuung
<ADDRESS_001>

Sehr geehrte Frau <PERSON_FEMALE_001>,

Ihre Kundennummer: <CUSTOMER_ID_001>
Ihr Konto <ACCOUNT_ID_001> bleibt unverändert bestehen.

Die Gutschrift über 240,00 EUR haben wir auf die IBAN <IBAN_001>
angewiesen.

Sie erreichen uns telefonisch unter Tel. <PHONE_001> oder per Mail an
<EMAIL_001>.

Für unsere Unterlagen: geboren am <DATE_OF_BIRTH_001> in <PLACE_OF_BIRTH_001>.

Bei Fragen zur Anlage wenden Sie sich bitte an Herrn <ACADEMIC_TITLE_001> <PERSON_MALE_002>.

Mit freundlichen Grüßen

<PERSON_FEMALE_001>
```

The sentence structure survives, the grammatical gender survives in the label, and the same person
gets the same token in the salutation and in the signature. Restoring is byte-identical:

```bash
uv run pgw restore --session "$(cat /tmp/sid)" /tmp/letter.safe.txt --out /tmp/letter.restored.txt
diff tests/fixtures/customer_letter_de.txt /tmp/letter.restored.txt   # no output
```

---

## Installation

### Requirements

- Python ≥ 3.12
- [`uv`](https://docs.astral.sh/uv/) (recommended) — `curl -LsSf https://astral.sh/uv/install.sh | sh`, or `brew install uv`
- Runtime dependencies: `cryptography`, `pyyaml`. The proxy adds `starlette`, `uvicorn`, `httpx`.

### Clone and install

```bash
git clone https://github.com/j911si/local-privacy-gateway.git
cd local-privacy-gateway

uv sync                  # library + pgw CLI + dev tools (pytest, ruff)
uv sync --group proxy    # additionally starlette, uvicorn, httpx for pgw-proxy

uv run pytest -q         # must end in "passed" with no "failed"
uv run pgw --help
```

Without `uv`, a virtual environment works too:

```bash
python3.12 -m venv .venv && . .venv/bin/activate
pip install -e .                 # library + pgw
pip install starlette uvicorn httpx   # only if you want the proxy
```

Everything below that starts with `uv run` then works without the `uv run` prefix.

### Where the state lives

These are the compiled-in defaults from `privacy_gateway/data/default_config.yaml`. They are
literal paths, not `XDG_*`-derived, but they follow the XDG layout:

| What | Default path | Overridden by |
|---|---|---|
| Vault database | `~/.local/share/privacy-gateway/vault.db` | `vault.db_path`, `PGW_VAULT_DB` |
| Vault key (32 random bytes, mode `0600`) | `~/.config/privacy-gateway/vault.key` | `vault.key_file`, `PGW_VAULT_KEY_FILE` |
| Audit log (JSON Lines, mode `0600`) | `~/.local/share/privacy-gateway/audit.jsonl` | `audit.path`, `PGW_AUDIT_LOG` |
| Proxy request log (one file per UTC day, kept 180 days) | `~/.local/state/privacy-gateway/audit/` | `PGW_AUDIT_LOG_DIR` |
| User configuration | `~/.config/privacy-gateway/config.yaml` | `--config` / `PGW_CONFIG` add another layer |

Both parent directories are created with mode `0700`. The key file is created on first use; back
it up together with the database, because without the key the vault cannot be decrypted and every
stored token is lost.

### Environment variables

| Variable | Default | Effect |
|---|---|---|
| `PGW_VAULT_DB` | `~/.local/share/privacy-gateway/vault.db` | Path of the encrypted SQLite vault. |
| `PGW_VAULT_KEY_FILE` | `~/.config/privacy-gateway/vault.key` | Path of the 32-byte AES key file. |
| `PGW_AUDIT_LOG` | `~/.local/share/privacy-gateway/audit.jsonl` | Path of the JSONL audit log. Set `audit.path: null` in YAML to disable auditing. |
| `PGW_AUDIT_LOG_DIR` | `~/.local/state/privacy-gateway/audit/` | Directory of the proxy's daily `proxy_request` v2 log, see [Request log](#request-log-v2). |
| `PGW_RESTORE_MODE` | `strict` | Default restore mode, `strict` or `lenient`. |
| `PGW_CONFIG` | unset | Extra configuration file, applied after the user config. |
| `PGW_SKIP_USER_CONFIG` | unset | `1`/`true`/`yes` ignores `~/.config/privacy-gateway/config.yaml`. Useful for reproducible runs and tests. |
| `PGW_PROXY_LISTEN` | `127.0.0.1:8787` | `host:port` the proxy binds to. Any address other than `127.0.0.1`, `localhost` or `[::1]` needs an auth token, else the proxy does not start. Besides loopback only explicit private addresses are accepted (`10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `100.64.0.0/10` as used by Tailscale, `fc00::/7`); `0.0.0.0`, `[::]`, public, link-local addresses and host names need `PGW_PROXY_ALLOW_PUBLIC_BIND`. |
| `PGW_PROXY_UPSTREAM` | `https://api.anthropic.com` | Upstream base URL. Only `https://` or `http://127.0.0.1` / `http://localhost` are accepted; anything else is a `ConfigError`. |
| `PGW_PROXY_SESSION_STRATEGY` | `metadata` | How the vault session key is derived: `metadata`, `header` or `single`. |
| `PGW_PROXY_TRANSFORM_SYSTEM` | `1` | `0`/`false`/`no`/`off` forwards the `system` prompt unchanged. Not needed for an OAuth login, see below. |
| `PGW_PROXY_PLACEHOLDER_NOTICE` | `1` | `0`/`false`/`no`/`off` suppresses the short notice that explains the placeholder format to the model. |
| `PGW_PROXY_DEBUG_DIR` | unset | Directory for one JSON dump per transformed request (mode `0600` in a `0700` directory). Contains the **pseudonymized** body. |
| `PGW_PROXY_RESCAN_BUDGET` | `10` | Seconds the rescan of one request may take; must be finite and above zero. Past it the request fails with 503 and nothing is sent. |
| `PGW_PROXY_PASSTHROUGH_PATHS` | unset (empty) | Comma-separated exact paths that may receive `POST`/`PUT`/`PATCH`/`DELETE` and are forwarded unchanged. Every other such request outside `/v1/messages` and `/v1/messages/count_tokens` gets 422. |
| `PGW_PROXY_AUTH_TOKEN` | unset | When set, every request except `GET /health` needs the header `x-pgw-auth` with this value, else 401. The header is never forwarded or logged. `install-launchd` refuses this variable; use the file variant. |
| `PGW_PROXY_AUTH_TOKEN_FILE` | unset | Path to a file holding the token. The file must not be readable by group or others (mode `0600`), else the proxy does not start. Cannot be combined with `PGW_PROXY_AUTH_TOKEN`. |
| `PGW_PROXY_UNCHECKED_FIELDS` | `block` | What happens when the rescan finds something in a field the proxy does not transform (`tools`, `thinking`, an untransformed `system`, unknown fields and blocks): `block` refuses the request with 422 `privacy_gateway_leak` before anything is sent when the finding belongs to a [blocking class](#unchecked-fields-blocking-classes); other classes are only reported. `allow` forwards everything unchanged with `verdict: ok_with_unchecked_findings` and a warning at startup (**unsafe**: the found values go upstream in clear text). Any other value stops the start. |
| `PGW_PROXY_ALLOW_UNAUTHENTICATED` | unset (off) | **Unsafe.** `1`/`true`/`yes`/`on` lets the proxy start on a non-loopback address without an auth token, with a warning in the startup log. Anyone who reaches the port and knows a session key gets that session's original values back. |
| `PGW_PROXY_ALLOW_PUBLIC_BIND` | unset (off) | **Unsafe.** `1`/`true`/`yes`/`on` lets the proxy bind to a wildcard, public or link-local address or a host name, still only with an auth token. The proxy has no TLS: token, prompts with real values and restored answers cross the network as plain HTTP. The startup log warns. |
| `PGW_PROXY_TOOL_RESTORE_POLICY` | unset (empty allowlist) | YAML file with the rules for restoring placeholders inside tool calls, see [Tool calls](#tool-calls-restore-policy). Without it nothing inside `tool_use.input` is restored. An unreadable or invalid file stops the start. |
| `PGW_PROXY_TOOL_RESTORE_ON_DENY` | `keep_token` | What happens to a placeholder no rule releases: `keep_token` leaves it in the tool call, `block` refuses the answer (HTTP 422, or an `error` event in a stream). Any other value stops the start. |
| `PGW_PROXY_DEBUG_ORIGINALS` | unset (off) | `1`/`true`/`yes`/`on` additionally dumps the **original, untransformed** body of a request that failed the leak check. Clear text. |

---

## CLI usage

Every command reads a `FILE` or stdin (`-`) and accepts `--config PATH`.

| Exit code | Meaning |
|---|---|
| `0` | Success. |
| `1` | Error (bad configuration, unreadable file, unknown token in `strict` restore, vault problem). |
| `2` | Fail-closed: `pseudonymize` detected a leak, or `validate` found something. |

### `pgw pseudonymize`

```
pgw pseudonymize [FILE|-] [--config PATH] [--out PATH] [--session-file PATH]
                          [--session-key KEY] [--report json|text]
```

Writes the pseudonymized text to stdout or `--out` (mode `0600`). The session id always goes to
stderr; `--session-file` additionally writes it to a file with mode `0600`.

```bash
uv run pgw pseudonymize letter.txt --out letter.safe.txt --session-file sid.txt --report text
```

`--report json` prints one value-free JSON object to stderr:

```bash
$ printf 'Kundennummer: 884512, IBAN DE89370400440532013000\n' | uv run pgw pseudonymize - --report json
session: a90842d46f704d35938b7ba36c090b49
{"counts": {"CUSTOMER_ID": 1, "IBAN": 1}, "duration_ms": 46, "leakage": "ok", "tokens": ["<CUSTOMER_ID_001>", "<IBAN_001>"]}
Kundennummer: <CUSTOMER_ID_001>, IBAN <IBAN_001>
```

`--session-key KEY` continues a named session instead of creating a new one. The same value then
keeps its token across runs — and `--report` produces no output, because a continued session has
no per-run summary:

```bash
$ printf 'IBAN DE89370400440532013000\n' | uv run pgw pseudonymize - --session-key demo
session: 1c968610822e4311a854492ef099059b
IBAN <IBAN_001>
$ printf 'IBAN DE89370400440532013000 again\n' | uv run pgw pseudonymize - --session-key demo
session: 1c968610822e4311a854492ef099059b
IBAN <IBAN_001> again
```

Redaction is irreversible and produces no vault entry:

```bash
$ printf 'password: "Hunter2-secret"\napi_key=AKIAIOSFODNN7EXAMPLE\n' | uv run pgw pseudonymize -
session: e384d012bbec419f9e517e1eebae2db9
password: "<PASSWORD_REDACTED>"
api_key=<API_KEY_REDACTED>
```

### `pgw restore`

```
pgw restore --session ID [FILE|-] [--config PATH] [--mode strict|lenient] [--out PATH]
```

Maps the tokens in the model's answer back to the stored values. Every spelling has its own
token, so a token always restores to exactly the text it replaced.

- **`strict`** (default, configurable via `restore.mode` / `PGW_RESTORE_MODE`): every token must be
  known. An unknown token is an error and aborts with exit code 1. Use it when you must be certain
  the answer contains no invented placeholder.
- **`lenient`**: also matches tokens the model altered cosmetically — lowercase, without angle
  brackets, wrapped in backticks or quotes. Unknown tokens stay in the text and are listed on
  stderr as `unknown tokens: …`. The proxy always restores responses in `lenient` mode so a
  hallucinated placeholder cannot abort an answer.

```bash
$ cat answer.txt
Answer about <PERSON_FEMALE_001> and <IBAN_009>.

$ uv run pgw restore --session "$(cat sid.txt)" answer.txt --mode lenient
unknown tokens: <IBAN_009>
Answer about Petersen and <IBAN_009>.

$ uv run pgw restore --session "$(cat sid.txt)" answer.txt --mode strict
error: unknown token: <IBAN_009>
# exit code 1
```

### `pgw validate`

Detection report only, nothing is rewritten and nothing is stored. Exit code `2` when anything was
found, `0` when the text is clean — useful as a pre-commit or CI check.

```bash
$ uv run pgw validate tests/fixtures/invoice_de.txt
ADDRESS: 1
BIC: 1
CARD_EXPIRY: 1
CREDIT_CARD: 1
CUSTOMER_ID: 1
IBAN: 1
INVOICE_ID: 1
PAYMENT_REFERENCE: 1
TAX_ID: 1
# exit code 2

$ printf 'The build finished in twelve seconds.\n' | uv run pgw validate -
no sensitive data detected
# exit code 0
```

### `pgw classes`

Every registered class as `name`, `policy`, `priority`, tab-separated. 141 classes with the bundled
defaults; your own configuration adds to and overrides that list.

```bash
$ uv run pgw classes | head -8
PERSON_FIRST_NAME	tokenize	140
PERSON_LAST_NAME	tokenize	140
PERSON_FULL_NAME	tokenize	140
PERSON_ALIAS	tokenize	140
PERSON_USERNAME	tokenize	140
PERSON_INITIALS	tokenize	140
SALUTATION	ignore	100
TITLE	tokenize	100
```

A higher priority wins overlap resolution. Note that `pgw classes` lists every registered class,
including ones you set to `enabled: false`.

### `pgw vault`

```bash
$ uv run pgw vault list          # session id, creation time, token count
e62175d58fb7417682a17ff43ea54e6c	2026-09-23T07:12:45.026227+00:00	12
1c968610822e4311a854492ef099059b	2026-09-23T07:13:03.090092+00:00	1

$ uv run pgw vault purge --session "$(cat sid.txt)"
purged 1 session(s)

$ uv run pgw vault purge --older-than 30
purged 0 session(s)
```

`--session` and `--older-than` are mutually exclusive and one of them is required. A purge writes a
`vault_purge` audit event and runs `VACUUM`, so the bytes are gone from the database file.

---

## Library usage

```python
from privacy_gateway import ConfigError, Gateway, LeakageError, RestoreError, VaultError

document = (
    "Sehr geehrte Frau Petersen,\n"
    "Ihre IBAN DE89370400440532013000 wurde am 12.03.2026 gutgeschrieben.\n"
)

try:
    with Gateway() as gateway:                      # or Gateway("config.yaml") / Gateway(cfg)
        # 1. Detect only, no rewriting, nothing stored.
        print(gateway.scan(document).counts_by_class())
        # {'SALUTATION': 1, 'PERSON_LAST_NAME': 1, 'IBAN': 1}

        # 2. Pseudonymize. Raises LeakageError instead of returning unsafe text.
        result = gateway.pseudonymize(document)
        print(result.text)
        # Sehr geehrte Frau <PERSON_FEMALE_001>,
        # Ihre IBAN <IBAN_001> wurde am 12.03.2026 gutgeschrieben.
        print(result.session_id, result.report.tokens)
        # a5b79f8229a84adaac0e804e91f5a606 ['<PERSON_FEMALE_001>', '<IBAN_001>']

        # 3. ... send result.text to the model, receive an answer ...
        answer = "Die Gutschrift für <PERSON_FEMALE_001> auf <IBAN_001> ist gebucht."

        # 4. Restore.
        restored = gateway.restore(answer, result.session_id, mode="lenient")
        print(restored.text, restored.unknown_tokens)
        # Die Gutschrift für Petersen auf DE89370400440532013000 ist gebucht. []

        # 5. A named session keeps its mapping across turns.
        chat = gateway.session("conversation-42")
        print(chat.pseudonymize("Frau Petersen ruft an."))
        # Frau <PERSON_FEMALE_001> ruft an.
        print(chat.pseudonymize("Petersen bestätigt IBAN DE89370400440532013000."))
        # <PERSON_FEMALE_001> bestätigt IBAN <IBAN_001>.
        print(chat.restore_text("<PERSON_FEMALE_001> ist informiert."))
        # Petersen ist informiert.
except LeakageError as exc:
    raise SystemExit(f"fail-closed: {len(exc.leaks)} potential leak(s)") from exc
except (ConfigError, VaultError, RestoreError) as exc:
    raise SystemExit(f"gateway error: {type(exc).__name__}") from exc
```

### API surface

| Call | Returns | Notes |
|---|---|---|
| `Gateway(config=None)` | — | `config` is a path, a `Config` object, or `None` for the layered default. Use it as a context manager or call `close()`. |
| `gateway.scan(text)` | `DetectionReport` | Detection only. `.counts_by_class()`, `.findings`, `.entities`. |
| `gateway.pseudonymize(text)` | `PseudonymizeResult` | `.text`, `.session_id`, `.report` (`counts`, `tokens`, `leakage`, `duration_ms`). Creates a fresh session. |
| `gateway.restore(text, session_id, mode=None)` | `RestoreResult` | `.text`, `.restored_count`, `.unknown_tokens`. `mode` defaults to `restore.mode`. |
| `gateway.session(key=None)` | `GatewaySession` | A named, continued session. `key=None` creates an anonymous one. |
| `session.pseudonymize(text)` | `str` | Reuses the tokens this session already assigned. |
| `session.pseudonymize_many(texts)` | `list[str]` | Same, in order, sharing counters. |
| `session.restore(text, mode=None)` | `RestoreResult` | |
| `session.restore_text(text)` | `str` | Convenience wrapper. |
| `session.entries()` | `Mapping[str, VaultEntry]` | Every token mapping this session knows. |
| `gateway.vault` | `Vault` | `list_sessions()`, `purge()`, `purge_older_than()`. Opened lazily. |

### Fail-closed exceptions

All of them derive from `PrivacyGatewayError`, so one `except PrivacyGatewayError` catches
everything.

- **`LeakageError`** — the pseudonymized text still contained something sensitive. `pseudonymize()`
  returns nothing, the session is purged. `exc.leaks` is a list of `Leak(kind, data_class, start,
  end)` — class names and positions only, never values.
- **`RestoreError`** — a token could not be restored in `strict` mode, or the mode name is unknown.
- **`VaultError`** — the vault or its key cannot be read or written: wrong key, key file with
  group/world permissions, wrong key length, decryption failure.
- **`ConfigError`** — invalid configuration: unknown key, unknown class category or policy, wrong
  type, `min_confidence` outside `0..1`, dictionary for a class that does not exist.

Any other exception inside `pseudonymize()` also aborts without producing output, after purging the
session and writing an `error` audit event.

---

## Proxy for Claude Code and the Anthropic API

`pgw-proxy` runs the gateway as a local HTTP service between an Anthropic API client and
`api.anthropic.com`. Requests are pseudonymized before they leave the machine; answers — streaming
or not — are restored before the client sees them.

```
Claude Code ──(real values)──► proxy ──(tokens)──► api.anthropic.com
Claude Code ◄──(real values)── proxy ◄──(tokens)── api.anthropic.com
```

### Running it

```bash
uv sync --group proxy
uv run pgw-proxy serve --listen 127.0.0.1:8787     # foreground
```

The startup log prints the settings the process actually runs with, which is the fastest way to
check that an environment variable arrived:

```
2026-09-23 09:14:21,594 INFO privacy_gateway_proxy: settings listen=127.0.0.1:8799 upstream=http://127.0.0.1:9 transform_system=True placeholder_notice=True debug_dir=None debug_originals=False
INFO:     Uvicorn running on http://127.0.0.1:8799 (Press CTRL+C to quit)
```

`GET /health` answers `{"status":"ok"}` without touching the upstream.

### As a background service (macOS, launchd)

```bash
uv run pgw-proxy install-launchd                  # writes the plist and bootstraps the job
uv run pgw-proxy status
uv run pgw-proxy uninstall-launchd                # boots the job out and deletes the plist
```

`install-launchd` writes `~/Library/LaunchAgents/com.privacy-gateway.proxy.plist` with `RunAtLoad`
and `KeepAlive`, logs to `~/Library/Logs/privacy-gateway/`, and runs
`uv run --project <repo> pgw-proxy serve`. Use `--label` for a different label and `--log-dir` for
a different log directory.

It copies **every `PGW_*` variable that is set in the installing shell** into the plist's
`EnvironmentVariables`, plus the current `PATH` so launchd finds `uv`. The environment of the
installing shell is therefore the configuration of the service:

```bash
PGW_PROXY_AUTH_TOKEN_FILE=~/.config/privacy-gateway/proxy-auth-token uv run pgw-proxy install-launchd
```

The command prints the variables it took over. Re-run it after changing one — the plist is
rewritten from the new environment; it is not merged.

```bash
$ uv run pgw-proxy status
label: com.privacy-gateway.proxy
plist: /Users/you/Library/LaunchAgents/com.privacy-gateway.proxy.plist
loaded: no
listening on 127.0.0.1:8787: no
```

`status` exits `0` when the port answers and `1` when it does not, so it works in a health check.

### As a background service (Linux, systemd user unit)

There is no installer for this; write the unit yourself. Replace `/home/you` with your home
directory and use the **absolute** path of `uv` (`command -v uv`), because systemd does not read
your shell profile.

`~/.config/systemd/user/privacy-gateway.service`:

```ini
[Unit]
Description=Local Privacy Gateway proxy
After=network.target

[Service]
Type=simple
WorkingDirectory=/home/you/local-privacy-gateway
ExecStart=/home/you/.local/bin/uv run --project /home/you/local-privacy-gateway pgw-proxy serve
Restart=always
RestartSec=2

Environment=PATH=/home/you/.local/bin:/usr/local/bin:/usr/bin:/bin
Environment=PGW_PROXY_LISTEN=127.0.0.1:8787
Environment=PGW_PROXY_UPSTREAM=https://api.anthropic.com
# Auth token (mode 0600 file, never the token itself in this unit):
# Environment=PGW_PROXY_AUTH_TOKEN_FILE=%h/.config/privacy-gateway/proxy-auth-token

[Install]
WantedBy=default.target
```

```bash
systemctl --user daemon-reload
systemctl --user enable --now privacy-gateway.service
systemctl --user status privacy-gateway.service
journalctl --user -u privacy-gateway.service -f
```

`loginctl enable-linger $USER` keeps the unit running when you are not logged in.

#### Hardened variant without `uv run`

[`docs/systemd/privacy-gateway-proxy.service.example`](docs/systemd/privacy-gateway-proxy.service.example)
starts `.venv/bin/pgw-proxy serve` directly after a one-time `uv sync --group proxy`, so nothing is
resolved or downloaded when the service starts. It sets the data paths through `PGW_*` variables,
uses `UMask=0077` and the sandboxing options a user manager allows (`NoNewPrivileges`,
`PrivateTmp`, `RestrictNamespaces` and others), and restarts on failure. It binds to loopback.

If another machine has to reach the proxy, bind it only to an address that nothing but trusted
devices can reach, such as a private VPN interface, never to `0.0.0.0`. On a non-loopback address
the `Host` header check is off (the proxy logs a warning at startup), and the proxy only starts
with `PGW_PROXY_AUTH_TOKEN_FILE` set.

### Pointing a client at it

```bash
export ANTHROPIC_BASE_URL=http://127.0.0.1:8787
claude --model "sonnet[1m]"
```

**The `[1m]` suffix is not optional.** With `ANTHROPIC_BASE_URL` set, Claude Code assumes a 200k
context window regardless of the model and starts autocompacting early; with a large tool set that
turns into repeated compaction of the same conversation. `--model "sonnet[1m]"`, `--model
"opus[1m]"` or `"model": "sonnet[1m]"` in `~/.claude/settings.json` restores the 1M window and
stops the thrashing. This is a property of the client, not of the proxy — it reproduces against an
unmodified passthrough.

A shell function keeps the private setup separate from your normal `claude`:

```bash
claude-private() {
  ANTHROPIC_BASE_URL=http://127.0.0.1:8787 \
  command claude --model "sonnet[1m]" "$@"
}
```

Note that `PGW_*` variables belong to the **proxy process**, not to the client. Putting
`PGW_PROXY_UNCHECKED_FIELDS=allow` into this function has no effect on a proxy that launchd or systemd
already started; it belongs in the service environment (see above).

### What is transformed

Transformed on `POST /v1/messages` and `POST /v1/messages/count_tokens`:

- **Request:** `system` (string, or the `text` of `type: "text"` blocks), `messages[].content`
  (string or `text` blocks), `tool_result` content (string or `text` blocks), every string leaf
  inside `tool_use.input`, and `source.data` of a `document` block whose `source.type` is `text`.
- **Response:** `content[].text`. Placeholders inside `tool_use.input` are restored only where
  the [tool restore policy](#tool-calls-restore-policy) allows it; by default nowhere.

Never touched, forwarded unchanged and **not scanned**:

- `thinking` and `redacted_thinking` blocks and their `signature` — Anthropic signs them, so a
  single changed byte invalidates the turn.
- `image` blocks, and `document` blocks with a base64 or PDF source.
- Server-side and MCP tool blocks: `server_tool_use`, `mcp_tool_use`, `search_result`.
- `tools` definitions, `metadata`, `model`, and all headers.

A user name inside a home-directory path is personal data too. `/Users/<name>/`, `/home/<name>/`
and `C:\Users\<name>\` give a `PERSON_USERNAME` finding for the `<name>` part, so the path comes
out as `/Users/<PERSON_002>/...` and is restored on the way back in text. In tool calls it is
restored only when a policy rule allows the class `PERSON_USERNAME` for that argument. Claude
Code puts such paths into every request (working directory, memory directory, instruction files).

Fields that are never changed are still read: the rescan of the outgoing body covers `tools`,
`metadata` and an unchanged system prompt, and the request log reports what it finds there.

`GET`, `HEAD` and `OPTIONS` requests to other paths are forwarded without a body. Their path is
scanned first: if the rules find something in a segment, the request gets HTTP 400 and is not
forwarded. UUIDs and plain numbers count as ids and are skipped. `POST`, `PUT`, `PATCH` and `DELETE`
to another path need that path in `PGW_PROXY_PASSTHROUGH_PATHS`, otherwise they get HTTP 422.

A `POST` to `/v1/messages` that the proxy cannot transform never reaches the upstream, because
forwarding it unchanged would mean forwarding clear text. A body with `Content-Encoding` gets
HTTP 422. A body that is not a JSON object of the expected form gets HTTP 400.

### Streaming

SSE is parsed event by event. `text_delta` is restored incrementally with a holdback: any trailing
fragment that could be the beginning of a token is kept back until the next delta or
`content_block_stop`, so a token is never split across deltas. `input_json_delta` is buffered per
content block and emitted as one delta at `content_block_stop`, after the tool restore policy has
decided on every placeholder in it, which makes tool calls appear slightly later in the stream
(typically under a second). Input that does not parse as JSON is forwarded with every placeholder
kept. Every other event —
`message_start`, `ping`, `thinking_delta`, `signature_delta`, `message_delta`, `message_stop`,
`error` — is forwarded byte-identical.

### Tool calls: restore policy

A placeholder inside a tool call is not restored unless a rule allows it. This closes a direct
path for prompt injection: text the model reads (a web page, a file, a tool result) can tell it
to put `<IBAN_001>` into `Bash`, `WebFetch` or an MCP tool, and without the policy the client
would receive and run the real value. Placeholders in text blocks are restored.

Without `PGW_PROXY_TOOL_RESTORE_POLICY` the allowlist is empty. Claude Code then writes the
placeholders, not the values, into files it creates with `Write` or `Edit`, and shell commands
see the placeholders too. If you want real values in files, allow exactly those arguments:

```yaml
# PGW_PROXY_TOOL_RESTORE_POLICY=~/.config/privacy-gateway/tool-restore.yaml
rules:
  - tool: Write
    argument: content
    classes: [IBAN, EMAIL, PERSON_FULL_NAME]
    target:
      argument: file_path
      under: /home/me/projects/letters
  - tool: Edit
    argument: new_string
    classes: [IBAN]
    target: {argument: file_path, under: /home/me/projects/letters}
  - tool: MultiEdit
    argument: edits[*].new_string
    classes: [IBAN]
```

Each rule needs all three of:

- `tool`: one exact, case-sensitive tool name (letters, digits, `_`, `-`). There are no patterns:
  `Write` does not cover `write`, `Write_evil`, `mcp__x__Write` or a name with a hidden character.
- `argument`: the path of a string inside the input. Object keys are joined with `.`, `[*]` stands
  for any element of a list. The path has to reach the string itself: `items` does not reach into
  a list, `items[*]` does.
- `classes`: the data classes that may be restored there, as listed by `pgw classes`
  (the class of the value, for example `PERSON_FULL_NAME`, not the token label `PERSON`).

The optional `target` applies the rule only when another argument holds an absolute path under
the directory `under`. The path is checked as a string: `//` and `/./` are normalized. A path with
`..`, a relative path, a path holding a placeholder, or a missing or non-string argument fails
the check, and the placeholder stays.

Object keys inside a tool input are never restored. A rule without `argument` or `classes`, an
unknown key, an unknown class, a tool name with a pattern, or a file that is not valid YAML stops
the proxy with an error message that names the position, not the content.

With `PGW_PROXY_TOOL_RESTORE_ON_DENY=block` a placeholder that no rule releases makes the proxy
refuse the answer. A non-streaming answer becomes HTTP 422 `privacy_gateway_tool_restore_denied`
and the client gets nothing of the tool call. In a stream, tool calls before it have already
been sent; the blocked call's input is replaced by an `error` event of the same type and the
stream ends there. The default `keep_token` leaves the placeholder in place and lets the agent
continue.

Each decision is logged in `tool-restore-YYYY-MM-DD.jsonl` next to the request log, one
`tool_restore` record per answer with placeholders in tool calls:

```json
{"v": 2, "event": "tool_restore", "ts": "...", "request_id": "<same as the proxy_request line>",
 "streaming": false, "on_deny": "keep_token",
 "entries": [{"tool": "Bash", "path": "content[0].input{0}", "cls": "IBAN", "decision": "kept"}]}
```

`decision` is `restored`, `kept` or `blocked`. `path` addresses object members by position like the
request log, so no key text appears. The tool name comes from the model: characters outside
letters, digits, `_` and `-` are written as `\uXXXX`, and the name is cut to 64 characters. No
value, no token and no hash of either is written. The file has its own name so readers of
`audit-*.jsonl` do not see an unknown event.

Limits: the policy decides per argument, not per effect. A value released into `Write.content`
can still leave the machine if the model later runs that file, uploads it, or reads it back into
a tool argument that has no rule. Keep rules narrow and use `target` for file tools. A symbolic
link under `under` that points elsewhere is not detected, because the check sees only the string. In block mode a stream
has already sent the start of the blocked call, its id and tool name, before the proxy ends it.

### Sessions

One vault session per conversation, so a value keeps its token across turns and prompt caching
keeps working. Strategies (`PGW_PROXY_SESSION_STRATEGY`):

| Strategy | Key |
|---|---|
| `metadata` (default) | The `session_id` field of a JSON `metadata.user_id` as Claude Code sends it; otherwise the `session_<uuid>` part of `metadata.user_id`; otherwise the `X-PGW-Session` header; otherwise a session for this request only. |
| `header` | The `X-PGW-Session` header, else a session for this request only. |
| `single` | One fixed key for everything. |

A request session restores the placeholders of its own answer and is purged from the vault when
the request or its stream ends, so a client without a key never sees another client's values.
Its next turn gets new placeholders. Before 0.2.0 all such requests shared one key per process.

The key must match `[A-Za-z0-9._-]{1,64}`; anything else is refused with HTTP 400
(`privacy_gateway_session`) before anything is scanned or forwarded. This holds for every request,
not only `/v1/messages`: a `GET`, `HEAD`, `OPTIONS`, `DELETE` or passthrough request with an
unusable key never reaches upstream, so a bad `X-PGW-Session` header cannot skip the path scan.
The audit line records the audit id of `-`, never the key that was sent. The server keeps
the 64 most recently used `GatewaySession` objects in memory; a conversation that falls out is
reloaded from the vault.

A session caches each pseudonymized text and drops that cache as soon as it learns a new value.
All texts of one request are pseudonymized again until no text adds a value, so a name that is
only recognized in a later field (`Frau Müller`) is also replaced where it stood alone earlier
(`Bitte Müller zurückrufen.`), within the same request.

The same holds inside one text. A value is only known to the session once it has been found, so
`/Users/anna/Notes` is found first and `-Users-anna-Work`, `~anna` or `anna_notes.md` later in the
same text would stay as they are. The pass therefore repeats while it learns new values (at most
four passes) before the leak check gives its verdict.

### Placeholder notice

A model that sees `<IBAN_001>` tends to answer with an invented IBAN instead of the placeholder.
The proxy therefore prepends one short text block to the **first user message** of every
transformed request:

```
<privacy-gateway>
Some values in this conversation are pseudonymized placeholders: an uppercase class name and a
three-digit number in angle brackets, written <CLASS_NNN>. They stand for real values that are
restored locally after your reply. Always reproduce placeholders verbatim, exactly as written,
including angle brackets and numbers. Never guess, invent or replace them with example values,
and never remove them.
</privacy-gateway>
```

A string `content` becomes a block list for this. The block is inserted at most once per request,
is visible to the model as ordinary conversation content, counts as one more field in the audit
line, and never goes into `system` — it sits in the messages because an OAuth client's system
prompt cannot be changed (see below). Disable it with `PGW_PROXY_PLACEHOLDER_NOTICE=0`.

### OAuth / Claude subscription

A client logged in with OAuth (a Claude Pro/Max subscription instead of an API key) works with the
default `PGW_PROXY_TRANSFORM_SYSTEM=1`, so the system prompt is pseudonymized like the messages.
Tested on 2026-11-27 with Claude Code 2.1.332 and a subscription login, in `claude -p` and in an
interactive session with tool calls, against an isolated proxy.

Claude Code sends a billing line as the first system block
(`x-anthropic-billing-header: cc_version=...; cc_entrypoint=...;`). The proxy forwards exactly this
line unchanged; it holds only the client version and entry point. Before 0.2.0 the proxy replaced
it, and the upstream answered every subscription request with `429 rate_limit_error`. That is why
older versions of this README recommended `PGW_PROXY_TRANSFORM_SYSTEM=0`. Anything else in the first
system block is transformed as usual. The billing line is Claude Code behaviour, not documented
Anthropic behaviour, so a later client version may need another check.

In an interactive session Claude Code also sends a top-level `safeguards` list whose
`classifier_context` carries the working directory and other context for Anthropic's safety
classifier. The proxy pseudonymizes that context like tool input, so the classifier sees the same
view as the model.

At the start of an interactive session Claude Code sends a small probe request (`max_tokens: 1`,
no system prompt). In the test above it got 429 in each of three sessions while every following
request got 200; the session was not affected. Whether the same probe gets 429 without the proxy
was not checked.

`PGW_PROXY_TRANSFORM_SYSTEM=0` still forwards the `system` field byte for byte. The audit line then
carries `system_transformed: false`, and everything the system prompt carries (project instruction
files, memory paths, skill descriptions) leaves the machine unchanged. With the default
`PGW_PROXY_UNCHECKED_FIELDS=block` the untransformed system prompt is rescanned, and a path such as
`/home/<name>/…` (the working directory or the auto-memory path) is a `PERSON_USERNAME` finding that
blocks every request with 422.

**Upgrade note (OAuth login with `PGW_PROXY_TRANSFORM_SYSTEM=0` from 0.1.0):** remove the setting
from the environment of the proxy process and restart the proxy.

### Unchecked fields: blocking classes

Fields the proxy does not transform (`tools`, `thinking` and `redacted_thinking`, `metadata`, an
untransformed `system`, unknown fields and blocks) are never changed, because some are signed. With
the default `PGW_PROXY_UNCHECKED_FIELDS=block` the rescan of the outgoing body blocks the request
(422 `privacy_gateway_leak`, `verdict: blocked`, nothing sent) when it finds one of these classes
in such a field:

- Secrets and credentials, every class with policy `redact`: `API_KEY`, `ANTHROPIC_API_KEY`,
  `OPENAI_API_KEY`, `STRIPE_SECRET_KEY`, `API_SECRET`, `CLIENT_SECRET`, `PASSWORD`, `PIN`, `TAN`,
  `OTP`, `ACCESS_TOKEN`, `REFRESH_TOKEN`, `JWT`, `OAUTH_CODE`, `SESSION_ID`, `SESSION_COOKIE`,
  `AUTH_COOKIE`, `CSRF_TOKEN`, `PRIVATE_KEY`, `SSH_PRIVATE_KEY`, `TLS_PRIVATE_KEY`,
  `AWS_ACCESS_KEY`, `AWS_SECRET_KEY`, `AZURE_SECRET`, `GCP_CREDENTIAL`, `KUBERNETES_SECRET`,
  `GITHUB_TOKEN`, `GITLAB_TOKEN`, `PERSONAL_ACCESS_TOKEN`, `DATABASE_CONNECTION_STRING`,
  `SIGNED_URL`, `SAS_TOKEN`.
- HTTP headers and cookies, which often carry credentials: `CUSTOM_HEADER`, `HEADER_VALUE`,
  `COOKIE`, `COOKIE_VALUE`.
- People: `PERSON_FIRST_NAME`, `PERSON_LAST_NAME`, `PERSON_FULL_NAME`, `PERSON_ALIAS`,
  `PERSON_USERNAME`, `CARDHOLDER`.
- Contact: `EMAIL`, `PHONE`, `MOBILE_PHONE`, `PHONE_INTERNATIONAL`, `FAX`.
- Payment: `IBAN`, `CREDIT_CARD`, `DEBIT_CARD`, `CVV`, `BANK_ACCOUNT`.
- Identity: `TAX_ID`, `SOCIAL_SECURITY_ID`, `PASSPORT_ID`, `NATIONAL_ID`, `DATE_OF_BIRTH`.

The rescan covers the keys of these objects too, except the field names of the Messages API and
of JSON Schema. In the request log a key outside that list appears as `<key>` in a path, and a
finding in the key itself has the path of its value plus `#key`. A `data` field is skipped only
as the base64 source of an `image` or `document` block in a message or `tool_result`, with an
allowed media type and well-formed base64; anywhere else it is scanned like any string.

The list is `UNCHECKED_BLOCKING_CLASSES` in `privacy_gateway_proxy/audit_trail.py`. Every other
class (for example `FQDN`, `URL`, `SOCIAL_MEDIA_HANDLE`, `ORGANIZATION_NAME`, `PERSON_INITIALS`,
addresses, IDs) is only reported in `observed` and `outgoing.rescan.findings`, never with a value,
and the request goes out with `verdict: ok_with_unchecked_findings`. Values under the public
example domains never count (`detect/public.py`), and neither do placeholders this session issued.

Two exact client values never block, and only in exactly this form:

- `metadata.user_id` as Claude Code sends it, either
  `{"device_id":"<64 lowercase hex>","account_uuid":"<uuid or empty>","session_id":"<uuid>"}`
  (these three keys in this order, no spaces) or `user_<64 hex>_account_<uuid or empty>_session_<uuid>`
  (lowercase UUIDs). Any other key, character or text makes it an ordinary field. Other
  `metadata` fields are always checked.
- The billing line in the first system block when the system prompt is untransformed: a block
  `{"type": "text", "text": …}` without further keys whose text is exactly
  `x-anthropic-billing-header: cc_version=<version>; cc_entrypoint=<word>;`, with a version of
  digits, letters and dots and an entrypoint of lowercase letters, digits, `_` and `-`. Any
  further key, header or text in that block makes the whole block an ordinary field, and its
  `CUSTOM_HEADER` finding blocks.

`PGW_PROXY_UNCHECKED_FIELDS=allow` turns the block off. That is unsafe: everything the rules
find in these fields goes upstream in clear text, as in earlier versions.

### Access control

The proxy answers only requests whose `Host` header is loopback (`127.0.0.1`, `localhost`, `[::1]`,
with or without a port) as long as it is bound to a loopback address; anything else gets HTTP 403.
Binding to a non-loopback address turns the host check off and logs a warning at startup.

```bash
$ curl -s -H 'Host: evil.example' -X POST http://127.0.0.1:8787/v1/messages -d '{}'
{"type":"error","error":{"type":"privacy_gateway_forbidden","message":"host header is not loopback"}}
```

The proxy auth token is off by default on loopback. Without it, anything that can reach the port
and knows or guesses a session key can have that session's tokens restored. On a single-user
machine bound to loopback that is acceptable; on a shared machine, set `PGW_PROXY_AUTH_TOKEN_FILE`.
On any other address (`0.0.0.0`, `[::]`, a LAN or VPN address) the proxy refuses to start without
a token. The check covers every route except `GET /health`, which answers `{"status":"ok"}` and
nothing else. `PGW_PROXY_ALLOW_UNAUTHENTICATED=1` overrides the refusal; that setup is unsafe and
the startup log says so.

Besides loopback the proxy binds only to explicit private addresses (RFC 1918, `100.64.0.0/10`,
`fc00::/7`). A wildcard (`0.0.0.0`, `[::]`), a public or link-local address or a host name is
refused unless `PGW_PROXY_ALLOW_PUBLIC_BIND=1` is set, and then still needs a token. The proxy
speaks plain HTTP and has no TLS, so on such an address the token and every request and answer
travel unencrypted unless the network itself encrypts them.

The proxy holds no credentials of its own: `x-api-key` and `Authorization` are forwarded untouched.

Request headers: `Cookie`, `Forwarded`, `X-Forwarded-*`, `X-Real-IP` and `Via` are never
forwarded. The values of all other forwarded headers are scanned with the blocking classes
above; a finding blocks the request with 422 and the request log names the header by position
(`headers[3]`), never by name. Not scanned are `x-api-key`, `Authorization` and the id headers
`x-claude-code-session-id` and `x-client-request-id` when they hold a plain UUID.
`PGW_PROXY_UNCHECKED_FIELDS=allow` forwards headers unscanned.

### Sharing one proxy across machines

One proxy can serve several machines on a private network such as Tailscale or WireGuard. Run it
on one host, bind it to that host's address on the private network and point the
`ANTHROPIC_BASE_URL` of every client at it. The example unit
[`docs/systemd/privacy-gateway-proxy.service.example`](docs/systemd/privacy-gateway-proxy.service.example)
ships with a loopback bind. Its commented Tailscale variant reads the Tailscale IPv4 address when
the service starts (`tailscale ip -4`), refuses to start when there is none and listens on that
address only. Prompt B in [`docs/AGENT-INSTALL.md`](docs/AGENT-INSTALL.md) switches the unit to
that variant for you, and Prompt C connects a client. The proxy needs an auth token on that
address.

```bash
# on the proxy host
umask 077; openssl rand -hex 32 > ~/.config/privacy-gateway/proxy-auth-token
export PGW_PROXY_AUTH_TOKEN_FILE=~/.config/privacy-gateway/proxy-auth-token
uv run pgw-proxy serve --listen "$(tailscale ip -4 | head -n1):8787"

# on every client (the same token, sent as the x-pgw-auth header)
export ANTHROPIC_BASE_URL=http://<proxy-host>:8787
export ANTHROPIC_CUSTOM_HEADERS="x-pgw-auth: <token>"
claude --model "sonnet[1m]"
curl http://<proxy-host>:8787/health        # {"status":"ok"} when the proxy is reachable
```

Limits of this setup:

- The host check is off for a non-loopback bind; the auth token is the access control. Limit
  reachability further with the network's access rules (Tailscale ACLs, a firewall) to your own
  devices. A bind to `0.0.0.0` or a public address is refused unless you set
  `PGW_PROXY_ALLOW_PUBLIC_BIND=1`; on a host with a public interface, do not.
- Between client and proxy the prompts travel as plain HTTP with real values. The private network
  encrypts that hop, nothing else does.
- A client without a connection to the private network gets a connection error. There is no
  fallback to `api.anthropic.com`; going direct again is a decision you make by removing
  `ANTHROPIC_BASE_URL`.
- Vault, key file and audit log live on the proxy host and hold the mappings and the request
  history of every client. Protect and back up that host accordingly.
- All clients share one configuration and one set of dictionaries.

### Status codes the proxy produces itself

| Code | `error.type` | When |
|---|---|---|
| 400 | `privacy_gateway_session` | The session key does not match `[A-Za-z0-9._-]{1,64}`. |
| 400 | `invalid_request_error` | The body of a `POST /v1/messages` is not a JSON object of the expected form, the query string has a parameter outside the allowed list, or the rules found something in a path segment. Nothing is sent upstream. |
| 400 | `privacy_gateway_rejected` | The path is not in normal form: dot segments, `//` or percent-encoded characters. Nothing is sent upstream. |
| 401 | `privacy_gateway_unauthorized` | `PGW_PROXY_AUTH_TOKEN` is set and `x-pgw-auth` is missing or wrong. Nothing is sent upstream. |
| 403 | `privacy_gateway_forbidden` | `Host` header is not loopback while bound to loopback. |
| 413 | `privacy_gateway_too_large` | Request body larger than 32 MiB. |
| 422 | `privacy_gateway_rejected` | `POST` to `/v1/messages…` that cannot be transformed: `Content-Encoding` set, or a sub-path such as `/v1/messages/batches`. Also any `POST`/`PUT`/`PATCH`/`DELETE` to another path not listed in `PGW_PROXY_PASSTHROUGH_PATHS`, and a `GET`/`HEAD`/`OPTIONS` with a body. Nothing is sent upstream. |
| 422 | `privacy_gateway_tool_restore_denied` | `PGW_PROXY_TOOL_RESTORE_ON_DENY=block` and a tool call in a non-streaming answer holds a placeholder that no rule releases. The client gets none of the answer. In a stream the same type arrives as an `error` event. The message lists class names and a count. |
| 422 | `privacy_gateway_leak` | The leak check, or the rescan of the body about to be sent, found residue in a transformed field, or (with the default `PGW_PROXY_UNCHECKED_FIELDS=block`) a finding of a blocking class in an unchecked field. Nothing is sent upstream. The message lists class names and a count, never values. |
| 502 | `privacy_gateway_upstream` | The upstream connection failed. |
| 503 | `privacy_gateway_timeout` | The rescan of the body exceeded `PGW_PROXY_RESCAN_BUDGET`. Nothing is sent upstream. |

Upstream status codes and error bodies are passed through unchanged.

```bash
$ curl -s -X POST http://127.0.0.1:8787/v1/messages -H 'content-type: application/json' -d 'not json'
{"type":"error","error":{"type":"privacy_gateway_rejected","message":"request body is not a transformable JSON object"}}
```

### Debug mode

`PGW_PROXY_DEBUG_DIR` points at a directory into which the proxy writes every transformed request
body as `<timestamp>-<audit_id>.json` with mode `0600`, in a directory created with mode `0700`.
`<audit_id>` is the random `session` id of the request log, never the session key.
That is exactly the pseudonymized JSON that goes upstream, so it answers "what really left the
machine".

A request that fails the leak check is written as
`<timestamp>-<audit_id>-FAILED-original.json` and contains the **original, untransformed body**,
because that is the only way to see which value tripped the check. Such a request is never sent
upstream. That second dump is clear text and therefore needs its own switch:

```bash
export PGW_PROXY_DEBUG_DIR=~/pgw-debug
export PGW_PROXY_DEBUG_ORIGINALS=1    # only while you are actually debugging
```

Both kinds contain full prompts and grow quickly. Use them for a single debugging run, delete the
dumps, and unset the variables afterwards. `install-launchd` copies both into the plist, so a
forgotten variable keeps writing dumps from the background service.

### Audit log

One JSON object per line, mode `0600`, never any content. The proxy adds `proxy_request` to the
core's `pseudonymize`, `session_pseudonymize`, `restore`, `vault_purge` and `error` events. A real
sequence for one non-streaming request:

```json
{"ts": "2026-09-23T07:14:58.905939+00:00", "event": "session_pseudonymize", "audit_id": "3f9a61c0d27e", "new_tokens": 0, "reused_tokens": 0, "leakage": "ok", "duration_ms": 47}
{"ts": "2026-09-23T07:14:58.908523+00:00", "event": "session_pseudonymize", "audit_id": "3f9a61c0d27e", "new_tokens": 2, "reused_tokens": 0, "leakage": "ok", "duration_ms": 2}
{"ts": "2026-09-23T07:14:58.929209+00:00", "event": "proxy_request", "path": "/v1/messages", "fields": 2, "tokens": 2, "leakage": "ok", "streaming": false, "duration_ms": 75, "system_transformed": true}
{"ts": "2026-09-23T07:14:58.929707+00:00", "event": "restore", "audit_id": "3f9a61c0d27e", "restored_count": 1, "unknown_token_count": 0, "mode": "lenient"}
```

`fields` is the number of transformed strings, `tokens` the number of mappings the session holds,
`leakage` is `ok`, `failed`, `rejected` or `upstream_error`. `audit_id` is a random id per vault
session, kept only in the process's memory, so it groups the events of one session but cannot be
used with `pgw restore`; after a restart the same session gets a new id. Follow it live with
`tail -f ~/.local/share/privacy-gateway/audit.jsonl`.

### Request log (v2)

In addition, the proxy writes one `proxy_request` line with `"v": 2` per `/v1/messages` request
into `PGW_AUDIT_LOG_DIR` (default `~/.local/state/privacy-gateway/audit/`, mode `0700`). Files are
named `audit-YYYY-MM-DD.jsonl` (UTC day, mode `0600`, append only). Once per process and day the
proxy deletes files of that name pattern dated 180 or more days back; other files stay.

Each line lists every field of the request:

- `status: checked` fields were pseudonymized. Each finding has class, offsets in the original
  field text, token, policy, confidence and stage. No value and no hash of a value is stored:
  a hash of a short value (CVV, date of birth, phone number, name) can be reversed by trying
  every candidate. Older versions wrote a per-value `hmac` with a salt file `audit.salt` next to
  the directory; the proxy no longer creates or reads that file, so after an update it is unused
  and can be deleted by hand. Lines with `hmac` from older versions stay valid `"v": 2` lines.
- `status: unchecked` fields are never changed (`reason`: `thinking`, `tools`, `metadata`,
  `image`, `signature`, `system`, `other`). `observed` lists classes and counts from the rescan.
  With `PGW_PROXY_UNCHECKED_FIELDS=block` (default) a finding of a blocking class in any of
  them blocks the request; with `allow` they are forwarded as they are. With `PGW_PROXY_TRANSFORM_SYSTEM=0` the system prompt (`system`, or each `system[i]`
  block) is such a field with `reason: system`.
- `outgoing` holds `sha256` and `bytes` of the body sent upstream (never the body itself),
  `leakage`, `upstream_status` (the HTTP status the upstream answered with, `null` when nothing
  was sent or the connection failed; the verdict does not depend on it) and a `rescan`: the full
  detection runs again over every string of that body. A hit
  in a checked field sets `verdict: blocked` and nothing is sent. So does a hit of a blocking class in
  an unchecked field under the default `PGW_PROXY_UNCHECKED_FIELDS=block`; other hits there, and
  all of them under `allow`, are only reported. Values under `example.com`, `example.org`, `example.net`, `json-schema.org` and
  `w3.org` (the `$schema` URLs of tool definitions, documentation addresses) are public by
  definition and are not reported (`detect/public.py`). With `verdict: blocked` the hash describes
  the body that was held back; after a failed leak check `sha256` is `null`. A rescan that exceeds `PGW_PROXY_RESCAN_BUDGET` stops
  with `status: skipped`, `reason: timeout` and `verdict: error`; nothing is sent. The budget is
  checked between strings, so one very long string can run past it before the request stops.
- The base64 `data` of images and documents is not rescanned. Detection is linear on it (about
  1.5 s per MB of base64 on the development machine), but the scan cache is dropped whenever a
  session learns a new value, so every image in the history would be scanned again on such
  requests.
- A checked field that failed the leak check carries `leaks`: a list of `kind`, `cls`, `start` and
  `end`, with offsets into the already replaced text of that field and never a value. `kind` is
  `original_value` (a value the session stored is still in the text), `residual_finding` (the
  detection finds something that is not a token) or `unknown_token` (a token this session never
  issued).
- `verdict` is `ok`, `ok_with_unchecked_findings`, `blocked` or `error` (upstream connection
  failed, rescan timeout, or a request was rejected). `ok_with_unchecked_findings` means nothing
  was blocked, but the rescan found something in at least one unchecked field that was forwarded
  (a non-blocking class, a known client value, or anything with
  `PGW_PROXY_UNCHECKED_FIELDS=allow`); look at the `observed` lists of the `unchecked` fields. A request with a body that is not a JSON object, a
  wrong basic form (`messages`, a message, `content`, a block, `system`) or a query string outside
  the allowed parameters gets HTTP 400 (`invalid_request_error`) and `verdict: blocked`.
- The keys of the objects inside `tool_use.input` are checked like values. A key field has the
  path of its object plus `{n}#key`; objects are addressed by position, so a key never appears in
  a path. If two keys of one object become equal after replacement, the later one gets a suffix
  (`#2`, `#3`). The restore removes it again when the key has a reversible token. A redacted key
  keeps the suffix, and a key that already ends in `#2` in your own data can lose it. `coverage` counts values and keys separately as
  `checked_fields` and `checked_keys`, next to `unchecked_fields`.
- Query strings are forwarded only with the parameters `beta`, `limit`, `before_id` and `after_id`
  and values of letters, digits and `_.:-` (up to 128 characters); anything else is refused with
  HTTP 400. The access log of uvicorn never shows the query.

`session` is a random audit id of 12 hex characters (`secrets.token_hex(6)`). The proxy draws
it the first time it sees a session key and keeps the pair in memory only (the 4096 most recent
keys), so the lines of one conversation share it until the process restarts. It is never derived
from the key: the key restores a session's tokens through the proxy, so it counts as a credential
and appears in no log, neither plain nor shortened nor hashed. The old `audit.jsonl` no longer
has a `session_key` field. Values, parts of values and error texts never appear.

**`verdict: ok` only means the rules found nothing.** It is no proof that a request is free of
personal data: forms the patterns, dictionaries and context rules do not know pass unnoticed, and
unchecked fields go upstream as they are.

#### Checking what was sent

The daily files are plain JSON Lines, so `jq` answers most questions:

```bash
LOG=~/.local/state/privacy-gateway/audit/audit-$(date -u +%F).jsonl

# requests per verdict
jq -r .verdict "$LOG" | sort | uniq -c

# blocked requests: where the leak check or the rescan found something
jq -c 'select(.verdict=="blocked") | {ts, leakage: .outgoing.leakage, leaks: [.fields[] | select(.leaks) | {path, leaks}], rescan: [.outgoing.rescan.findings[] | {path, cls}]}' "$LOG"

# classes seen in fields that were forwarded unchanged
jq -r '.fields[] | select(.status=="unchecked") | .observed[]? | .cls' "$LOG" | sort | uniq -c | sort -rn

# requests whose final rescan found something, with the field paths
jq -c 'select(.outgoing.rescan.status=="findings") | {ts, paths: [.outgoing.rescan.findings[].path]}' "$LOG"
```

`rescan.status: clean` means the rules found nothing in any string of the body, checked or not.
A Claude Code request always carries unchecked fields (`tools`, `metadata`, and the system prompt
with an OAuth login). For those the log shows what the rules saw, not that it is harmless.

---

## Configuration

Load order — each layer overrides the previous one **field by field**, it does not replace whole
sections:

1. Bundled `privacy_gateway/data/default_config.yaml`
2. `~/.config/privacy-gateway/config.yaml` (skipped when `PGW_SKIP_USER_CONFIG=1`)
3. `--config PATH`, then `PGW_CONFIG`
4. `PGW_VAULT_DB`, `PGW_VAULT_KEY_FILE`, `PGW_AUDIT_LOG`, `PGW_RESTORE_MODE`

So a class block that only sets `policy:` keeps the built-in category, patterns and context words.
Dictionary lists are appended, not replaced. Unknown keys are an error, never a silent no-op.

### A complete annotated example

`~/.config/privacy-gateway/config.yaml`:

```yaml
classes:
  # A new class. `category` is required for a class that does not exist yet.
  PROJECT_CODE:
    category: PROJECT           # one of PERSON ROLE ORGANIZATION CONTACT LOCATION BIRTH
                                # IDENTIFIER FINANCIAL HEALTH NETWORK DOMAIN URL APPLICATION
                                # KUBERNETES DATABASE TENANT PROJECT EDGE REPOSITORY TICKET
                                # SECRET HTTP
    policy: tokenize            # tokenize | redact | ignore
    patterns: ['\bPRJ-\d{5}\b'] # Python regex; a capturing group marks the part to replace
    context_words: [project, projekt]
    context_required: false     # true: only a match near one of the context words counts
    # priority: 90              # optional, higher wins overlap resolution
    # token_label: PROJECT      # optional, label used in the token instead of the class name

  # Override one field of a built-in class; everything else stays.
  EMAIL:
    policy: redact              # e-mail addresses are now irreversible <EMAIL_REDACTED>

  # Switch a built-in class off entirely.
  CARD_EXPIRY:
    enabled: false

dictionaries:
  # Inline terms, matched case-insensitively, multi-word aware.
  CUSTOMER_NAME: [Contoso GmbH, Fabrikam AG]
  INTERNAL_DOMAIN: [corp.example.internal]
  # Or one term per line from a text file; blank lines and `#` comments are ignored.
  # A relative path is resolved against the directory of this config file.
  files:
    CUSTOMER_NAME: ./customers.txt
    INTERNAL_DOMAIN: ./domains.txt
    HOSTNAME: ./hostnames.txt

vault:
  db_path: ~/.local/share/privacy-gateway/vault.db
  key_file: ~/.config/privacy-gateway/vault.key

audit:
  path: ~/.local/share/privacy-gateway/audit.jsonl   # `null` disables the audit log

restore:
  mode: strict                  # strict | lenient

person:
  record_gender_from_salutation: true   # false: never put a gender into a PERSON token

languages: [de, en]             # reserved: read, but has no effect in 0.2.0

min_confidence: 0.5             # 0..1; findings below this are dropped
```

`customers.txt`:

```
# one term per line
Contoso GmbH
Fabrikam AG
```

Result:

```bash
$ printf 'Projekt PRJ-40711 für Contoso GmbH läuft auf corp.example.internal.\n' | pgw pseudonymize -
session: 54f2e120faca4668befd06265476bd72
Projekt <PROJECT_CODE_001> für <CUSTOMER_NAME_001> läuft auf <INTERNAL_DOMAIN_001>.
```

Dictionaries are the practical answer to the biggest gap in rule-based detection: customer names,
project names, internal domains and hostnames have no recognizable format, so nothing finds them
unless you list them. Keep those lists in files, keep the files next to the config, and keep both
out of any repository.

Use `pgw classes --config your.yaml` to see the effective class list, and `pgw validate` on a
representative document to check whether a new rule fires.

### Validation errors

Configuration problems raise `ConfigError` and exit with code 1, with a message that names the
offending key:

```bash
$ pgw classes --config bad.yaml
error: unknown keys for class 'FOO': ['categorie']

$ pgw classes --config bad2.yaml
error: 'min_confidence' must be between 0 and 1
```

Other cases: `unknown configuration keys in <path>`, `unknown category '…' for class '…'`,
`unknown policy '…'`, `'patterns' of class '…' must be a list`, `dictionaries for unknown classes:
[…]`, `restore mode must be one of ('strict', 'lenient')`, `config file not found`, `invalid YAML
in config file`. A typo is always an error and never a silently ignored setting — that is on
purpose, because a silently ignored class definition would mean silently disabled protection.

---

## Security model and known limits

### What this protects against

Sending clear-text personal data, credentials and internal identifiers to an external LLM provider.
The provider sees `<PERSON_FEMALE_001>` and `<IBAN_001>`; the mapping stays on your machine in an
encrypted vault; secrets classified as `SECRET` are redacted irreversibly and are not stored at
all.

Supporting properties:

- **Fail closed.** Any exception in any stage aborts `pseudonymize()` without producing output. The
  pseudonymized text is re-scanned and searched for every stored value; any hit raises
  `LeakageError` and purges the session.
- **Never logged.** Findings, detection reports, audit events and exception messages carry class
  names, spans and counts — never values. The audit log records classes, offsets, lengths and
  counts, not content. Audit records use random ids for correlation, never the session key or the
  vault session id.
- **No network in the core.** `privacy_gateway` imports no networking module; a test enforces this
  statically. All network code lives in `privacy_gateway_proxy`, which the core never imports.
- **Per-session tokens.** Two separate documents produce no cross-linkable tokens.
- **Gender** comes only from an explicit salutation or from configuration, never from a first name.

### What this does not protect against

- **A local attacker with access to both the key file and the database.** The vault is encrypted at
  rest against someone who copies `vault.db` alone. Someone who can read your home directory as
  your user reads both files and decrypts everything. There is no passphrase, no key rotation, no
  multi-user separation.
- **Prompt injection, in part.** A model instructed by text inside a file it read can put
  `<IBAN_001>` into a tool call. By default the proxy does not restore it there, so the tool gets
  the placeholder. A rule you add re-opens that path for its tool, argument and classes, and a
  released value can travel on: through a file the model later executes or uploads, or through
  text the model reads back. Text answers are restored, so whatever you copy from them by hand
  carries the real value. Placeholders are numbered in order and easy to guess.
- **Anything at the proxy port.** Without `PGW_PROXY_AUTH_TOKEN`, any local process that reaches
  `127.0.0.1:8787` and knows a session key can use the proxy as a restore oracle. A non-loopback
  bind without a token is refused unless `PGW_PROXY_ALLOW_UNAUTHENTICATED=1` is set; with it,
  every device that reaches the port is such a process.
- **Whatever the rules do not describe.** See below.

### Known limits

- **Rule-based only.** Regexes, validators, dictionaries and context rules. There is no NER model,
  so anything the rules do not describe is not found. Classes without a recognizable format —
  person aliases, customer names, department names — need a dictionary entry or a context marker.
- **Names need shape.** `Anna Müller` is detected, `anna müller` is not (lowercase), and a bare
  `Müller` without a salutation or a known full name is not. A single first name or a single city
  name on its own falls below `min_confidence` and is dropped, because treating every occurrence of
  a common first name as a person produces unusable false positives.
- **Name parts across turns.** A session recognizes only the surface forms it has stored. If turn 1
  contains `Frau Anna Müller` and turn 2 contains only `Müller`, turn 2 may go out in the clear or
  receive a second token. Within one document `correlate()` joins them; across turns it does not.
  (An automatic derivation of name parts was implemented twice and removed both times: it made the
  leak check reject legitimate requests such as `Termin Hollerbach-Petersen`.)
- **Names behind a label.** `Kontoinhaber`, `Customer:`, `Patient:` and similar labels turn the two
  or three capitalized words behind them into a person name. The generic label `Name:` (also
  `Display Name:`, `Model Name:`) does so only when one of the words is in the first-name list, so
  `name: Run Unit Tests` stays and a person with a first name outside the list stays too. A single
  word behind a label is not taken (`Kontoinhaber Müller`), and capitalized words behind a person
  label in technical text (`Customer: Order History`) are replaced like a person.
- **Labelled numbers.** `PIN`, `TAN` and `OTP` are redacted when the digits follow the word directly
  or after up to 40 characters and a `:` or `=` on the same line, so `PIN-Länge: 123456` is redacted
  too. An 11-digit number directly behind `Steuer-ID`, `Steuernummer`, `IdNr`, `TIN` or `Tax ID` is
  replaced without a valid check digit; without such a label the check digit decides. German tax
  numbers written with slashes are not covered by this rule.
- **Images, PDFs and base64.** `image` blocks and `document` blocks with a base64 or PDF source
  pass through unchanged, and the `data` of a well-formed base64 source with an allowed media type
  is never scanned. Screenshots and scanned invoices are not protected.
- **`thinking` blocks keep their tokens.** They are signed by Anthropic, so the proxy cannot rewrite
  them. Extended-thinking text you see may contain `<IBAN_001>` instead of the value.
- **Redaction is irreversible.** A round trip is byte-identical only for documents that contain no
  `redact` class; everything else comes back with `<CLASS_REDACTED>`.
- **`ß`/`SS` case folding** is not covered by the leak check, so a value written `Straße` in the
  input and `STRASSE` in the output would not be flagged.
- **Availability of the proxy.** Detection runs on the proxy's event loop, so one large request
  holds every other request and `/health` until it is done (1 MiB of prose about 29 s, measured
  with a cold vault). Requests that wait longer than the 10 s connect timeout meanwhile fail with
  502 (11 of 14 in a test with four 256 KiB and ten small requests). Nothing is forwarded in
  clear text because of it. There is no admission limit and no time budget for the
  pseudonymization itself (the rescan stops after 10 s with 503), memory grows by about 220 MiB
  per MiB of input, and a request whose client has disconnected is still sent upstream.
  Resource limits and parallel requests are the focus of 0.2.1 ([roadmap](ROADMAP.md)).
- **Numbers in forwarded JSON.** Detection reads strings. A JSON number, for example an ID stored
  as a number inside a tool input or in the `classifier_context` of Claude Code's `safeguards`,
  is neither replaced nor rescanned and goes out as it is.
- **VIN without a check digit.** A VIN is found only when its check digit (position 9) is valid.
  Many European VINs do not use one (`WVWZZZ1JZXW000001`) and go out unchanged.
- **Look-alike characters.** Fullwidth letters and digits are folded to ASCII and invisible
  format characters (Unicode category Cf, such as a zero-width space), variation selectors and
  the combining grapheme joiner are dropped before the rules run; a base character followed by
  more than 32 combining marks is left as it is. Letters of other scripts that only look Latin,
  such as a Cyrillic `А` inside an IBAN, are not mapped, so such a value is not found.
- **Generic markers are off by default.** Words like "reference", "number" or "name" are not
  context markers, because they produce too many false positives. Add them per class with
  `context_words` if your documents need them.
- **Streaming holdback.** The holdback covers token fragments of up to 80 characters after a `<`,
  and bracket-less uppercase fragments of up to 73 characters. A class name longer than that can
  break restoration in a stream.
- **One vault per process.** The proxy serves exactly one vault and one configuration. The auth
  token is one shared secret, not a per-user login.
- **No TLS.** The listener speaks plain HTTP. Over a VPN such as Tailscale or WireGuard the VPN
  encrypts the hop; on a plain LAN or any other network, token, prompts and answers are readable on
  the way. TLS on the listener is planned for a later version.
- **No client identity.** A session is chosen by what the client sends (`metadata.user_id` or
  `X-PGW-Session`). Whoever reaches the port, holds the token and knows a session key gets that
  session's values restored. Only a request without any key is isolated, by a session of its own.
- **Header scan.** Header values are checked by the same rules as unchecked fields. `x-api-key`,
  `Authorization` and UUID id headers are not scanned, and a value the rules do not find is
  forwarded as it came.
- **Unchecked fields are not repaired.** `tools` definitions, `metadata`, an unchanged system
  prompt (OAuth login) and signed blocks are never changed. By default a finding of a blocking class
  in one of them blocks the whole request; other classes (domains, URLs, handles, organization
  names) and everything under `PGW_PROXY_UNCHECKED_FIELDS=allow` are forwarded byte for byte and
  only reported. Values the rules do not find go out either way.
- **Spellings are separate placeholders.** `Anna`, `ANNA` and the `anna` in `/Users/anna/` each
  restore exactly, but the model sees three different tokens and cannot tell that they name the
  same person.
- **Learned names in a request path.** The path scan runs the rules, not the values a conversation
  has learned. A name that only a context rule found earlier is not recognized in a path.
- **Token-shaped text in your own input.** Text that already contains something like `<IBAN_001>`
  (docs about this gateway, for example) stays as literal text. A new token skips numbers that
  already appear in the text it is issued for, but a literal that first shows up in a later turn
  can still match a token issued earlier; a restored answer can then show that value where the
  model quoted the literal. Nothing leaves your machine through this.
- **Prompt caching.** A new known value changes older messages of the same conversation, which
  invalidates Anthropic's prompt cache for that one request.
- **Rescan budget.** `PGW_PROXY_RESCAN_BUDGET` is checked between strings; one very long string can
  run past it. A custom `FQDN` pattern in your YAML falls back to the slower regex scan.
- **Large requests block the proxy.** Detection runs in the event loop. Measured on the release
  candidate: about 9 s of CPU per MiB of prose for one request, so a body near the 32 MiB limit
  holds every other session for minutes. The default rules run in linear time; a pattern you change
  in your YAML falls back to the plain regex scan and has no such guarantee.
- **Redacted values live in memory only.** Once a password, PIN or TAN is redacted, later copies in
  the same document or conversation are redacted too. That memory ends with the process and with
  each separate `pgw` call, so a copy in a later CLI call or after a proxy restart is caught only
  if a rule finds it again. A short PIN such as `2024` also replaces the same number as a year.
- **Parallel writers on one vault.** Several processes may share `vault.db` and a session key. A
  token is claimed inside one transaction; when two writers collide, the loser fails closed with
  `VaultError` and the next request gets a free token. Under heavy parallel use of one session
  many requests fail this way.
- **Detection edges.** An IBAN glued to capital letters (`IBANDE89…`) and a card number glued to a
  word other than a card word (`id4111…`) are not found. Escaped JSON is covered up to three
  escape levels, escaped password values up to 512 characters.
- **Countries and languages.** Identifiers of countries other than Germany and the United States
  (French NIR, Spanish DNI, UK National Insurance number and many more) are found only behind a
  label, and labels, salutations and address grammar exist in German and English only. Full list
  in the [coverage register](docs/COVERAGE.md).
- **Plain dates.** A date on its own is not replaced, with or without a year (`14.03.2025`,
  `14.03.`, `2025-03-14`). Only a date in front of a birth marker (`geboren`, `born`,
  `Geburtsdatum`) or a health statement counts as a birth date.
- **Unknown names without a salutation.** Two capitalized words that are in no bundled list stay
  as they are unless a salutation (`Herr`, `Frau`, `Mr`) stands in front. A person label such as
  `Name:` helps only when the first name is in the bundled list.
- **Out of scope:** ML/NER models, OCR, binary documents, multi-user vaults, key rotation.

### Further reading

- [`SECURITY.md`](SECURITY.md) — how to report a vulnerability.
- [`docs/reviews/2026-09-23-security-review.md`](docs/reviews/2026-09-23-security-review.md) — a
  full adversarial review with reproduced findings, written in German. Note that it describes the
  state at the time it was written; several findings have since been fixed, and the ones that
  remain are listed above.
- [`docs/superpowers/specs/2026-09-22-local-privacy-gateway-design.md`](docs/superpowers/specs/2026-09-22-local-privacy-gateway-design.md)
  — core design spec.
- [`docs/superpowers/specs/2026-09-23-api-proxy-design.md`](docs/superpowers/specs/2026-09-23-api-proxy-design.md)
  — proxy design spec.

---

## Troubleshooting

### HTTP 422 `privacy_gateway_leak` — a request was refused

This is the fail-closed path doing its job: something in the request still looked sensitive after
pseudonymization. The request was not sent upstream.

1. Open today's file in `PGW_AUDIT_LOG_DIR` and find the line with `"verdict": "blocked"`. If
   `outgoing.leakage` is `fail`, the leak check stopped it and the field with `leaks` names the
   field path, the kind of leak and the class, for example `original_value PERSON_USERNAME`. If
   it is `ok`, the final rescan stopped it and `outgoing.rescan.findings` lists path, class and
   offsets. A path in an unchecked field (`tools[…]`, `system` with
   `PGW_PROXY_TRANSFORM_SYSTEM=0`, a `thinking` block, an unknown field) means the default
   `PGW_PROXY_UNCHECKED_FIELDS=block` stopped it: the proxy cannot replace values there, see
   [Unchecked fields: blocking classes](#unchecked-fields-blocking-classes). The older `audit.jsonl` has the timestamp, but no session key.
2. If that is not enough, turn on `PGW_PROXY_DEBUG_DIR` **and** `PGW_PROXY_DEBUG_ORIGINALS=1`, reproduce, and read the
   `-FAILED-original.json` dump. It is clear text, so delete it afterwards.
3. Identify the class that fired. Usually one of two things is happening: a value appears in two
   spellings and only one was tokenized (a user name as `/Users/anna/` and as `-Users-anna-`, a
   name with a genitive `s`), or a rule matched a fragment of a longer value.
4. **Sharpen the rule, do not weaken the leak check.** Add the value to a dictionary, add a
   `context_word`, or add a pattern that covers the full value instead of a fragment. Lowering
   `min_confidence` or disabling a class to make the error go away removes protection instead of
   fixing the cause.

Note that the same 422 status with `"type": "privacy_gateway_rejected"` is a different problem: the
body was not transformable at all (see the status table above).

### HTTP 403 `privacy_gateway_forbidden`

The `Host` header is not loopback. Use `http://127.0.0.1:8787` or `http://localhost:8787` in
`ANTHROPIC_BASE_URL`, not a LAN address or a hostname that resolves elsewhere. If you really need
to bind to a non-loopback address, the check turns itself off and the proxy needs an auth token
to start. For several machines use the private-network setup in
[Sharing one proxy across machines](#sharing-one-proxy-across-machines).

### Claude Code reports a connection error with a shared proxy

The client cannot reach the proxy host. Check that the private network is connected on the client,
then `curl http://<proxy-host>:8787/health`. If that fails, check on the proxy host that the service
runs (`systemctl --user status privacy-gateway-proxy`) and that it listens on the private address
(`ss -ltn | grep 8787`). The unit exits when the host has no private-network address yet and tries
again every ten seconds.

### HTTP 429 with an empty body and no rate-limit headers

With an OAuth login, check that the proxy is 0.2.0 or later: older versions replaced Claude Code's
billing line in the system prompt, and the upstream answers such requests with 429 (see
[OAuth / Claude subscription](#oauth--claude-subscription)). A single 429 on the small probe at the
start of an interactive session does not stop the session. A real rate limit carries
`anthropic-ratelimit-*` headers and a JSON error body.

### Claude Code compacts the conversation over and over

`ANTHROPIC_BASE_URL` is set and the model has no `[1m]` suffix, so the client assumes a 200k
window. Start it as `claude --model "sonnet[1m]"` or put `"model": "sonnet[1m]"` into
`~/.claude/settings.json`.

### `decryption failed` / `VaultError`

The vault database and the key file do not belong together. Most often `PGW_VAULT_KEY_FILE` points
somewhere else than it did when the session was created, or the key file was deleted and silently
recreated — a fresh key cannot decrypt old sessions. Restore the original key file. Also check the
permissions: a key file readable by group or others is rejected on purpose (`chmod 600`).

### `error: unknown token: <X_001>` on restore

You are in `strict` mode and the text contains a token this session does not know — because the
model invented it, or because you passed the wrong session id. Check the session id first
(`pgw vault list`). If the answer legitimately contains invented placeholders, use `--mode lenient`;
unknown tokens then stay in the text and are listed on stderr.

### `error: address already in use` on `pgw-proxy serve`

Something already listens on the port — usually an installed launchd or systemd service.
`pgw-proxy status` tells you whether the job is loaded; `lsof -nP -iTCP:8787 -sTCP:LISTEN` tells you
which process it is. Either stop the service or start your foreground instance on another port with
`--listen 127.0.0.1:8799`.

### Nothing gets detected in my documents

Run `pgw validate document.txt` to see what the rules find. If the answer is "nothing", the values
have no format the rules recognize — customer names, internal project names, hostnames. Add them as
dictionary entries or give the class a `context_word` that actually appears in your documents. Check
`min_confidence` too; the default `0.5` is already permissive, and raising it drops more.

---

## Automated installation with a coding agent

If you use a coding agent (Claude Code, Codex, Cursor or similar), you can hand it the prompt below
and it will install and verify the gateway end to end without asking questions. The same prompt,
with a short explanation of what it does and what to check afterwards, lives in
[`docs/AGENT-INSTALL.md`](docs/AGENT-INSTALL.md).

Read it before you run it — it installs a background service and appends a shell function to your
shell profile.

[`docs/AGENT-INSTALL.md`](docs/AGENT-INSTALL.md) holds two more prompts. Prompt B installs one
shared proxy on a server that only your Tailscale network can reach. Prompt C connects another
machine's Claude Code to it. Both are described in
[Sharing one proxy across machines](#sharing-one-proxy-across-machines).

```text
You are installing the Local Privacy Gateway (https://github.com/j911si/local-privacy-gateway) on
this machine and verifying that it works. Complete the whole installation autonomously: do not ask
me any questions, use the defaults stated below for every decision, and report at the end.

ASSUMPTIONS AND DEFAULTS (use these, do not ask):
- Install directory: $PGW_HOME if that variable is set, otherwise ~/local-privacy-gateway.
- Proxy listen address: 127.0.0.1:8787.
- Gateway config directory: ~/.config/privacy-gateway. Vault data: ~/.local/share/privacy-gateway.
- Model default for the shell function: sonnet[1m]. The [1m] suffix is required, never drop it.
- OS detection: `uname -s` -> "Darwin" means macOS (use launchd), "Linux" means Linux (use a
  systemd user unit). Anything else: skip the service step and report it.
- Login type: API key and OAuth/subscription login both work with the defaults. Do not set
  PGW_PROXY_TRANSFORM_SYSTEM.
- Do not modify any existing shell configuration except appending one clearly marked block to the
  user's shell rc file (~/.zshrc for zsh, ~/.bashrc for bash). Never edit or reorder existing lines.
- If any step fails, stop, do not improvise a workaround, and report exactly what failed with the
  command output.

SECURITY RULES (non-negotiable):
- Never write an API key, token or password into any file, and never echo one.
- Never set PGW_PROXY_DEBUG_ORIGINALS. It writes untransformed prompts to disk in clear text.
- Never read, print, copy or back up ~/.config/privacy-gateway/vault.key or any vault.db.
- Never send a request to api.anthropic.com as part of this installation. All smoke tests are local.
- If a test fails, report it. Do not edit, skip or weaken tests to make them pass.

STEPS:

1. Check prerequisites.
   - `git --version` must succeed. If git is missing, install it (macOS: `xcode-select --install`
     or `brew install git`; Linux: the distribution package manager) and re-check.
   - The uv installer needs `curl` and, on a minimal Linux, `ca-certificates`. If `curl --version`
     fails, install both with the distribution package manager first.
   - `uv --version` must succeed. If uv is missing, install it with
     `curl -LsSf https://astral.sh/uv/install.sh | sh` (or `brew install uv` on macOS if brew is
     present), then make sure the uv binary is on PATH for this session
     (`export PATH="$HOME/.local/bin:$PATH"`) and re-check.
   - uv provides the Python interpreter; the project requires Python >= 3.12. You do not need a
     system Python.

2. Clone the repository into the install directory. If the directory already exists and is a git
   checkout of this repository, run `git pull --ff-only` instead of cloning. If it exists and is
   something else, stop and report.
   `git clone https://github.com/j911si/local-privacy-gateway.git <install dir>`

3. Install dependencies from the install directory:
   `uv sync --group proxy`
   Expected: uv resolves and installs; the packages starlette, uvicorn and httpx appear.

4. Run the test suite: `uv run pytest -q`
   Expected: the last line reports passed tests and contains no "failed" and no "error".
   If anything failed, STOP here and report the failing output. Do not continue.

5. Create the configuration directory and a starter config.
   - `mkdir -p ~/.config/privacy-gateway && chmod 700 ~/.config/privacy-gateway`
   - `mkdir -p ~/.local/share/privacy-gateway && chmod 700 ~/.local/share/privacy-gateway`
   - Create the three empty dictionary files ~/.config/privacy-gateway/customers.txt,
     domains.txt and hostnames.txt, each containing only the comment line
     "# one term per line", and chmod 600 each of them.
   - Write ~/.config/privacy-gateway/config.yaml with mode 600 and exactly this content:

       dictionaries:
         files:
           CUSTOMER_NAME: ./customers.txt
           INTERNAL_DOMAIN: ./domains.txt
           HOSTNAME: ./hostnames.txt

       restore:
         mode: lenient

     If config.yaml already exists, do not overwrite it; leave it alone and note this in the report.

6. First run, which creates the vault key. From the install directory:
   `uv run pgw pseudonymize tests/fixtures/customer_letter_de.txt`
   Expected on stdout: the letter with tokens such as <ORGANIZATION_NAME_001>, <ADDRESS_001>,
   <PERSON_FEMALE_001>, <CUSTOMER_ID_001>, <IBAN_001>, <PHONE_001>, <EMAIL_001>. On stderr a line
   "session: <32 hex characters>". Exit code 0.
   Then verify with `ls -l ~/.config/privacy-gateway/vault.key` that the key file exists with mode
   -rw------- (0600). Do not print its content.

7. Install the background service.
   macOS: from the install directory run
     `uv run pgw-proxy install-launchd`
     Expected output: "installed /Users/<you>/Library/LaunchAgents/com.privacy-gateway.proxy.plist",
     a list of the PGW_* variables taken over, the log directory, and a line
     "export ANTHROPIC_BASE_URL=http://127.0.0.1:8787".
   Linux: run `mkdir -p ~/.config/systemd/user`, then write
   ~/.config/systemd/user/privacy-gateway.service with this content, substituting the
   real home directory and the absolute path of uv from `command -v uv`:

       [Unit]
       Description=Local Privacy Gateway proxy
       After=network.target

       [Service]
       Type=simple
       WorkingDirectory=<install dir>
       ExecStart=<absolute uv path> run --project <install dir> pgw-proxy serve
       Restart=always
       RestartSec=2
       Environment=PATH=<dirname of uv>:/usr/local/bin:/usr/bin:/bin
       Environment=PGW_PROXY_LISTEN=127.0.0.1:8787
       Environment=PGW_PROXY_UPSTREAM=https://api.anthropic.com

       [Install]
       WantedBy=default.target

     Then run
     `systemctl --user daemon-reload` and `systemctl --user enable --now privacy-gateway.service`.
   If neither service manager is available, skip this step, and in the report tell the user to run
   `uv run pgw-proxy serve --listen 127.0.0.1:8787` in the foreground instead.

8. Check the status.
   `uv run pgw-proxy status`
   Expected: the label, the plist path, "loaded: yes" on macOS, and
   "listening on 127.0.0.1:8787: yes". Exit code 0. On Linux use
   `systemctl --user status privacy-gateway.service` plus
   `uv run pgw-proxy status --listen 127.0.0.1:8787` (which will report loaded: no, that is correct
   there, only the listening line matters).
   If the port does not answer, read the log (macOS:
   ~/Library/Logs/privacy-gateway/com.privacy-gateway.proxy.err.log; Linux:
   `journalctl --user -u privacy-gateway.service -n 50`) and report.

9. Local smoke tests. No request reaches Anthropic in any of these.
   a) `curl -s http://127.0.0.1:8787/health`
      Expected exactly: {"status":"ok"}
   b) `curl -s -o /dev/null -w '%{http_code}' -X POST http://127.0.0.1:8787/v1/messages \
         -H 'content-type: application/json' -d 'not json'`
      Expected: 422
   c) `curl -s -o /dev/null -w '%{http_code}' -X POST http://127.0.0.1:8787/v1/messages \
         -H 'Host: evil.example' -H 'content-type: application/json' -d '{}'`
      Expected: 403
   d) `ls -l ~/.local/state/privacy-gateway/audit/` must list a file `audit-<today, UTC>.jsonl`
      with mode -rw-------, and `wc -l` on it must be at least 1. The file holds field paths,
      classes and counts, never content.
   If a code differs, report the actual code and the response body; do not change the code to make
   it match.

10. Append the shell function. Detect the shell from $SHELL (zsh -> ~/.zshrc, bash -> ~/.bashrc;
    if neither, report and skip). If the marker "# >>> local-privacy-gateway >>>" is already
    present, replace the block between the markers instead of appending a second one. Append:

        # >>> local-privacy-gateway >>>
        claude-private() {
          ANTHROPIC_BASE_URL=http://127.0.0.1:8787 \
          command claude --model "sonnet[1m]" "$@"
        }
        # <<< local-privacy-gateway <<<

11. Final report. Print, in this order:
    - Installed version and commit hash (`git -C <install dir> rev-parse --short HEAD`).
    - The install directory, the config file, the vault database path and the vault key path.
    - The result of every smoke test with its actual status code.
    - How to use it: open a new shell and run `claude-private`.
    - Where the audit logs are: `~/.local/share/privacy-gateway/audit.jsonl` (events, watch it with
      `tail -f`) and `~/.local/state/privacy-gateway/audit/` (one file per UTC day with the
      field-by-field request log; `jq` recipes are in the README section "Checking what was
      sent").
    - Uninstall instructions: macOS `uv run pgw-proxy uninstall-launchd`; Linux
      `systemctl --user disable --now privacy-gateway.service` and delete the unit file; then
      remove the block between the shell markers, delete the install directory, and — only if the
      user wants to discard every stored mapping, delete ~/.local/share/privacy-gateway,
      ~/.local/state/privacy-gateway and ~/.config/privacy-gateway.
    - Anything you skipped or that failed, stated plainly.
```

---

## Development

```bash
uv sync --group proxy
uv run pytest -q                                   # full suite
uv run pytest tests/unit/test_validators.py -q -k luhn   # one test
uv run ruff check .                                # lint, line length 100
```

Conventions, in short — [`CONTRIBUTING.md`](CONTRIBUTING.md) has the details:

- **TDD.** Write the failing test first, then the smallest change that makes it pass.
- `ruff` defaults, line length 100, type hints everywhere. Docstrings are one line. No comments that
  explain *what* the code does.
- Values never appear in findings, reports, audit events or exception messages — only class names,
  spans and counts. A patch that puts a value into a log line will not be merged.
- Each detection stage receives the accumulated findings read-only and returns **only its new
  findings**. The shared interfaces in `docs/superpowers/plans/2026-09-22-local-privacy-gateway.md`
  are a contract; do not change a signature without updating that section.
- `detect/__init__.py` is the only place that knows the stage order.
- Network code lives **only** in `privacy_gateway_proxy/`. `transform` and `streaming` are pure
  functions; `server` and `cli` own `httpx` and `uvicorn`. Nothing there may be imported from
  `privacy_gateway/`.
- Commit per task with a conventional message.

Documentation:

- Core spec: `docs/superpowers/specs/2026-09-22-local-privacy-gateway-design.md`
- Core plan: `docs/superpowers/plans/2026-09-22-local-privacy-gateway.md`
- Proxy spec: `docs/superpowers/specs/2026-09-23-api-proxy-design.md`
- Proxy plan: `docs/superpowers/plans/2026-09-23-api-proxy.md`
- Security review: `docs/reviews/2026-09-23-security-review.md`
- Agent installation prompt: `docs/AGENT-INSTALL.md`

---

## License

MIT — see [`LICENSE`](LICENSE).

Security reports: [`SECURITY.md`](SECURITY.md). Contributions: [`CONTRIBUTING.md`](CONTRIBUTING.md).
