Metadata-Version: 2.4
Name: blackbar-redact
Version: 0.1.2
Summary: Reversible redaction of sensitive values in text: mask before you paste, unmask the answer.
Author: blackbar contributors
License: MIT
Project-URL: Homepage, https://github.com/RealAoss/blackbar
Project-URL: Issues, https://github.com/RealAoss/blackbar/issues
Keywords: redaction,privacy,pii,anonymization,secrets,llm
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Security
Classifier: Topic :: Text Processing :: Filters
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# blackbar

Reversible redaction of sensitive values in text.

Mask email addresses, phone numbers, keys and other values before you paste a
text into an AI assistant, a ticket or a chat. Keep the mapping in a local
vault. Put the real values back into the answer.

> **blackbar does not detect names of people.** It has no language model. It
> is a set of regular expressions and checksums. A name, a company or a
> project is masked only if you list it yourself (`terms`). It does not
> promise to find everything else either. Read the masked text before you
> send it. See [What it does not do](#what-it-does-not-do).

Python 3.10 or newer, standard library only, no network access.

## The problem

Asking an assistant about a customer ticket, a log or a config file is useful.
Pasting the ticket also hands over the customer's email address, their phone
number, the server's IP address and sometimes a password. Deleting those by
hand is slow, and afterwards the answer talks about "the customer" and you
have to put everything back yourself.

blackbar replaces each value by a stable placeholder such as `[EMAIL_1]`, so
the text keeps its meaning ("the same address appears twice"), and restores
the values in whatever comes back, even if the assistant changed the
placeholder's case or wrapped it in Markdown.

## Example: mask, ask, unmask

```python
>>> from blackbar import mask, unmask
>>> ticket = """Customer Maria Example (maria@example.com, +1 202 555 0164) cannot log in.
... She connects from 198.51.100.23 and her temporary password: Tmp-Example-553
... Logs are in C:\\Users\\mexample\\AppData\\Local\\acme\\app.log"""
>>> m = mask(ticket, terms=["Maria Example", "acme"])
>>> print(m.text)
Customer [TERM_1] ([EMAIL_1], [PHONE_1]) cannot log in.
She connects from [IP_1] and her temporary password: [SECRET_1]
Logs are in C:\Users\[USER_1]\AppData\Local\[TERM_2]\app.log

```

`m.text` is what you paste. Without `terms=[...]` the name and the company
would have stayed in the text. The assistant answers with placeholders, not
always spelled the way it received them:

```python
>>> answer = "Tell **[TERM_1]** to reset it. [email_1]'s account and [PHONE 1] look fine; ignore [EMAIL_9]."
>>> print(unmask(answer, m.vault))
Tell **Maria Example** to reset it. maria@example.com's account and +1 202 555 0164 look fine; ignore [EMAIL_9].

```

`[EMAIL_9]` is not in the vault, so it is left alone. `unmask_report` tells
you about it:

```python
>>> from blackbar import unmask_report
>>> unmask_report(answer, m.vault).unknown
['[EMAIL_9]']

```

## Install

```sh
pip install git+https://github.com/RealAoss/blackbar
```

blackbar is not published on a package index; the line above installs it from
the repository. It has no dependencies. You can also copy `src/blackbar` into
a project.

## Python API

### `mask(text, *, kinds=None, terms=None, vault=None) -> Masked`

- `kinds`: which detectors to run, by the names shown by `blackbar kinds`.
  `None` is the default set. The words `"default"` and `"all"` are accepted,
  so `kinds=["default", "uuid"]` adds one.
- `terms`: literal strings to mask. Matched case-insensitively on word
  boundaries, in any script. For Arabic terms the prefix clitics و ف ب ل ك
  and the article ال may be attached and stay outside the placeholder
  (`arabic_clitics=False` turns this off).
- `vault`: pass the same `Vault` again to keep placeholders stable across
  calls.
- `min_confidence`: drop findings below a confidence (0 to 1, default 0).

The result has `.text`, `.vault`, and `.findings`, a list of `Finding` with
`kind`, `start`, `end`, `span`, `confidence` and `placeholder`:

```python
>>> [(f.kind, f.span, f.confidence) for f in m.findings][:3]
[('term', (9, 22), 1.0), ('email', (24, 41), 0.95), ('phone', (43, 58), 0.9)]
>>> m.counts
{'term': 2, 'email': 1, 'phone': 1, 'ip': 1, 'secret': 1, 'user': 1}

```

The same value gets the same placeholder, also when it is spelled slightly
differently: email letter case, phone numbers with other spacing, dashes or
Arabic-Indic digits, IBANs with or without spaces, card numbers with or
without separators. Different values never share a placeholder.

Exactly these spellings are merged, after Unicode NFC (canonical
composition, so a precomposed `é` and `e` + combining accent are one
spelling); compatibility forms are never folded, so `x²` and `x2`, or the
`ﬁ` ligature and `fi`, stay different values:

| kind | merged |
|---|---|
| `email`, `domain`, `uuid` | letter case (`str.lower`) |
| `url` | letter case of the scheme and the host |
| `phone` | spaces and punctuation, Arabic-Indic and Persian digits, a leading `00` read as `+` (more than ten digits) |
| `iban` | spaces, ASCII letter case |
| `card`, `mac` | spaces and punctuation (and letter case for `mac`) |
| `ip` | the canonical form of the address (`2001:0DB8::0:1` = `2001:db8::1`) |
| `term` | letter case (`str.lower`, so `Straße` and `STRASSE` stay different), Arabic and Hebrew diacritics and tatweel, runs of whitespace |
| `secret`, `entropy`, `user` | nothing |

```python
>>> two = mask("Call +1 202-555-0164 or +1 (202) 555 0164")
>>> two.text
'Call [PHONE_1] or [PHONE_1]'

```

There is a price for that, and it is the one exception to an exact round
trip: both occurrences come back in the spelling that was seen first.
`Masked.exact` is `False` when this happened.

```python
>>> two.exact
False
>>> unmask(two.text, two.vault)
'Call +1 202-555-0164 or +1 202-555-0164'

```

Arabic text and digits:

```python
>>> print(mask("أرسلت العقد لسلمى على ٠٧٧٠٠ ٩٠٠١٢٣", terms=["سلمى"]).text)
أرسلت العقد ل[TERM_1] على [PHONE_1]

```

Names are not found unless you pass them:

```python
>>> mask("Omar Sample called.").text
'Omar Sample called.'
>>> mask("Omar Sample called.", terms=["Omar Sample"]).text
'[TERM_1] called.'

```

### `unmask(text, vault) -> str`

Restores the original values. It tolerates what language models do to
placeholders: other letter case (`[email_1]`), spaces (`[ EMAIL 1 ]`), a dash
or nothing instead of the underscore, a Markdown-escaped underscore or
brackets (`\[EMAIL\_1\]`), bold, italics or backticks around or inside the
brackets, a possessive or plural suffix (`[EMAIL_1]'s`), full-width brackets
and letters, Arabic-Indic digits in the number.

It does not restore a placeholder whose brackets were removed (`EMAIL_1`) or
replaced by other brackets (`(EMAIL_1)`, `<EMAIL_1>`).

`unmask_report(text, vault)` returns `.text`, `.restored` (a count) and
`.unknown` (placeholders that are not in the vault; they are left untouched).

### `Vault`

**The vault contains the secrets.** It maps every placeholder to its original
value. A saved vault file is plain, unencrypted JSON with all of them in it.
Keep it private, do not commit it, delete it when you are done.

blackbar never writes a vault on its own. You choose the path:

```python
>>> import os, tempfile
>>> from blackbar import Vault
>>> with tempfile.TemporaryDirectory() as folder:
...     path = os.path.join(folder, "vault.json")
...     m.vault.save(path)          # mode 0600 where the OS supports it
...     later = Vault.load(path)
>>> unmask("[IP_1]", later)
'198.51.100.23'

```

On Windows the POSIX mode bits are mostly ignored and the file gets the
permissions of its folder.

`a.merge(b)` adds the entries of another vault. If both vaults used the same
placeholder for different values, the incoming one is renumbered and the
method returns the mapping `{placeholder in b: placeholder in a}`.

**Keyed mode.** `Vault(key=...)` derives the identifier from
`HMAC-SHA256(key, kind + NUL + normalised value)` instead of counting.
Separate runs with the same key then agree on the placeholders without
sharing a vault:

```python
>>> key = "a long random string that is kept out of the repository"
>>> a = mask("mail maria@example.com", vault=Vault(key=key))
>>> b = mask("MARIA@example.com wrote", vault=Vault(key=key))
>>> a.findings[0].placeholder == b.findings[0].placeholder
True
>>> len(a.findings[0].placeholder)        # "[EMAIL_" + 10 hex digits + "]"
18

```

If the input already contains placeholder-looking text, `mask` leaves it
alone in both modes and never hands that placeholder out, including every
form `unmask` would read as it (`[EMAIL_01]` and `[email 1]` both count as
`[EMAIL_1]`). In numbered mode the next free number is used; in keyed mode
the value gets a longer prefix of its HMAC (12 hex digits or more), so in
that run its placeholder differs from the one other runs give it.

Each run still needs its own vault to restore its values. The key is never
written to the vault file. Whoever has the key can test whether a placeholder
stands for a value they guess; see `SECURITY.md`.

### `scan(text, ...)` and `redact(kind, value)`

`scan` returns the findings without changing anything. `redact` gives a short
hint that is safe to print:

```python
>>> from blackbar import scan, redact
>>> text = "ping 192.0.2.7 or jane@example.com"
>>> [(f.kind, redact(f.kind, text[f.start:f.end])) for f in scan(text)]
[('ip', '1***'), ('email', 'j***@e***.com')]

```

## Command line

```sh
blackbar mask ticket.txt --vault vault.json --terms-file terms.txt -o ticket.masked.txt
blackbar unmask answer.txt --vault vault.json -o answer.restored.txt
blackbar scan ticket.txt --terms-file terms.txt
blackbar kinds
```

- `mask [FILE|-] --vault PATH [--kinds LIST] [--exclude LIST] [--terms-file PATH] [--term TEXT] [--min-confidence X] [--key-env NAME] [-o OUT] [--force] [-q]`
  reads the file or standard input, creates or extends the vault, writes the
  masked text to `OUT` or standard output. The summary on standard error
  counts the values and never shows them.
- `unmask [FILE|-] --vault PATH [-o OUT] [--force] [--strict]` restores.
  Placeholders that are not in the vault are listed on standard error;
  `--strict` makes that exit status 3.
- `scan [FILE|-] [--kinds ...] [--terms-file ...] [--json] [--fail-on-findings]`
  only reports. Values are shown redacted, never in full.
- `kinds` lists the kinds; `kinds --aliases` also lists other accepted names
  (`ipv4`, `credit_card`, ...).

`--terms-file` is a UTF-8 file with one term per line; lines starting with `#`
are comments. `--key-env NAME` switches to keyed mode and reads the key from
the environment variable `NAME`, so that it does not end up in the shell
history.

An existing output file is never overwritten unless you pass `--force`, and
the output may not be the input or the vault. Input and output are UTF-8 on
every platform, including the Windows console; line endings are kept as they
are.

For the ticket of the example above, with `Maria Example` and `acme` in
`terms.txt`, `blackbar scan ticket.txt --terms-file terms.txt` prints
(line:column, kind, confidence, hint):

<!-- scan-output -->
```text
1:10	term	1.00	M***
1:25	email	0.95	m***@e***.com
1:44	phone	0.90	+***64
2:19	ip	0.90	1***
2:61	secret	0.80	*** (15 chars)
3:22	user	0.85	m***
3:45	term	1.00	a***
```

In a pipe (`your-assistant` stands for whatever you use):

```sh
cat ticket.txt | blackbar mask --vault vault.json | your-assistant | blackbar unmask --vault vault.json
```

## Detectors

Confidence is a rough, hand-assigned number, not a calibrated probability.
"Default" says whether the kind runs when you do not pass `kinds`.

| Kind | Default | What is matched | Strong at | Weak at |
|---|---|---|---|---|
| `email` | yes | ASCII addresses with a dotted domain | ordinary addresses, `+tags`, subdomains; skips `logo@2x.png` | non-ASCII local parts; `user@localhost`; obfuscated forms (`a [at] b`); the display name next to an address is not touched; `git@host` is masked as an address |
| `url` | yes | anything `scheme://...`, and `www.` hosts; the whole URL becomes one placeholder, including `user:pass@` | trailing punctuation, brackets, Markdown links, Arabic punctuation | `example.com/path` without scheme or `www.` is not a URL here; the whole URL is hidden, so the assistant cannot see its path. With `kinds` that leave out `url`, only the password inside `scheme://user:pass@host` is masked, as a secret |
| `ip` | yes | IPv4 with four parts 0-255 and no leading zeros; IPv6 validated by the standard library | documentation, private and public ranges; `::ffff:` forms; ports and `/24` stay outside | **Version numbers.** `1.2.3.4` after `version`, `v`, `build`, `release`, a `name/` prefix (user agents) or before `-beta` is skipped, but a bare four-part version such as `node 20.11.0.1` is taken for an address (confidence 0.6 or 0.9 depending on the numbers). Loopback, `0.0.0.0` and netmasks are deliberately not masked. Short IPv6 forms like `a::b` have low confidence |
| `mac` | yes | `aa:bb:cc:dd:ee:ff`, `aa-bb-...`, `aabb.ccdd.eeff` | separators | 12 hex digits without separators are not matched; six dash-separated decimal pairs can be something else (confidence 0.7) |
| `phone` | yes | `+` international (9-15 digits, `+1`/`+7` exactly 11); `00` international with separators; North American `(202) 555-0164` shapes; grouped national numbers with a leading zero (10-11 digits); any 7-15 digit number right after a phone word (phone, tel, mobile, fax, WhatsApp, call ... on; هاتف, جوال, موبايل, ...); Western, Arabic-Indic and Persian digits | **Precision is preferred.** Dates, times, timestamps, prices, epoch values, ISBNs, and national-format numbers right after order / invoice / ticket / ref / id / tracking / SKU (and Arabic طلب, فاتورة, ...) are not flagged | **This is the hard one.** Unformatted national digits with no phone word (`02079460777`) are missed. A grouped leading-zero number that is something else (`Lot 0412 345 6789`) is flagged at confidence 0.7. Local formats that are neither `+`, leading-zero nor North American are missed without a phone word. National and international spellings of one number get different placeholders. A short number right after a `+` number may be absorbed into it. No per-country numbering plan is used |
| `card` | yes | 12-19 digits, optional uniform spaces or dashes in card-like groups, Luhn checksum, and a known scheme prefix and length | public test numbers of the main schemes, Arabic-Indic digits | prefix table written from memory; the broad Maestro range has confidence 0.6; any other 16-digit number that happens to pass Luhn with a card prefix is flagged (about 1 in 10 of such numbers) |
| `iban` | yes | two capitals, two digits, then the country's length, with or without single spaces; mod-97 checksum | exact length per country for the 77 codes in the table | table written from memory; a country that is not in it is accepted on the checksum alone at confidence 0.6; lower-case IBANs are not matched |
| `secret` | yes | private-key blocks; JSON Web Tokens; `Authorization:` header values and `Bearer <token>`; values of `key=value` / `key: value` / JSON pairs whose key contains a secret word (password, passwd, pwd, passphrase, secret, token, api_key, access_key, private_key, credentials, session id, pin, otp ...); `--password VALUE` flags; `CVV 123`, `PIN 4821`; the password in `scheme://user:pass@host`; token prefixes listed below; Arabic `كلمة المرور: ...` | only the value is masked, the key stays; skips `max_tokens`, `token_type`, `password_policy`, placeholders like `<token>`, `${VAR}`, `None`, function calls and attribute references in code | a secret in a sentence without `:` or `=` ("the password is ...", "the door code is 4821") is missed; an unquoted value stops at `,` `;` `&` unless the pair starts the line; `mysql -pSECRET` style flags are missed; a key named just `key` is not treated as secret; tokens of services that are not in the prefix list are found only next to a secret-looking key |
| `user` | yes | the user-name part of `C:\Users\NAME`, `/home/NAME`, `/Users/NAME`, `/mnt/c/Users/NAME` | names with a space when a path separator follows; JSON-escaped backslashes | only the name inside the path is masked, not the same name elsewhere in the text (add it to `terms`); `/home/pricing` in a web route written without host is taken for a user; generic accounts (`Public`, `root`, `runner`, ...) are skipped |
| `term` | with `terms` | the literal strings you pass, case-insensitive, whole words, Unicode-aware; Arabic and Hebrew diacritics and tatweel are ignored; Arabic prefix clitics may be attached | exactly what you list | nothing you did not list. Inflected forms and Arabic suffixes (`شركتنا`) are different words. `acme_corp` does not contain the word `acme` (underscore and digits are word characters). For Arabic `لل` + noun the whole word is masked under its own placeholder |
| `domain` | no | dotted names ending in a top-level domain from a short list | | list written from memory and incomplete; `config.app`-like code is flagged |
| `uuid` | no | 8-4-4-4-12 hex | | |
| `entropy` | no | runs of 24+ base64/URL-safe characters with letters and digits and high Shannon entropy; skips pure hex (hashes, commit ids), UUIDs, `data:` payloads, word-like identifiers | | noisy by nature: long camelCase identifiers and encoded data are flagged. Confidence 0.5 |

Not masked by design unless you pass them as `terms`: UUIDs (opt-in kind),
dates including dates of birth, plain numbers, national identity or social
security numbers, passport numbers, postal addresses, account numbers that
are not IBANs.

## Dev-set numbers

`bench/dataset.py` holds 76 short texts with labelled spans: support tickets,
logs, emails, chat messages and config snippets in English and Arabic (plus a
little German, French and Persian), and hard negatives. `python bench/run.py`
printed this for version 0.1.1, the same as for 0.1.0 (Python 3.14, Windows):

<!-- dev-set-numbers -->
```text
== dev set (bench/dataset.py): 76 texts, 99 labelled spans ==
kind        gold  found  exact  precision  recall
email         13     13     13       1.00    1.00
url            9      9      9       1.00    1.00
ip            12     13     12       0.92    1.00
mac            3      3      3       1.00    1.00
phone         22     22     21       0.95    0.95
card           3      3      3       1.00    1.00
iban           3      3      3       1.00    1.00
secret        19     17     17       1.00    0.89
user           5      5      5       1.00    1.00
term          10      8      8       1.00    0.80
all           99     96     94       0.98    0.95
covered by any mask: 94/99 (0.95)
round trip: 76/76 (1.00)
```

How to read it, honestly:

- **These numbers are optimistic.** The set was written by the same author
  as the detectors and was looked at during development; one rule (`CVV 123`)
  was added after a miss in it. It measures "does the tool do what its author
  intended" far more than "how well does it work on your text". Counts per
  kind are small; one item moves a column by several points.
- Scoring is strict: kind, start and end must all match a label. "covered"
  counts labelled spans that lie inside any masked span.
- The seven errors are kept in the set on purpose: two names that were not
  given as terms (the two `term` misses; blackbar cannot find names), two
  secrets written in a sentence, one unformatted phone number, one lot number
  taken for a phone number, one four-part version taken for an IP address.
- "round trip" is exact restoration of each text. It is 76/76 here because no
  text writes the same value in two spellings.
- `bench/run.py` also evaluates `bench/blind.py` and prints a second table;
  that result is below.

### Blind set

`bench/blind.py` was written by someone who never saw the code: 186 texts in
English and Arabic (tickets, chat, logs, config, invoices), 179 labelled
values, and 62 texts with nothing to mask but plenty of look-alikes (dates,
prices, order numbers, versions, hashes). Every value in it is fake. It was run
once and the detectors were not changed afterwards. For version 0.1.1 it was
re-run after fixes made once the blind set had been seen (term matching,
placeholder reservation, normalisation; none aimed at it); every number
below stayed the same.

| kind | labelled | precision | recall |
|---|---|---|---|
| email, url, mac, card, iban, user | 95 | 1.00 | 1.00 |
| ip | 26 | 0.96 | 1.00 |
| phone | 34 | 0.97 | 0.91 |
| secret | 24 | 0.96 | 0.96 |
| all | 179 | 0.98 | 0.98 |

Round trip (mask, then unmask, gives back the original text): 186 of 186.

The seven errors, in full:

- three phone numbers missed: national numbers written as one unbroken run
  of ten or eleven digits with no plus sign, one of them in Arabic-Indic
  digits;
- one secret missed (a token mentioned in prose without `=` or `:`);
- three things masked that should not have been: a four-part version number
  (`3.2.1.0`) taken for an IP address, a spaced digit group taken for a phone
  number, and a short number after a secret-looking key.

A missed value is the failure that matters here, because it leaves the text
you share with a real value in it. Read the masked text before you send it.

## What it does not do

- **No name detection.** Names of people, companies, products, places and
  projects are masked only when you pass them as `terms`. There is no
  language model and no dictionary of names.
- **No guarantee of completeness.** blackbar finds what its patterns
  describe. Unusual formats, typos, values split across lines, text in
  images or attachments, and whole categories (postal addresses, identity
  numbers, dates of birth, medical or financial details written in words)
  pass through. Treat the output as a first pass and read it.
- **Regex-based.** It does not understand the text. It can mask something
  harmless that looks like a phone number and miss a password that is
  introduced by a sentence. The detector table lists the known cases.
- **Context can still identify a person.** Removing the values does not make
  a text anonymous. A job title, a place, a date and a rare event can be
  enough. blackbar is not an anonymisation tool in any legal sense.
- **The vault holds the secrets.** The vault and any saved vault file contain
  every original value in plain text. Losing the file to someone else undoes
  the masking; losing it yourself means you cannot restore. It is not
  encrypted.
- **The answer is restored blindly.** `unmask` replaces placeholders wherever
  they are. Read the restored text before you pass it on.
- **No exact restoration of respelled duplicates.** The same value written in
  two spellings comes back in the first spelling (`Masked.exact`).
- **No protection of what stays visible on purpose**: key names, path
  structure, ports, the kind and number of values.

## Tables written from memory

These were written from memory and have not been checked against the official
registries. Corrections are welcome.

- IBAN country lengths (`blackbar.checks.IBAN_LENGTHS`, 77 codes). An unknown
  country is accepted on the checksum alone, with lower confidence.
- Card scheme prefixes and lengths (`blackbar.checks.card_brand`).
- Token prefixes for the `secret` kind: `ghp_` `gho_` `ghu_` `ghs_` `ghr_`,
  `github_pat_`, `glpat-`, `AKIA` / `ASIA` + 16, `xoxb-` `xoxp-` `xoxa-`
  `xoxr-` `xoxs-`, `sk-` followed by 20 or more characters, `sk_live_`
  `sk_test_` `rk_live_` `rk_test_`, `AIza` + 35, `npm_` + 36, `hf_`, and the
  `pypi-AgEIcHlwaS5vcmc` prefix. Only prefixes the author was sure of are
  included; many services are missing.
- Top-level domains for the opt-in `domain` kind (short and incomplete).
- The reserved phone ranges used in tests and examples (US `555-01xx`, UK
  `020 7946 0xxx` and `07700 900xxx`, Australia `0491 570 xxx`, Germany
  `030 23125 xxx`, France `01 99 00 xx xx`).

## Development

```sh
python -m unittest discover -s tests -v
python bench/run.py --verbose
```

Every value in the tests, the examples and the dev set is invented. See
`CONTRIBUTING.md` for the rules on test data and `SECURITY.md` for the threat
model.

## License

MIT. See `LICENSE`.
