◆  ────────────────────────────────────  ◆

      S   U   R   R   O   G   A   T   E

      ███████╗██╗  ██╗██╗███████╗██╗     ██████╗ 
      ██╔════╝██║  ██║██║██╔════╝██║     ██╔══██╗
      ███████╗███████║██║█████╗  ██║     ██║  ██║
      ╚════██║██╔══██║██║██╔══╝  ██║     ██║  ██║
      ███████║██║  ██║██║███████╗███████╗██████╔╝
      ╚══════╝╚═╝  ╚═╝╚═╝╚══════╝╚══════╝╚═════╝ 

      ◆  ────────────────────────────────────  ◆
v / 1.9.0 build / 2026.10 python / ≥ 3.10 pip / ./python-library license / Apache-2.0 status / ● operational

PII never leaves
your device. Surrogates do.

SurrogateShield finds the personal data in a message, replaces it with realistic, consistent surrogates before the request reaches an LLM provider, and puts the real values back in the reply. On 3,677 personal values placed in real ShareGPT, WildChat and oasst1 messages it let 0.8% through. GLiNER-PII let through 9.1%, Microsoft Presidio 31.6% and LLM Guard 56.3%. It trailed on only a few tests, listed in one line under Limitations. The surrogate map is encrypted with AES-256-GCM and stays on your machine. Ships as a Python library with a CLI, plus an interactive terminal app.

0.8%
PII leaked on real chat text
GLiNER-PII 9.1% · Presidio 31.6%
11×
fewer leaks than GLiNER-PII
39× fewer than Presidio
97.4%
prompts sent fully clean
GLiNER-PII 75.4% · Presidio 30.8%
43.5 ms
median per message, CPU
1.9× faster than GLiNER-PII
01 / PIPELINE
How it works

A single round-trip through the proxy, end to end.

Every message goes through detection, surrogate generation, an encrypted map, the LLM call and restoration. Detected values are replaced before the request is made. If a detection model is missing, mask() raises DetectorUnavailable and the text is not sent half-masked.

pipeline.live — watch a single message travel through the proxy 01 DETECT 02 SURROGATE 03 SEND 04 RECEIVE 05 RESOLVE
Detect
SentinelLayer scans the message for personal values
USER ▸ on device
Hi, I'm Priya Raman. Email me at priya.raman@northwind.io or call +1 415 555 0142.
masked text · HTTPS
LLM API ▸ remote
waiting…
response · contains surrogates
USER ▸ display
awaiting response…
SHADOWMAP AES-256-GCM
PERSON Priya Raman ↔ Adya Nath
EMAIL priya.raman@northwind.io ↔ adya.nath@vance.io
PHONE +1 415 555 0142 ↔ +1 213 581 8333
pipeline.flow — visual annotated
user message [ SERVICE QUERY DETECTOR ] address: shift · coarsen · replace SENTINELLAYER detection stages · balanced preset · then structural passes PatternScan regex + views stage 1 EntityTrace spaCy NER stage 2 PIITagger DeBERTa-v3-small stage 3 MimicGen · surrogate generation same shape · Luhn-valid · no collisions SHADOWMAP · AES-256-GCM { surrogate → original } HKDF-SHA256 · per-conversation key LLM API ↳ receives the masked text RESOLVEPASS exact · component · fuzzy (≥ 85) restored output
pipeline.flow — explained read me
01
Service-query router

With address_mode="auto" (the default), a question that needs a location to be answered (e.g. pharmacies near…) keeps the street and city and shifts the house number by ±1. If the question is about a sensitive topic (HIV, abortion, rehab, therapy, mental health, shelter, immigration and similar), the street becomes my area. Every other address is replaced in full.

02
SentinelLayer detection

PatternScan finds structured values with regex and validators. The canonicaliser also reads them when they are written in words, spelled out or disguised with look-alike characters. EntityTrace (spaCy) and PIITagger (a fine-tuned DeBERTa-v3-small) find names, organisations, places, addresses, handles and IDs. Structural passes then read CSV columns, signatures and “my name is” frames. A relation gate keeps public figures and companies you only mention.

03
MimicGen

Draws a surrogate of the same type and shape for each value: real-looking names, an e-mail built from the surrogate name, a phone in the same format, Luhn-passing card numbers, IDs with the same letter and digit pattern. A value gets the same surrogate every time it appears in a session, and no two values share one.

04
ShadowMap

The {surrogate → original} pairs are kept in memory by default. When saved, they are encrypted with AES-256-GCM under a per-session key derived with HKDF-SHA256 from a 32-byte device secret. The file cannot be read without that secret.

05
LLM API

Receives the masked text over HTTPS: the prompt, the earlier turns and any RAG context, each with its detected values replaced. On real chat text 0.8% of placed values reached it, against 9.1% for GLiNER-PII and 31.6% for Presidio.

06
ResolvePass

Three-tier substitution on the response: exact match → component match (handles partial name mentions) → fuzzy match (rapidfuzz score ≥ 85). Restores originals before the user sees anything.

Service-query handling. In a message like "restaurants near 1126 E Apache Blvd, Tempe, AZ", the house number is shifted by ±1 and the street and city are kept, because replacing the address would make the answer useless. Sensitive topics (HIV, abortion, rehab, addiction, mental health, therapy, domestic violence, shelter, immigration, self-harm and others) coarsen the street to my area instead. Turn the feature off with service=False. The benchmark redraws every address, so these kept parts are not part of its leak figures.
02 / DETECTION
SentinelLayer

Patterns, two models, structure. One answer per value.

On the default balanced preset, the stages run in this order: PatternScan with the canonicaliser, EntityTrace, PIITagger, then the structural passes. A relation gate keeps names that are not tied to the writer, and a resolver settles each value on one type. Removing any stage raises the leak rate. Without the pattern rules it goes from 0.8% to 1.4%, without the canonicaliser to 3.9%, and without the tagger to 10.8%.

STAGE 01

PatternScan

pattern_scan.py · canonical.py

Regex with format validators: Luhn for cards, checksums for IBANs, VINs and routing numbers, and range checks for SSNs and ZIPs. The canonicaliser reads the same message in other written forms, such as numbers in words, “at”/“dot” e-mails, ordinal dates and look-alike or zero-width characters. A value found that way gets its surrogate written back in the same form.

methodregex + validators + views
coversemail · phone · URL · IP · MAC · card · IBAN · SSN · passport · VIN · API key · crypto · DOB · age · ZIP
viewsworded · spelled · dates · folded · joined
STAGE 02

EntityTrace

spaCy · en_core_web_lg

Named-entity recognition with spaCy. In balanced it reads places only, because its names cost more harmless edits than they find, so names come from the tagger. In strict and classic it reads names too and sends borderline spans to ContextGuard. The fast preset skips it, and the tagger reads places instead.

confirmed≥ 0.90
borderline0.70 – 0.90
fallback0.75 (CG off)
STAGE 03

PIITagger

DeBERTa-v3-small · pii-tagger-dv3s-40k

A token tagger fine-tuned for personal data. It reads names, organisations, places, addresses, phones, handles, IDs and credentials, and long text is read in overlapping windows. The weights (~565 MB) are on Hugging Face: they download once, at a fixed commit, must match their SHA-256 pin, and then load from the local cache with no network. If they cannot be fetched, mask() raises DetectorUnavailable instead of sending the text with less protection. The classic preset runs without it.

window256 tokens · stride 64
weightsHugging Face · sha256-pinned
servernone, in-process

Passes after the models detection/pipeline.py · structural.py · relation_gate.py · resolver.py

PassBehaviour
SStructure-driven detection. It covers CSV columns, chat speakers, signatures, “my name is” / “lives in” frames, payees after “PAYMENT TO”, and streets written the French or Portuguese way. Each rule needs its own structural evidence, so none of them fires on a bare word.
A · E · HStructural ORG (<name> Inc / LLC / Corp…), structural PERSON in all-lowercase or all-caps text, and the card brand written right before a card number.
F · G · B · CDrops implausible ORGs, merges adjacent name pieces, turns an ORG that matches an e-mail username into a PERSON, and removes a surname already inside a detected full name.
RRelation gate. An organisation or place is replaced only when it is tied to the writer (“I work at…”, “my son’s school…”). Public figures, public companies and places that are only the topic of a question are kept.
resolverOne candidate per value. Source priority is applied first, then a rule for each type conflict, then the score.
CGContextGuard (dslim/distilbert-NER) checks borderline spaCy spans. It is off in balanced and fast, and on in strict and classic.

Quasi-identifier scorer per Sweeney (2000) k-anonymity

Flags combinations of fields that together can re-identify a person. The result is logged with the detections, and the terminal app shows a warning. The scorer does not change what gets replaced.

CombinationRiskSource
ZIP + DOB + Genderhigh87% of the US population uniquely identifiable (Sweeney 2000)
Postcode + DOBhighUK equivalent
Name + SSN · Name + DOBhighDirect identity pairing
Name + Employer + CitymediumProfessional cross-reference
Email / Phone / IP + Name or LocationmediumContact or network triangulation
DOB + Location + EmployermediumThree-field narrowing
03 / COVERAGE
PII types detected

Structured, named, and written in disguise. Thirteen public types.

Each public type groups finer internal types, for example ID covers ssn, passport, iban, vin and credit_card. Any type can be left alone with pii_off. On real chat text, SurrogateShield had the lowest or joint-lowest leak rate of every tool on 10 of the 13 types, and no leaks at all on 7 of them.

TypeExamplesValidatorSource
PERSONPriya Raman · my coworker Danarelation gatemodel
ORGMercy General (when you work there)relation gatemodel
LOCATIONTempe · “we live near Reno”relation gatemodel
ADDRESS1847 Alder Street, Portland, OR 97214 · SW1A 1AAZIP / postcode formatregex model
EMAILpriya.raman@northwind.io · priya at northwind dot iostructureregex
PHONE+1 415 555 0142 · +44 7911 123456 · in wordsformatregex model
URLhttps://priyaraman.dev/notes · hostnamesstructureregex
HANDLE@priyaraman—regex model
IDSSN · passport · VIN · card · IBAN · routing no. · licence · plate · cryptoLuhn · IBAN · VIN · ABAregex model
CREDENTIALsk-ant-… · ghp_… · AKIA… · passwordsprefix matchregex model
NETWORK192.168.1.100 · MAC addressesoctet boundsregex
AGE34 years oldphraseregex
DATE_OF_BIRTHMarch 14, 1991 · the 14th of Marchdateregex
Values written in another form. The canonicaliser also reads phone numbers written in words, e-mails spelled priya at northwind dot io, ordinal dates (the 14th of March), and text with full-width, look-alike or zero-width characters. The surrogate is written back in the same form. On formats that were held out while the detector was built (phones in words and month-ordinal birth dates), SurrogateShield missed 0 of 30 values and GLiNER-PII missed 3 of 30.
04 / GENERATION
MimicGen

Realistic surrogates, not [PLACEHOLDER] tokens.

Every surrogate has the same type and shape as the value it replaces, and stays the same for the whole session. Fake names look like names, a fake card passes Luhn, and a fake IBAN passes its checksum. The model reads a coherent message and writes a coherent reply, and that reply can be restored. Placeholder tools such as Presidio and GLiNER-PII send [PERSON] instead.

● ORIGINAL · user input
Hi, I'm Priya Raman. Email me at priya.raman@northwind.io or call +1 415 555 0142. My order NW-48213-K hasn't arrived at 1847 Alder Street, Portland. Can you draft a complaint to Northwind Outfitters?
● MASKED · sent to LLM
Hi, I'm Adya Nath. Email me at adya.nath@vance.io or call +1 213 581 8333. My order VW-02898-Z hasn't arrived at 6237 James Street, Olympia. Can you draft a complaint to Northwind Outfitters?

Real output of the default balanced preset. The company is kept because you only mention it, and the complaint still goes to the right company. Surrogates are drawn at random for each session; pass seed= for repeatable output.

ShadowMap — encrypted surrogate ↔ original

Kept in memory by default. With pii_mem set to a folder (or in the CLI and the app), it is saved as SSv1 ‖ nonce (12 bytes) ‖ AES-256-GCM ciphertext and cannot be read without the device key.

PERSON Priya Raman ↔ Adya Nath
EMAIL priya.raman@northwind.io ↔ adya.nath@vance.io
PHONE +1 415 555 0142 ↔ +1 213 581 8333
ID NW-48213-K ↔ VW-02898-Z
ADDRESS 1847 Alder Street, Portland ↔ 6237 James Street, Olympia
ORG Northwind Outfitters ↔ kept · only mentioned

What each type's surrogate looks like

Entity typeGenerated surrogate looks like
PERSONAdya Nath  — the same person gets the same name all session
EMAILadya.nath@vance.io  — built from the surrogate name
PHONE+1 213 581 8333  — same country code and grouping
ADDRESS9351 Meyer Street, Charlottesville, TN 19093
ID · ssn841-69-1543  — valid format
ID · credit_card4159 0830 1661 3181  — passes Luhn
ID · ibanDE02786579754323194875  — passes mod-97
ID · otherVW-02898-Z  — same letter and digit pattern
CREDENTIALsk-ant-api03-Hw90uUn0Hb8Ej6EtDu4Tx2Du  — prefix kept, rest random
NETWORK192.168.63.243  — same private range
URL · HANDLEhttps://forumrao.dev/notes · @forumrao
AGE · DATE_OF_BIRTH31 years old · June 26, 1991  — same format; a birth date moves by at most two years
05 / COMPARISON
Head to head · six other tools

Fewer leaks than every tool we tested. Fewer harmless edits too.

All tools ran on the same real ShareGPT, WildChat and oasst1 user messages, with the same scorer. The messages were sealed until the detector was final. 3,677 personal values were placed in 1,308 messages. SurrogateShield let 30 of them (0.8%) reach the provider. The others let through: GLiNER-PII tuned to 0.3, 7.3%; GLiNER-PII at its default 0.5, 9.1%; Microsoft Presidio, 31.6% (with Faker, the same); Presidio with the obi/deid_roberta_i2b2 transformer, 54.0%; LLM Guard, 56.3%. That is 11× fewer leaks than GLiNER-PII and 39× fewer than Presidio. The difference from GLiNER-PII is −8.3 points, with a 95% interval of [−9.3, −7.3]. Commands and every split: bench/results.

SurrogateShield

Realistic surrogates
Hi, I'm Adya Nath. Email me at adya.nath@vance.io or call +1 213 581 8333. My order VW-02898-Z hasn't arrived at 6237 James Street, Olympia. Can you draft a complaint to Northwind Outfitters?
Leaked, real chat text0.8%
Prompts sent fully clean97.4%
PII-free messages untouched88.5%
Nemotron-PII span F10.886

Microsoft Presidio

Placeholder redaction
Hi, I'm [PERSON]. Email me at [EMAIL_ADDRESS] or call [PHONE_NUMBER]. My order NW-48213-K hasn't arrived at [DATE_TIME] Alder Street, [LOCATION]. Can you draft a complaint to Northwind Outfitters?
Leaked, real chat text31.6%
Prompts sent fully clean30.8%
PII-free messages untouched59.6%
Nemotron-PII span F10.716

Both outputs are real runs on the same sentence. Presidio sent the order number and the street name in plain text and read the house number as a date. GLiNER-PII at 0.5 also sent the order number in plain text. It replaced the rest with [PERSON], [ADDRESS] and even [ORGANIZATION], so the complaint can no longer name the right company.

Every tool · same messages, same scorer

Leak, clean and spurious figures are on the injected slice: 3,677 values in 1,059 prompts and conversations (1,308 messages). Clean means the whole prompt or conversation reached the provider with no value left. Untouched means PII-free natural messages left unchanged (of 2,433). Odd formats are 530 values written the way a regex may not expect: lower-case names, an SSN without dashes, a phone number in words, an e-mail as "name at domain dot com". Nemotron is an outside dataset of 1,000 records. Speed is the median per message on CPU. Lower is better except for clean and untouched.

ToolLeakedCleanSpuriousUntouchedOdd-format leakNemotron leakp50 ms
SurrogateShield0.8%97.4%13.9%88.5%0.2%14.5%43.5
GLiNER-PII @0.37.3%79.5%41.3%20.0%7.5%22.5%79.9
GLiNER-PII @0.59.1%75.4%35.4%28.9%8.3%25.8%82.1
Presidio31.6%30.8%32.6%59.6%43.6%40.1%8.2
Presidio + Faker31.6%30.8%32.6%59.6%43.6%40.2%8.4
Presidio + RoBERTa54.0%11.7%22.0%70.9%66.0%56.6%83.5
LLM Guard56.3%9.1%16.4%83.9%61.5%61.0%58.0

SurrogateShield has the best number in every column except raw speed, where plain Presidio is faster. It is the fastest tool here that runs a transformer: 1.9× faster than GLiNER-PII, using about 970 MB less memory. Per dataset, its leak rate was 0.7% on oasst1, 0.9% on ShareGPT and 0.8% on WildChat. GLiNER-PII at 0.5 was 8.4%, 10.1% and 8.8%.

Leak rate by type · % of values sent in plain text

SurrogateShield is lowest or joint-lowest on 10 of the 13 types and leaks nothing on 7. It is behind GLiNER-PII on PERSON and LOCATION, and behind Presidio on URL.

Type (values)SSGLiNER 0.5GLiNER 0.3Presidio+ RoBERTaLLM Guard
ADDRESS 19708.67.197.093.9100
AGE 3260.30.90.640.869.3100
CREDENTIAL 19507.25.195.496.976.9
DATE_OF_BIRTH 19006.35.87.938.4100
EMAIL 30003.02.38.38.38.3
HANDLE 20206.93.593.186.682.7
ID 2481.233.125.422.222.252.0
LOCATION 2172.86.51.415.765.993.1
NETWORK 196018.416.3019.919.9
ORG 2543.58.75.585.473.691.7
PERSON 8671.20.30.110.676.521.3
PHONE 27203.73.39.29.25.9
URL 2130.546.945.10099.5
06 / EVALUATION
Benchmark · real chat text

Measured on real messages, sealed until the end.

The messages are real user turns from ShareGPT, WildChat and oasst1, held back until the detector was frozen. Personal values were placed using the halves of the word lists that were never used for building. Intervals are 95% bootstrap intervals with the conversation as the unit (2,000 resamples). Every number here can be rerun, and the commands are in bench/results/README.md.

M01
0.8%
Values leaked
30 of 3,677 placed values · GLiNER-PII 9.1% · Presidio 31.6%
M02
97.4%
Sent fully clean
1,031 of 1,059 prompts and conversations · GLiNER-PII 75.4% · Presidio 30.8%
M03
88.5%
PII-free messages untouched
2,153 of 2,433 natural messages · LLM Guard 83.9% · GLiNER-PII 28.9%
M04
0.2%
Odd-format leak
1 of 530 values in unusual formats · GLiNER-PII 8.3% · Presidio 43.6%
M05
14.5%
Nemotron-PII leak
Outside dataset, 4,627 values · span F1 0.886 · GLiNER-PII 25.8%
M06
81 / 82
Multi-turn restored
Surrogates put back over 60 conversations · Faker 0 / 80 · GLiNER-PII 0 / 54

Leak rate — values sent in plain text

3,677 values placed in 1,308 real messages (1,059 prompts and conversations), across 13 types. Shorter is better. Command: python -m bench.realdata.score --split test3 --out bench/results/realdata_test3.json.

SurrogateShield
0.8%
GLiNER-PII @0.3
7.3%
GLiNER-PII @0.5
9.1%
Presidio (± Faker)
31.6%
Presidio + RoBERTa
54.0%
LLM Guard
56.3%

BERTScore — are the answers still useful?

Each tool's masked version of 298 prompts was answered by claude-sonnet-4-6. The answer was compared with the answer to the original prompt (roberta-large, rescaled). SurrogateShield scored +0.077 [+0.053, +0.103] above Presidio + Faker and +0.072 [+0.046, +0.098] above GLiNER-PII. A judge model (claude-opus-5-5) preferred SurrogateShield's answer over Presidio + Faker's 195 times and the other way 62 times, with 39 ties: +0.449 [+0.355, +0.540]. Against GLiNER-PII it preferred SurrogateShield's answer 132 times and GLiNER-PII's 117 times, with 47 ties: +0.051 [−0.051, +0.152].

SurrogateShield
0.442
GLiNER-PII
0.369
Presidio + Faker
0.365
Presidio (placeholders)
0.358

On 150 natural prompts, most of which hold no personal data, SurrogateShield changed 23, Presidio 59 and GLiNER-PII 108. Answering the original prompt a second time scores 0.508. SurrogateShield's answers score 0.490, Presidio's 0.440 and GLiNER-PII's 0.365.

Multi-turn conversations

60 multi-turn conversations with personal values placed in them, 20 per dataset. Only SurrogateShield puts the values back in the replies, because the other tools keep no map.

ToolValues restoredFinal answer correct / partlyReal value sent upstream
SurrogateShield81 / 8232 / 185 / 150
GLiNER-PII0 / 542 / 530 / 150
Presidio + Faker0 / 800 / 1978 / 150

The judge preferred SurrogateShield's conversations by +0.576 [+0.467, +0.685] over Presidio + Faker and +0.649 [+0.527, +0.770] over GLiNER-PII.

Natural messages — harmless edits

2,476 natural messages, 2,433 of them with nothing to protect. Every change to those is a harmless word altered for no reason. GLiNER-PII at 0.5 makes 5.7× more of these than SurrogateShield. Every SurrogateShield operating point sits below and to the left of every GLiNER-PII threshold from 0.3 to 0.9, both pooled and per dataset.

ToolUntouched (of 2,433)Spurious edits / all edits
SurrogateShield2,153 · 88.5%1,053 / 1,389
LLM Guard2,041 · 83.9%1,391 / 1,710
Presidio + RoBERTa1,725 · 70.9%2,259 / 2,749
Presidio1,450 · 59.6%3,438 / 4,044
GLiNER-PII @0.5704 · 28.9%6,012 / 6,697
GLiNER-PII @0.3486 · 20.0%7,789 / 8,496

Nemotron-PII — an outside dataset

1,000 records and 4,627 values from a dataset none of the tools was built on. SurrogateShield has the lowest leak rate in all four strata: 11.9%, 12.5%, 16.9% and 16.8%.

ToolLeakedSpan F1
SurrogateShield14.5%0.886
GLiNER-PII @0.322.5%0.751
GLiNER-PII @0.525.8%0.758
Presidio40.1%0.716
Presidio + Faker40.2%0.716
Presidio + RoBERTa56.6%0.594
LLM Guard61.0%0.530

Speed and memory

200 messages on a 10-CPU Mac, warm. Plain Presidio is the fastest. Among tools that run a transformer, SurrogateShield is the fastest.

ToolMedian ms / messagePeak memory
Presidio8.21,084 MB
Presidio + Faker8.41,010 MB
SurrogateShield43.51,348 MB
LLM Guard58.01,565 MB
GLiNER-PII @0.379.92,333 MB
GLiNER-PII @0.582.12,318 MB
Presidio + RoBERTa83.51,611 MB

Presets and ablation

The same injected slice was run with each preset, and with one part of balanced switched off at a time. Even with every regex broken, the leak rate stays below Presidio's 31.6%.

ConfigurationLeakedUntouched (of 2,433)p50 ms
strict0.2%1,26467.1
balanced (default)0.8%2,15347.1
fast0.8%2,14738.2
classic (no tagger weights)2.5%1,88529.2
balanced, no pattern rules1.4%——
balanced, no canonicaliser3.9%——
balanced, no tagger10.8%——
balanced, no models15.7%——
balanced, every regex broken26.1%——
Limitations: it trailed on the 96 real values in natural text (29 leaked; GLiNER-PII 16–20, Presidio 27), on some single types (3 of 13 on test-3, 8 of 13 on Nemotron-PII, URL most of all) and on speed and memory (plain Presidio is about 5× faster and lighter); it came out ahead on every other test.
07 / ADVERSARIAL
Attacker experiment

Can an attacker model recover the originals?

claude-opus-5-5 was given the text each tool sent to the provider for 180 real prompts holding 636 placed values. It was told that a filter may have replaced some values, changed parts of others or left them alone, and asked to give back every original. A value counts as known if the tool left it in plain text or the attacker named it letter for letter. SurrogateShield let the attacker know 1.8% of the values. GLiNER-PII let it know 12.6%, Presidio 34.2% and LLM Guard 61.0%.

SURROGATESHIELD

The fewest values known, by far

  • Known letter for letter: 1.8% (11 of 627)
  • Left in plain text: 7 of 636
  • Recovered exactly: 4 of 620, all of them URLs
  • Across whole conversations: 1 of 177 recovered, 3 of 179 known
THE OTHER TOOLS

Most of the loss is text left in place

  • GLiNER-PII: 12.6% known (79 of 629), 73 left in plain text
  • Presidio: 34.2% known (215 of 629), 201 left in plain text
  • Presidio + Faker: 33.2% known (209 of 629)
  • LLM Guard: 61.0% known (383 of 628), 364 left in plain text
How to read this. SurrogateShield lets the attacker know 7× fewer values than GLiNER-PII and 19× fewer than Presidio. Its four exact recoveries, the fewest of all five tools, were all URLs whose surrogate changed one part of the host and kept the path. The attacker also guessed 98 parts of values that a SurrogateShield surrogate keeps on purpose: 38 e-mail domains, 19 organisation words such as "Pharmacy", 18 URL hosts, 14 address parts, 8 birth years and 1 area code. These are listed apart, not counted as recovered. Responder claude-sonnet-4-6, attacker claude-opus-5-5, one run. Command: python -m bench.realdata.attacker_exact --split test3, details in bench/results.

Per tool

ToolLeft in plain textRecovered exactlyKnown letter for letter
SurrogateShield74 / 62011 / 627 · 1.8%
GLiNER-PII736 / 55679 / 629 · 12.6%
Presidio + Faker2018 / 428209 / 629 · 33.2%
Presidio20114 / 428215 / 629 · 34.2%
LLM Guard36419 / 264383 / 628 · 61.0%
08 / SECURITY
Cryptographic design

Local-only key material. AES-256-GCM on every write.

The map from surrogates back to your values is kept on your machine. In the library it lives in memory unless you give it a directory. On disk it is sealed with a key derived from a device secret that is never sent anywhere, and a file that will not decrypt raises an error instead of quietly becoming an empty map.

KEY MATERIAL

Device secret + per-store derivation

  • 32 random bytes at ~/.surrogateshield/device.key, created once
  • File mode 0600, home directory 0700
  • Per-store key: HKDF-SHA256, device secret as input, store id as salt, file kind as info
  • If the secret cannot be saved, an error is raised rather than using a throwaway key
SHADOWMAP

Sealed surrogate ↔ original store

  • Format: SSv1 ‖ nonce (12 B) ‖ AES-256-GCM, fresh nonce on every save
  • Kind and id are bound in as associated data, so a file only opens as what it was written for
  • Atomic writes: temp file, fsync, rename
  • Undecryptable file → moved aside, CorruptStoreError raised
TRANSMISSION

What goes over the wire

  • Detected values are sent over HTTPS as surrogates
  • Conversation history is sealed the same way as the ShadowMap
  • RAG documents go through SentinelLayer before they are indexed
  • Missing tagger weights raise DetectorUnavailable; nothing is sent half-checked
.GITIGNORE

What is excluded by default

  • conversations/ and *.shadowmap — history and sealed maps
  • *.key, .surrogateshield/ — the device secret
  • .env — API keys
  • Raw benchmark data and live-run outputs
09 / RAG
Privacy-aware retrieval

Documents are anonymised at index time.

Local RAG via ChromaDB + sentence-transformers (all-MiniLM-L6-v2), in process, with no server. Detected values are replaced before a document is indexed, so the index holds surrogates.

rag.index — at index time chromadb in-process
document.txt
    │
    ▼
SentinelLayer  ▸ detect PII
    │
    ▼
MimicGen      ▸ generate surrogates
    │
    ▼
rag_global ShadowMap
   { surrogate → original } persisted
    │
    ▼
Anonymised document
    │
    ▼
chunk @ RAG_CHUNK_SIZE = 512
    │
    ▼
sentence-transformers
   all-MiniLM-L6-v2
    │
    ▼
ChromaDB  ▸ ~/.surrogateshield/rag
rag.query — at query time top-k = 3
user query
    │
    ▼
SentinelLayer  ▸ anonymise query
    │
    ▼
embed ▸ ChromaDB ▸ retrieve top-3
    │
    ▼
Prepend anonymised context
    │
    ▼
LLM API  ← receives the masked text
    │
    ▼
ResolvePass
   restores your values + document values
   via rag_global ShadowMap
    │
    ▼
Display to user
10 / ARCHITECTURE
Project structure

One engine in python-library. The app and the benchmark use it.

Detection, surrogates, storage and restore live once, in the package. The terminal app's modules are thin wrappers that read config.py, and the benchmark runs the same code against the other tools.

SurrogateShield/
├── python-library/          # The engine: pip install ./python-library
│   └── surrogateshield/
│       ├── __init__.py      # config · scan · mask · unmask · forget · flush
│       ├── session.py       # Session — sync and async
│       ├── cli.py           # scan · mask · unmask · bench · doctor · download
│       └── core/
│           ├── detection/   # SentinelLayer
│           │   ├── pipeline.py      # stages, passes, relation gate, resolver
│           │   ├── config.py        # presets: fast · balanced · strict · classic
│           │   ├── pattern_scan.py  # PatternScan — regex + validators
│           │   ├── canonical.py     # views of spaced, spelled-out and obfuscated values
│           │   ├── entity_trace.py  # EntityTrace — spaCy en_core_web_lg
│           │   ├── pii_tagger.py    # PIITagger — DeBERTa-v3-small
│           │   ├── context_guard.py # ContextGuard — distilbert-NER
│           │   ├── structural.py    # Passes A–H and S
│           │   └── service_query.py # address shift for service queries
│           ├── generation/  # MimicGen — same-shape surrogates, no collisions
│           ├── storage/     # ShadowMap — AES-256-GCM
│           └── reconstruction/ # ResolvePass — exact · component · fuzzy
│
├── main.py                  # Terminal app: dashboard and commands
├── pipeline.py              # App message flow: mask, send, restore
├── config.py                # App settings: models, thresholds, paths
├── detection/ generation/   # Wrappers over the package
├── storage/ reconstruction/ # Wrappers over the package
├── chatbot/
│   ├── chat.py              # Claude / Gemini / OpenAI / Ollama, sealed history
│   └── rag.py               # RAGStore — Chroma + sentence-transformers
├── presidio/                # Side-by-side comparison in the app
│
├── bench/                   # The benchmark
│   ├── arms/                # SS, GLiNER-PII, Presidio (+ Faker, RoBERTa), LLM Guard
│   ├── realdata/            # build, inject, label, score, live runs
│   ├── perf_arms.py         # speed and memory per tool
│   └── results/             # every committed number + README of commands
│
└── tests/                   # pytest, no API key needed
11 / INSTALL
Quick start

Up and running in a few commands.

Activate a virtual environment before installing. Installing into the system or base conda Python is the most common cause of "package not found" errors at runtime. Then run surrogateshield doctor: it checks that every detection stage loads before you send anything.

terminal · bash installation
# Clone
$ git clone https://github.com/sherwinvishesh/SurrogateShield.git
$ cd SurrogateShield

# Create and activate a virtual environment  ← required
$ python -m venv .venv
$ source .venv/bin/activate           # Windows: .venv\Scripts\activate

# App + library (editable) + benchmark dependencies
$ pip install -r requirements.txt

# Library only, for your own code
$ pip install ./python-library
$ python -m spacy download en_core_web_lg

# Fetch the PIITagger weights now (~565 MB, Hugging Face);
# otherwise the first scan downloads them once
$ surrogateshield download

# Check every stage
$ surrogateshield doctor

# Set your API key and launch the terminal app
$ echo "ANTHROPIC_API_KEY=sk-ant-..." > .env
$ ./run.sh
No tagger weights? The default preset downloads them from Hugging Face once; if it cannot (no network, or HF_HUB_OFFLINE with nothing cached), it stops with DetectorUnavailable rather than run without them. Use preset="classic", which needs only spaCy and ContextGuard's dslim/distilbert-NER (downloaded from Hugging Face on first use). It leaked 2.5% on the benchmark, still far below GLiNER-PII's 9.1%. To use only the engine in your own code, see Library.

Supported providers

ProviderModelEnv var
Claude defaultclaude-sonnet-4-6ANTHROPIC_API_KEY
Geminigemini-2.5-flashGEMINI_API_KEY
ChatGPTgpt-4o-miniOPENAI_API_KEY
Local (Ollama)llama3.2 (configurable)none — offline

Each model can be changed without editing code: SURROGATESHIELD_CLAUDE_MODEL, SURROGATESHIELD_GEMINI_MODEL, SURROGATESHIELD_OPENAI_MODEL, LOCAL_LLM_MODEL.

12 / CLI
Dashboard reference

Press a key. Do a thing.

terminal · bashcommands
# Interactive dashboard (recommended)
$ python main.py
$ ./run.sh

# Start a new conversation directly
$ python main.py chat
$ python main.py chat --load <conversation-id>
$ python main.py chat --rag

# PII detection sandbox — no API calls, no credits
$ python main.py pii-finder

# Index a document into the RAG store
$ python main.py add-doc path/to/document.txt
terminal · bashsurrogateshield · library cli
# List what would be masked (no provider call)
$ surrogateshield scan "Call Priya on +1 415 555 0142" --json

# Mask: prints the text to send, and the session id on stderr
$ surrogateshield mask --preset fast < prompt.txt

# Put the originals back in the reply; --close erases the stored map
$ surrogateshield unmask -s <session-id> --close < reply.txt

# Latency on built-in samples · check models, dependencies, key storage
$ surrogateshield bench
$ surrogateshield doctor --smoke

Dashboard shortcuts

NNew conversation
RRAG mode
PPII Finder — no API
JJSON Test batch
EEvaluation — vs a key file
AAttacker experiment
SSettings — provider, view, Presidio
HHelp
1–9Open saved conversation
D1–9Delete conversation
QQuit
13 / LIBRARY
Standalone package

The whole engine, in pip install ./python-library.

No dashboard, just the detection and masking engine as a Python API. The package is self-contained: it imports nothing from the terminal app, which is built on top of it. Use a Session per conversation, or the module functions for a quick script. It is the same engine that leaked 0.8% on real chat text, against 9.1% for GLiNER-PII and 31.6% for Presidio.

terminal · bashinstall
# From the repository root
$ pip install ./python-library
$ python -m spacy download en_core_web_lg

# Optional: Rich colour tables for detected PII / surrogates
$ pip install "./python-library[display]"

# Optional: fetch the PIITagger weights now (else on first use)
$ surrogateshield download

# Check that every stage loads
$ surrogateshield doctor
Models. The default preset, balanced, needs spaCy's en_core_web_lg and the PIITagger weights, sherwinvishesh/surrogateshield-pii-tagger on Hugging Face (~565 MB, MIT). The weights download once on first use, or with surrogateshield download, and are checked against their SHA-256 pin; a folder of the same name under $SURROGATESHIELD_MODELS is used instead when there is one. If either model is missing or cannot be fetched, mask() raises DetectorUnavailable and sends nothing. On a machine without the tagger weights, use preset="classic".

Public API

FunctionDescription
shield.Session(id, *, config, storage_dir, seed)Masking state for one conversation. Use it as a context manager; amask / aunmask / ascan for asyncio
shield.config(**kwargs)Preset, storage, pii_off, address mode and display settings for new sessions and the current one
shield.scan(text)Detect only: a list of Detection (text, type, start, end, score, source, masked); as_dict=True for {value: type}. Alias pii_finder
shield.mask(text)Replace detected values with surrogates and store the mapping; returns the text to send
shield.mask_result(text)Like mask, plus the detections, the replacements, and the pii_off values sent as typed
shield.unmask(response)Restore your values in a reply: a string, or an Anthropic, OpenAI or Gemini response object
shield.forget(original)Erase every mapping for one value from the session
shield.flush()End the current session: discard its mappings and its file, if any

Quick start — a full round-trip

python · claudemask ▸ call ▸ unmask
import anthropic
import surrogateshield as shield

client = anthropic.Anthropic()

text = (
    "Hi, I'm Priya Raman. Email me at priya.raman@northwind.io or call "
    "+1 415 555 0142. My order NW-48213-K hasn't arrived at 1847 Alder "
    "Street, Portland. Can you draft a complaint to Northwind Outfitters?"
)

with shield.Session() as s:
    sanitized = s.mask(text)
    # → "Hi, I'm Adya Nath. Email me at adya.nath@vance.io or call
    #    +1 213 581 8333. My order VW-02898-Z hasn't arrived at 6237
    #    James Street, Olympia. Can you draft a complaint to Northwind
    #    Outfitters?"   (surrogates differ per run; pass seed= to fix them)

    response = client.messages.create(
        model="claude-sonnet-5-5", max_tokens=1024,
        messages=[{"role": "user", "content": sanitized}],
    )

    # unmask() takes the SDK object directly and puts your values back
    print(s.unmask(response))   # the letter is signed "Priya Raman"
# leaving the block discards the map

The provider receives the surrogates for every value the detector found; the answer you see has your own values back. The company you are complaining to is kept, because it is only mentioned. The same flow works with OpenAI, Gemini and local Ollama models; unmask() detects the response format.

INSPECT

scan() — detect without masking

Runs the full pipeline and returns each detection with its offsets, type, score and the stage that found it. It never changes the text or the session's map.

  • masked=False marks a value kept by pii_off
  • pii_finder alias for data-pipeline readability
  • Pre-warm the models with shield.Session().scan("warm up")
PRESETS

Pick the trade-off

shield.config(detection="fast"), or SURROGATESHIELD_PRESET in the environment. Benchmark leak and median time per message:

  • balanced (default) — 0.8%, 47.1 ms
  • fast — 0.8%, 38.2 ms, no spaCy
  • strict — 0.2%, 67.1 ms, edits far more harmless text
  • classic — 2.5%, 29.2 ms, no tagger weights needed
PERSISTENT

Encrypted disk shadow map

The default is in memory. Give a directory and the map persists across processes, sealed with AES-256-GCM, for web servers and multi-worker setups.

  • shield.Session("user-42", storage_dir="/var/app/maps")
  • The same id reopens the same map
  • Key derived from the device secret (HKDF-SHA256), file mode 0600
  • flush() or close() deletes the .shadowmap file
PORTABLE

Any provider, any object

unmask() reads Anthropic, OpenAI and Gemini response objects and dicts, and plain strings from local models.

  • Anthropic Message · OpenAI ChatCompletion · Gemini response
  • Multi-turn: the session map lives across turns
  • 13 public types, the same pipeline as the terminal app

Multi-turn conversations

Keep two histories: one in surrogates for the API, one with your values for display. The session map lives across turns, so a surrogate made in turn 1 still resolves in turn 5. On the benchmark's 60 conversations, SurrogateShield put back 81 of 82 values; Presidio + Faker and GLiNER-PII put back none.

python · openaitwo histories, one session
from openai import OpenAI
import surrogateshield as shield

client = OpenAI()
session = shield.Session()
api_history, display_history = [], []   # surrogates vs your values

def chat(user_input):
    sanitized = session.mask(user_input)
    api_history.append({"role": "user", "content": sanitized})
    display_history.append({"role": "user", "content": user_input})

    response = client.chat.completions.create(
        model="gpt-4o-mini", messages=api_history,
    )
    raw = response.choices[0].message.content   # surrogate text
    restored = session.unmask(response)          # your values

    api_history.append({"role": "assistant", "content": raw})
    display_history.append({"role": "assistant", "content": restored})
    return restored

chat("My name is Priya Raman and I live at 1847 Alder Street, Portland.")
print(chat("What was the address I mentioned earlier?"))
# → "1847 Alder Street, Portland", restored from turn 1's map
session.close()

One pattern, every provider

pythonasyncio · gemini · ollama / local
# asyncio — the models run in a worker thread
async with shield.Session() as s:
    sanitized = await s.amask(user_text)
    restored = await s.aunmask(await llm.achat(sanitized))

# Google Gemini — unmask() reads response.text
model = genai.GenerativeModel("gemini-2.5-flash")
sanitized = shield.mask("My card is 4532015112830366, IP 192.168.1.100.")
print(shield.unmask(model.generate_content(sanitized)))
shield.flush()

# Local / Ollama — unmask() also accepts a plain string
sanitized = shield.mask("My phone is +44 7911 123456, postcode SW1A 1AA.")
raw_reply = ask_ollama(sanitized)              # your own HTTP call
print(shield.unmask(raw_reply))
shield.flush()

unmask() — three reconstruction passes

Each pass only runs on surrogates the previous one did not resolve, so partial matches never corrupt unrelated text.

PassMethodHandles
1exact replacementSurrogate appears verbatim in the response — the vast majority of cases
2component matchingMulti-word surrogate used partially (the model wrote "Adya" from "Adya Nath") — scoped to unresolved surrogates only
3fuzzy · rapidfuzzpartial_ratio ≥ fuzzy_threshold (default 85) — reformatted casing, added punctuation, minor edits

config() — full parameter reference

ParameterDefaultEffect
detectionNoneA preset name ("fast", "balanced", "strict", "classic"), a DetectionConfig or a dict. None = the environment's choice, else balanced
detailed_viewFalsePrint Rich tables after each call. They show your original values, so it is off by default
pii_mem"temp""temp" = in memory; an existing directory = sealed AES-256-GCM files
pii_off[]Types detected but sent as typed — aliases or raw type strings
serviceTrueRecognise service queries ("pharmacies near…"); drives address_mode="auto"
address_mode"auto""auto": shift in a service query, replace otherwise · "shift": always shift the house number · "replace": always a fake address of the same shape
address_shift_range1Largest house-number change in shift mode
spacy_modelen_core_web_lgEntityTrace model
context_guard_enabledFalseRun distilbert-NER as well; on in strict and classic
entity_trace_high_threshold0.90spaCy type score at/above which an entity is confirmed
entity_trace_low_threshold0.70spaCy type score at/above which an entity is borderline
context_guard_threshold0.70distilbert score required to confirm a borderline entity
entity_trace_fallback_threshold0.75Promotes a borderline entity when ContextGuard is off
fuzzy_threshold85rapidfuzz partial_ratio (0–100) for pass 3 of unmask() — below 70 not recommended
context_guard_model / _devicedslim/distilbert-NER · -1ContextGuard model and device (-1 = CPU, ≥ 0 = GPU id)
tagger_model / _revision / _devicepii-tagger-dv3s-40k · sha256:f9e58… · -1PIITagger: a name, local folder or Hugging Face id; a sha256: pin or a commit; CPU, GPU id or "mps"
PII_OFF ALIASES

Short names, expanded

phonephone_us · phone_uk · phone_intl
postal_codezip_us · postcode_uk
name / namesPERSON
locationGPE · LOC
org · facilityORG · FAC
username · passwordhandle · credential
bank · license · cryptous_bank_number · us_driver_license · crypto
SERVICE QUERIES

Proportional address protection

A question like "find a coffee shop near 99 Market Street" would be useless with a random fake address. With address_mode="auto" (default), a service query keeps the street and city and shifts the house number by ±1.

  • House number shifted, street and city kept
  • Sensitive topics (HIV, abortion, rehab, therapy, shelter, immigration…) turn the street into my area
  • Any other message: a full fake address of the same shape
  • shield.config(service=False) or address_mode="replace" to always replace

Quasi-identifier combination scoring Sweeney k-anonymity

When one of these combinations appears in a message, the match is logged and attached to the detection result as a warning. It does not change what gets replaced.

CombinationRiskBasis
ZIP + DOB + Genderhigh87% of US population uniquely identified — Sweeney 2000
Postcode + DOBhighUK ICO guidance — sufficient for re-identification
Name + SSNhighEnables direct identity theft
Name + DOBhighStandard identity-verification combination worldwide
Phone + NamehighDirectly identifies an individual
IP Address + NamehighEnables device-level identification
Name + Employer + CitymediumUniquely identifies in most cities
Email + LocationmediumNarrows to a specific named individual
Phone + LocationmediumNarrows to a local individual
DOB + Location + EmployermediumHighly specific triple
DEPENDENCIES

Installed with the package

fakerRealistic fake values per type
cryptographyAES-256-GCM for the disk shadow map
rapidfuzzFuzzy reconstruction pass
spacyEntityTrace; the model is a separate download
transformers + torchPIITagger and ContextGuard
TROUBLESHOOTING

Common adjustments

  • DetectorUnavailable? Run surrogateshield doctor; it names the missing model
  • Slow first call? Models load lazily — pre-warm with shield.Session().scan("warm up")
  • Need it faster? shield.config(detection="fast"): same leak rate on the benchmark, no spaCy
  • Surrogate not restored? Lower fuzzy_threshold toward 75 to recover heavily reformatted values
  • distilbert (~250 MB) downloads once to ~/.cache/huggingface/ when ContextGuard is on
Tested with no API key. pytest tests python-library/tests covers the package end to end: detection, surrogates, ShadowMap memory and disk modes, the response parser, pii_off, presets, ResolvePass, the CLI and the public API.
14 / CITE
Citation

Cite this work.

The first version of SurrogateShield is described in a preprint on arXiv. The numbers on this page come from the v2 benchmark in bench/results/, not from the preprint. Pick a format and copy — BibTeX is the default.