Skip to main content Switch to mobile version privacy-gateway 0.2.0 Offline pseudonymization gateway between documents and external LLMs
pip install privacy-gateway Copy PIP instructions
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
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.
These principles guide the project. The second column says how far each one is implemented in 0.2.0; the roadmap has the planned work.
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 sorts them by evidence.
Proxy for Claude Code and the Anthropic API
Security model and known limits
Automated installation with a coding agent
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.
Text runs through a fixed stage order, defined in exactly one place (privacy_gateway/detect/__init__.py):
Format <{LABEL}_{NNN}>, zero-padded to three digits, counted per label per session:
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.
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.
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.
tests/fixtures/customer_letter_de.txt with the bundled defaults:
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:
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
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.
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:
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:
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
Every command reads a FILE or stdin (-) and accepts --config PATH.
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.
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:
$ 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": ["
$ printf 'IBAN DE89370400440532013000\n' | uv run pgw pseudonymize - --session-key demo session: 1c968610822e4311a854492ef099059b IBAN
$ printf 'password: "Hunter2-secret"\napi_key=AKIAIOSFODNN7EXAMPLE\n' | uv run pgw pseudonymize - session: e384d012bbec419f9e517e1eebae2db9 password: "
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.
$ cat answer.txt Answer about
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.
$ 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.
$ 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.
$ 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.
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
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.
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
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)
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
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:
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.
$ 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:
[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 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 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
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:
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).
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 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/
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.
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
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:
# 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:
{"v": 2, "event": "tool_restore", "ts": "...", "request_id": "
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.
One vault session per conversation, so a value keeps its token across turns and prompt caching keeps working. Strategies (PGW_PROXY_SESSION_STRATEGY):
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.
A model that sees
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/
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
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":"
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=
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.
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.
$ 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 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 switches the unit to that variant for you, and Prompt C connects a client. The proxy needs an auth token on that address.
# 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://
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
Upstream status codes and error bodies are passed through unchanged.
$ 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
A request that fails the leak check is written as
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.
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:
{"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.
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:
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.
Load order — each layer overrides the previous one field by field, it does not replace whole sections:
Bundled privacy_gateway/data/default_config.yaml
~/.config/privacy-gateway/config.yaml (skipped when PGW_SKIP_USER_CONFIG=1)
--config PATH, then PGW_CONFIG
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:
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
# one term per line Contoso GmbH Fabrikam AG Result:
$ printf 'Projekt PRJ-40711 für Contoso GmbH läuft auf corp.example.internal.\n' | pgw pseudonymize - session: 54f2e120faca4668befd06265476bd72 Projekt
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.
Configuration problems raise ConfigError and exit with code 1, with a message that names the offending key:
$ 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
What this protects against
Sending clear-text personal data, credentials and internal identifiers to an external LLM provider. The provider sees
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
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.
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
Redaction is irreversible. A round trip is byte-identical only for documents that contain no redact class; everything else comes back with
ß/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).
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
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.
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.
SECURITY.md — how to report a vulnerability.
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 — core design spec.
docs/superpowers/specs/2026-09-23-api-proxy-design.md — proxy design spec.
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.
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. The older audit.jsonl has the timestamp, but no session key.
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.
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.
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.
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://
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). 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
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:
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
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.
Read it before you run it — it installs a background service and appends a shell function to your shell profile.
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.
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
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 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.
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
Security reports: SECURITY.md. Contributions: CONTRIBUTING.md.
Released: Nov 28, 2026
Author: Michael Jung
Both files in this release have provenance metadata.
View provenance details
MIT View SPDX License List
anthropic gdpr llm pii privacy proxy pseudonymization
Development Status 3 - Alpha
Intended Audience Developers
License OSI Approved :: MIT License
Operating System MacOS :: MacOS X
Programming Language Python :: 3.12
Release files for privacy-gateway 0.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
Built distribution (wheel)
Total release size: 657.4 kB
Release files / privacy_gateway-0.2.0.tar.gz
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 28, 2026.
Release files / privacy_gateway-0.2.0-py3-none-any.whl
Security for privacy-gateway 0.2.0
Both files in this release have been uploaded with provenance metadata.
With provenance privacy_gateway-0.2.0.tar.gz Nov 28, 2026
With provenance privacy_gateway-0.2.0-py3-none-any.whl Nov 28, 2026
Attestation for privacy_gateway-0.2.0.tar.gz
Attestation for privacy_gateway-0.2.0-py3-none-any.whl
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.
Release history Release notifications | RSS feed
Nov 28, 2026 2 release files Full provenance
"PyPI", "Python Package Index", and the blocks logos are registered trademarks of the Python Software Foundation.
© 2026 Python Software Foundation
Deployed from fc0d8e6











