blackbar-redact 0.1.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
blackbar/__init__.py ADDED
@@ -0,0 +1,36 @@
1
+ """blackbar: reversible redaction of sensitive values in text.
2
+
3
+ >>> from blackbar import mask, unmask
4
+ >>> m = mask("Write to jane@example.com")
5
+ >>> m.text
6
+ 'Write to [EMAIL_1]'
7
+ >>> unmask("Sure, I will write to [EMAIL_1].", m.vault)
8
+ 'Sure, I will write to jane@example.com.'
9
+
10
+ blackbar is a set of regular expressions and checksums. It has no language
11
+ model and does not find names of people; pass them as ``terms``.
12
+ """
13
+
14
+ from .core import Masked, Unmasked, mask, redact, scan, unmask, unmask_report
15
+ from .detectors import ALIASES, DEFAULT_KINDS, KINDS, Finding, KindInfo, resolve_kinds
16
+ from .vault import Vault
17
+
18
+ __version__ = "0.1.2"
19
+
20
+ __all__ = [
21
+ "ALIASES",
22
+ "DEFAULT_KINDS",
23
+ "Finding",
24
+ "KINDS",
25
+ "KindInfo",
26
+ "Masked",
27
+ "Unmasked",
28
+ "Vault",
29
+ "__version__",
30
+ "mask",
31
+ "redact",
32
+ "resolve_kinds",
33
+ "scan",
34
+ "unmask",
35
+ "unmask_report",
36
+ ]
blackbar/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ sys.exit(main())
blackbar/checks.py ADDED
@@ -0,0 +1,133 @@
1
+ """Checksums and small validators used by the detectors.
2
+
3
+ The tables in this module (IBAN lengths, card prefixes) were written from
4
+ memory, not copied from a registry. They are believed to be right but have
5
+ not been checked against the official sources. See README, "Tables written
6
+ from memory".
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import math
12
+ from collections import Counter
13
+
14
+ __all__ = [
15
+ "IBAN_LENGTHS",
16
+ "card_brand",
17
+ "iban_check_digits",
18
+ "iban_ok",
19
+ "luhn_check_digit",
20
+ "luhn_ok",
21
+ "shannon_entropy",
22
+ ]
23
+
24
+ _ASCII_DIGITS = "0123456789"
25
+
26
+ # Total IBAN length per country code. WRITTEN FROM MEMORY.
27
+ # A country that is missing here is still accepted on the mod-97 checksum
28
+ # alone, with lower confidence.
29
+ IBAN_LENGTHS: dict[str, int] = {
30
+ "AD": 24, "AE": 23, "AL": 28, "AT": 20, "AZ": 28, "BA": 20, "BE": 16,
31
+ "BG": 22, "BH": 22, "BR": 29, "BY": 28, "CH": 21, "CR": 22, "CY": 28,
32
+ "CZ": 24, "DE": 22, "DK": 18, "DO": 28, "EE": 20, "EG": 29, "ES": 24,
33
+ "FI": 18, "FO": 18, "FR": 27, "GB": 22, "GE": 22, "GI": 23, "GL": 18,
34
+ "GR": 27, "GT": 28, "HR": 21, "HU": 28, "IE": 22, "IL": 23, "IQ": 23,
35
+ "IS": 26, "IT": 27, "JO": 30, "KW": 30, "KZ": 20, "LB": 28, "LC": 32,
36
+ "LI": 21, "LT": 20, "LU": 20, "LV": 21, "MC": 27, "MD": 24, "ME": 22,
37
+ "MK": 19, "MR": 27, "MT": 31, "MU": 30, "NL": 18, "NO": 15, "PK": 24,
38
+ "PL": 28, "PS": 29, "PT": 25, "QA": 29, "RO": 24, "RS": 22, "SA": 24,
39
+ "SC": 31, "SE": 24, "SI": 19, "SK": 24, "SM": 27, "ST": 25, "SV": 28,
40
+ "TL": 23, "TN": 24, "TR": 26, "UA": 29, "VA": 22, "VG": 24, "XK": 20,
41
+ }
42
+
43
+
44
+ def luhn_ok(number: str) -> bool:
45
+ """True if the ASCII digits in ``number`` satisfy the Luhn checksum."""
46
+ digits = [ord(c) - 48 for c in number if c in _ASCII_DIGITS]
47
+ if len(digits) < 2:
48
+ return False
49
+ total = 0
50
+ for i, d in enumerate(reversed(digits)):
51
+ if i % 2 == 1:
52
+ d *= 2
53
+ if d > 9:
54
+ d -= 9
55
+ total += d
56
+ return total % 10 == 0
57
+
58
+
59
+ def luhn_check_digit(partial: str) -> str:
60
+ """Return the digit that, appended to ``partial``, satisfies Luhn."""
61
+ for c in _ASCII_DIGITS:
62
+ if luhn_ok(partial + c):
63
+ return c
64
+ raise ValueError("no digits in input")
65
+
66
+
67
+ def _iban_number(s: str) -> int:
68
+ out = []
69
+ for c in s:
70
+ if c in _ASCII_DIGITS:
71
+ out.append(c)
72
+ elif "A" <= c <= "Z":
73
+ out.append(str(ord(c) - 55))
74
+ else:
75
+ raise ValueError("invalid IBAN character")
76
+ return int("".join(out))
77
+
78
+
79
+ def iban_ok(compact: str) -> bool:
80
+ """mod-97 check of an IBAN given without spaces (any letter case)."""
81
+ s = compact.upper()
82
+ if not (15 <= len(s) <= 34):
83
+ return False
84
+ if not (s[:2].isalpha() and s[:2].isascii() and s[2] in _ASCII_DIGITS and s[3] in _ASCII_DIGITS):
85
+ return False
86
+ try:
87
+ return _iban_number(s[4:] + s[:4]) % 97 == 1
88
+ except ValueError:
89
+ return False
90
+
91
+
92
+ def iban_check_digits(country: str, bban: str) -> str:
93
+ """Two check digits that make ``country + digits + bban`` a valid IBAN."""
94
+ rest = _iban_number(bban.upper() + country.upper() + "00") % 97
95
+ return f"{98 - rest:02d}"
96
+
97
+
98
+ def card_brand(digits: str) -> str | None:
99
+ """Guess the card scheme from prefix and length. WRITTEN FROM MEMORY.
100
+
101
+ Returns None when the prefix/length combination is not one we know,
102
+ in which case the number is not reported as a card even if it passes
103
+ the Luhn check.
104
+ """
105
+ n = len(digits)
106
+ if n < 12 or n > 19 or not digits.isascii() or not digits.isdigit():
107
+ return None
108
+ p2, p3, p4 = int(digits[:2]), int(digits[:3]), int(digits[:4])
109
+ if digits[0] == "4" and n in (13, 16, 19):
110
+ return "visa"
111
+ if (51 <= p2 <= 55 or 2221 <= p4 <= 2720) and n == 16:
112
+ return "mastercard"
113
+ if p2 in (34, 37) and n == 15:
114
+ return "amex"
115
+ if (p4 == 6011 or p2 == 65 or 644 <= p3 <= 649) and 16 <= n <= 19:
116
+ return "discover"
117
+ if 3528 <= p4 <= 3589 and 16 <= n <= 19:
118
+ return "jcb"
119
+ if (300 <= p3 <= 305 or p2 in (36, 38, 39)) and 14 <= n <= 19:
120
+ return "diners"
121
+ if p2 == 62 and 16 <= n <= 19:
122
+ return "unionpay"
123
+ if (p2 == 50 or 56 <= p2 <= 69) and 12 <= n <= 19:
124
+ return "maestro"
125
+ return None
126
+
127
+
128
+ def shannon_entropy(s: str) -> float:
129
+ """Shannon entropy in bits per character."""
130
+ if not s:
131
+ return 0.0
132
+ n = len(s)
133
+ return -sum((c / n) * math.log2(c / n) for c in Counter(s).values())
blackbar/cli.py ADDED
@@ -0,0 +1,270 @@
1
+ """Command line interface: blackbar mask | unmask | scan | kinds."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import sys
9
+
10
+ from . import __version__
11
+ from .core import mask, redact, scan, unmask_report
12
+ from .detectors import ALIASES, KINDS
13
+ from .vault import Vault
14
+
15
+ __all__ = ["main"]
16
+
17
+
18
+ class CliError(Exception):
19
+ pass
20
+
21
+
22
+ def _utf8_streams() -> None:
23
+ """Make messages safe on consoles whose default encoding is not UTF-8."""
24
+ for stream in (sys.stdout, sys.stderr):
25
+ reconfigure = getattr(stream, "reconfigure", None)
26
+ if reconfigure is not None:
27
+ try:
28
+ reconfigure(encoding="utf-8", errors="backslashreplace")
29
+ except (ValueError, OSError):
30
+ pass
31
+
32
+
33
+ def _read_input(path: str | None) -> str:
34
+ """Read bytes and decode as UTF-8, keeping line endings exactly as they are."""
35
+ try:
36
+ if path in (None, "-"):
37
+ buffer = getattr(sys.stdin, "buffer", None)
38
+ data = buffer.read() if buffer is not None else sys.stdin.read().encode("utf-8")
39
+ else:
40
+ with open(path, "rb") as fh:
41
+ data = fh.read()
42
+ except OSError as exc:
43
+ raise CliError(f"cannot read {path}: {exc.strerror or exc}") from None
44
+ try:
45
+ return data.decode("utf-8")
46
+ except UnicodeDecodeError:
47
+ raise CliError("input is not valid UTF-8") from None
48
+
49
+
50
+ def _check_output(path: str | None, force: bool, *others: str | None) -> None:
51
+ if path is None:
52
+ return
53
+ for other in others:
54
+ if other not in (None, "-") and os.path.abspath(other) == os.path.abspath(path):
55
+ raise CliError(f"output file {path} is also an input or the vault")
56
+ if os.path.exists(path) and not force:
57
+ raise CliError(f"{path} exists; use --force to overwrite it")
58
+
59
+
60
+ def _write_output(text: str, path: str | None, force: bool) -> None:
61
+ data = text.encode("utf-8")
62
+ if path is None:
63
+ buffer = getattr(sys.stdout, "buffer", None)
64
+ if buffer is not None:
65
+ sys.stdout.flush()
66
+ buffer.write(data)
67
+ buffer.flush()
68
+ else:
69
+ sys.stdout.write(text)
70
+ return
71
+ try:
72
+ with open(path, "wb" if force else "xb") as fh:
73
+ fh.write(data)
74
+ except FileExistsError:
75
+ raise CliError(f"{path} exists; use --force to overwrite it") from None
76
+ except OSError as exc:
77
+ raise CliError(f"cannot write {path}: {exc.strerror or exc}") from None
78
+
79
+
80
+ def _kinds_arg(args: argparse.Namespace) -> list[str] | None:
81
+ kinds = None
82
+ if args.kinds:
83
+ kinds = [k for part in args.kinds for k in part.split(",") if k.strip()]
84
+ if args.exclude:
85
+ from .detectors import resolve_kinds
86
+
87
+ drop = resolve_kinds([k for part in args.exclude for k in part.split(",")])
88
+ kinds = sorted(resolve_kinds(kinds) - drop)
89
+ return kinds
90
+
91
+
92
+ def _load_terms(args: argparse.Namespace) -> list[str]:
93
+ terms: list[str] = list(args.term or [])
94
+ for path in args.terms_file or []:
95
+ for line in _read_input(path).lstrip("").splitlines():
96
+ line = line.strip()
97
+ if line and not line.startswith("#"):
98
+ terms.append(line)
99
+ return terms
100
+
101
+
102
+ def _load_vault(path: str, key: bytes | None, must_exist: bool) -> Vault:
103
+ if not os.path.exists(path):
104
+ if must_exist:
105
+ raise CliError(f"vault {path} does not exist")
106
+ return Vault(key=key)
107
+ try:
108
+ return Vault.load(path, key=key)
109
+ except (OSError, ValueError) as exc:
110
+ raise CliError(f"cannot load vault {path}: {exc}") from None
111
+
112
+
113
+ def _key_from_env(name: str | None) -> bytes | None:
114
+ if not name:
115
+ return None
116
+ value = os.environ.get(name)
117
+ if not value:
118
+ raise CliError(f"environment variable {name} is not set or empty")
119
+ return value.encode("utf-8")
120
+
121
+
122
+ def _cmd_mask(args: argparse.Namespace) -> int:
123
+ _check_output(args.output, args.force, args.file, args.vault)
124
+ text = _read_input(args.file)
125
+ vault = _load_vault(args.vault, _key_from_env(args.key_env), must_exist=False)
126
+ try:
127
+ result = mask(
128
+ text,
129
+ kinds=_kinds_arg(args),
130
+ terms=_load_terms(args),
131
+ vault=vault,
132
+ min_confidence=args.min_confidence,
133
+ )
134
+ except ValueError as exc:
135
+ raise CliError(str(exc)) from None
136
+ # Save the vault first: masked text without its vault cannot be restored.
137
+ try:
138
+ vault.save(args.vault)
139
+ except OSError as exc:
140
+ raise CliError(f"cannot write vault {args.vault}: {exc.strerror or exc}") from None
141
+ _write_output(result.text, args.output, args.force)
142
+ if not args.quiet:
143
+ counts = ", ".join(f"{kind} {n}" for kind, n in sorted(result.counts.items())) or "nothing"
144
+ print(f"blackbar: masked {len(result.findings)} value(s): {counts}", file=sys.stderr)
145
+ print(f"blackbar: vault {args.vault} holds {len(vault)} original value(s); keep it private", file=sys.stderr)
146
+ if not result.exact:
147
+ print(
148
+ f"blackbar: {result.respelled} value(s) will be restored in the spelling first seen",
149
+ file=sys.stderr,
150
+ )
151
+ return 0
152
+
153
+
154
+ def _cmd_unmask(args: argparse.Namespace) -> int:
155
+ _check_output(args.output, args.force, args.file, args.vault)
156
+ text = _read_input(args.file)
157
+ vault = _load_vault(args.vault, None, must_exist=True)
158
+ result = unmask_report(text, vault)
159
+ _write_output(result.text, args.output, args.force)
160
+ if result.unknown and not args.quiet:
161
+ print(
162
+ "blackbar: not in the vault, left as is: " + " ".join(result.unknown),
163
+ file=sys.stderr,
164
+ )
165
+ return 3 if (result.unknown and args.strict) else 0
166
+
167
+
168
+ def _cmd_scan(args: argparse.Namespace) -> int:
169
+ text = _read_input(args.file)
170
+ try:
171
+ findings = scan(text, kinds=_kinds_arg(args), terms=_load_terms(args), min_confidence=args.min_confidence)
172
+ except ValueError as exc:
173
+ raise CliError(str(exc)) from None
174
+ rows = []
175
+ for f in findings:
176
+ line = text.count("\n", 0, f.start) + 1
177
+ col = f.start - (text.rfind("\n", 0, f.start) + 1) + 1
178
+ rows.append(
179
+ {
180
+ "line": line,
181
+ "column": col,
182
+ "start": f.start,
183
+ "end": f.end,
184
+ "kind": f.kind,
185
+ "confidence": f.confidence,
186
+ "redacted": redact(f.kind, text[f.start:f.end]),
187
+ }
188
+ )
189
+ if args.json:
190
+ print(json.dumps(rows, ensure_ascii=False, indent=2))
191
+ else:
192
+ for r in rows:
193
+ print(f"{r['line']}:{r['column']}\t{r['kind']}\t{r['confidence']:.2f}\t{r['redacted']}")
194
+ print(f"blackbar: {len(rows)} finding(s)", file=sys.stderr)
195
+ return 1 if (rows and args.fail_on_findings) else 0
196
+
197
+
198
+ def _cmd_kinds(args: argparse.Namespace) -> int:
199
+ print(f"{'kind':<9}{'default':<9}{'placeholder':<13}description")
200
+ for k in KINDS.values():
201
+ print(f"{k.name:<9}{'yes' if k.default else 'no':<9}{'[' + k.label + '_1]':<13}{k.description}")
202
+ if args.aliases:
203
+ print()
204
+ for alias, name in sorted(ALIASES.items()):
205
+ print(f"alias {alias} -> {name}")
206
+ return 0
207
+
208
+
209
+ def _add_detection_options(p: argparse.ArgumentParser) -> None:
210
+ p.add_argument("--kinds", action="append", metavar="LIST",
211
+ help="comma-separated kinds; 'default' and 'all' are accepted (see: blackbar kinds)")
212
+ p.add_argument("--exclude", action="append", metavar="LIST", help="comma-separated kinds to leave out")
213
+ p.add_argument("--terms-file", action="append", metavar="PATH",
214
+ help="UTF-8 file with one literal term per line (# starts a comment line)")
215
+ p.add_argument("--term", action="append", metavar="TEXT", help="one literal term; repeatable")
216
+ p.add_argument("--min-confidence", type=float, default=0.0, metavar="X",
217
+ help="ignore findings below this confidence (0..1, default 0)")
218
+
219
+
220
+ def build_parser() -> argparse.ArgumentParser:
221
+ parser = argparse.ArgumentParser(
222
+ prog="blackbar",
223
+ description="Reversible redaction of sensitive values in text. "
224
+ "No name detection: pass names with --term or --terms-file.",
225
+ )
226
+ parser.add_argument("--version", action="version", version=f"blackbar {__version__}")
227
+ sub = parser.add_subparsers(dest="command", required=True)
228
+
229
+ p = sub.add_parser("mask", help="replace values by placeholders and record them in a vault")
230
+ p.add_argument("file", nargs="?", default="-", metavar="FILE", help="input file, or - for standard input")
231
+ p.add_argument("--vault", required=True, metavar="PATH",
232
+ help="vault file to create or extend; IT CONTAINS THE ORIGINAL VALUES")
233
+ _add_detection_options(p)
234
+ p.add_argument("--key-env", metavar="NAME",
235
+ help="keyed mode: read the HMAC key from this environment variable")
236
+ p.add_argument("-o", "--output", metavar="OUT", help="write here instead of standard output")
237
+ p.add_argument("--force", action="store_true", help="overwrite OUT if it exists")
238
+ p.add_argument("-q", "--quiet", action="store_true", help="no summary on standard error")
239
+ p.set_defaults(func=_cmd_mask)
240
+
241
+ p = sub.add_parser("unmask", help="put the original values back")
242
+ p.add_argument("file", nargs="?", default="-", metavar="FILE", help="input file, or - for standard input")
243
+ p.add_argument("--vault", required=True, metavar="PATH", help="vault file written by 'mask'")
244
+ p.add_argument("-o", "--output", metavar="OUT", help="write here instead of standard output")
245
+ p.add_argument("--force", action="store_true", help="overwrite OUT if it exists")
246
+ p.add_argument("--strict", action="store_true", help="exit with status 3 if a placeholder is not in the vault")
247
+ p.add_argument("-q", "--quiet", action="store_true", help="no messages on standard error")
248
+ p.set_defaults(func=_cmd_unmask)
249
+
250
+ p = sub.add_parser("scan", help="report findings without changing anything; values are shown redacted")
251
+ p.add_argument("file", nargs="?", default="-", metavar="FILE", help="input file, or - for standard input")
252
+ _add_detection_options(p)
253
+ p.add_argument("--json", action="store_true", help="machine-readable output")
254
+ p.add_argument("--fail-on-findings", action="store_true", help="exit with status 1 if anything is found")
255
+ p.set_defaults(func=_cmd_scan)
256
+
257
+ p = sub.add_parser("kinds", help="list the kinds of values blackbar knows")
258
+ p.add_argument("--aliases", action="store_true", help="also list accepted alternative names")
259
+ p.set_defaults(func=_cmd_kinds)
260
+ return parser
261
+
262
+
263
+ def main(argv: list[str] | None = None) -> int:
264
+ _utf8_streams()
265
+ args = build_parser().parse_args(argv)
266
+ try:
267
+ return args.func(args)
268
+ except CliError as exc:
269
+ print(f"blackbar: error: {exc}", file=sys.stderr)
270
+ return 2
blackbar/core.py ADDED
@@ -0,0 +1,202 @@
1
+ """mask / unmask."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import dataclasses
6
+ import re
7
+ import unicodedata
8
+ from dataclasses import dataclass
9
+ from typing import Iterable
10
+
11
+ from .detectors import KINDS, Finding, detect
12
+ from .normalize import ascii_digits, normalize
13
+ from .vault import Vault
14
+
15
+ __all__ = ["Masked", "Unmasked", "mask", "redact", "scan", "unmask", "unmask_report"]
16
+
17
+ _LABELS = frozenset(k.label for k in KINDS.values())
18
+ _LABELS_BY_LENGTH = sorted(_LABELS, key=len, reverse=True)
19
+
20
+ # ASCII, full-width and lenticular brackets, each optionally backslash-escaped
21
+ # (Markdown). What is inside is parsed by ``_parse_placeholder``.
22
+ _OPEN = "\\[\\uff3b\\u3010" # [ full-width [ lenticular [
23
+ _CLOSE = "\\]\\uff3d\\u3011"
24
+ _BRACKETED = re.compile(
25
+ r"(\\)?[" + _OPEN + "]([^" + _OPEN + _CLOSE + r"\n]{3,48}?)(\\)?[" + _CLOSE + "]"
26
+ )
27
+ _DASHES = "".join(chr(c) for c in range(0x2010, 0x2016)) # hyphen ... horizontal bar
28
+ _WITH_SEPARATOR = re.compile(r"([A-Z]{2,12})[\s_\-:#." + _DASHES + r"]+([0-9A-F]{1,64})")
29
+ _HEX = re.compile(r"[0-9A-F]{1,64}")
30
+
31
+
32
+ def _parse_placeholder(inner: str) -> tuple[str, str] | None:
33
+ """Parse the text between brackets; return ``(LABEL, id)`` or None.
34
+
35
+ Tolerates what language models do: other letter case, spaces, an escaped
36
+ or missing underscore, a dash instead of it, Markdown emphasis or
37
+ backticks inside the brackets, full-width characters, Arabic-Indic digits.
38
+ """
39
+ s = ascii_digits(unicodedata.normalize("NFKC", inner)).replace("\\", "")
40
+ s = s.strip(" \t*`_~").upper()
41
+ m = _WITH_SEPARATOR.fullmatch(s)
42
+ if m:
43
+ label, ident = m.groups()
44
+ return (label, ident.lower()) if label in _LABELS else None
45
+ for label in _LABELS_BY_LENGTH: # no separator: "[EMAIL1]"
46
+ if s.startswith(label) and _HEX.fullmatch(s[len(label):]):
47
+ return label, s[len(label):].lower()
48
+ return None
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class Masked:
53
+ """Result of ``mask``."""
54
+
55
+ text: str
56
+ vault: Vault
57
+ findings: list[Finding]
58
+ respelled: int = 0
59
+
60
+ @property
61
+ def counts(self) -> dict[str, int]:
62
+ """Number of masked occurrences per kind."""
63
+ out: dict[str, int] = {}
64
+ for f in self.findings:
65
+ out[f.kind] = out.get(f.kind, 0) + 1
66
+ return out
67
+
68
+ @property
69
+ def exact(self) -> bool:
70
+ """True when ``unmask(self.text, self.vault)`` gives back the input exactly.
71
+
72
+ False when a value occurred in a spelling that differs from the one
73
+ stored in the vault (for example the same phone number with other
74
+ spacing): it will be restored in the stored spelling.
75
+ """
76
+ return self.respelled == 0
77
+
78
+
79
+ @dataclass(frozen=True)
80
+ class Unmasked:
81
+ """Result of ``unmask_report``."""
82
+
83
+ text: str
84
+ restored: int
85
+ unknown: list[str]
86
+
87
+
88
+ def scan(
89
+ text: str,
90
+ *,
91
+ kinds: Iterable[str] | str | None = None,
92
+ terms: Iterable[str] | None = None,
93
+ min_confidence: float = 0.0,
94
+ arabic_clitics: bool = True,
95
+ ) -> list[Finding]:
96
+ """Report what ``mask`` would replace, without changing anything."""
97
+ return detect(text, kinds, terms, min_confidence=min_confidence, arabic_clitics=arabic_clitics)
98
+
99
+
100
+ def mask(
101
+ text: str,
102
+ *,
103
+ kinds: Iterable[str] | str | None = None,
104
+ terms: Iterable[str] | None = None,
105
+ vault: Vault | None = None,
106
+ min_confidence: float = 0.0,
107
+ arabic_clitics: bool = True,
108
+ ) -> Masked:
109
+ """Replace detected values by placeholders.
110
+
111
+ ``kinds`` names from ``blackbar kinds``; None means the default set.
112
+ ``terms`` literal strings to mask (names, companies, projects).
113
+ blackbar does not find names on its own.
114
+ ``vault`` reuse a vault to keep placeholders stable across calls.
115
+ """
116
+ if not isinstance(text, str):
117
+ raise TypeError("text must be a str")
118
+ if vault is None:
119
+ vault = Vault()
120
+ findings = detect(text, kinds, terms, min_confidence=min_confidence, arabic_clitics=arabic_clitics)
121
+
122
+ # Placeholder-looking text already present in the input must never be
123
+ # handed out for a new value, or restoring would rewrite it. Reserve
124
+ # every canonical form ``unmask`` could resolve it to (``[EMAIL_01]``
125
+ # resolves to ``[EMAIL_1]``), in numbered and in keyed mode.
126
+ for m in _BRACKETED.finditer(text):
127
+ parsed = _parse_placeholder(m.group(2))
128
+ if parsed is not None:
129
+ vault.reserve_parsed(*parsed)
130
+
131
+ pieces: list[str] = []
132
+ done: list[Finding] = []
133
+ pos = 0
134
+ respelled = 0
135
+ for f in findings:
136
+ value = text[f.start:f.end]
137
+ placeholder = vault.placeholder_for(f.kind, value)
138
+ if vault.get(placeholder) != value:
139
+ respelled += 1
140
+ pieces.append(text[pos:f.start])
141
+ pieces.append(placeholder)
142
+ pos = f.end
143
+ done.append(dataclasses.replace(f, placeholder=placeholder))
144
+ pieces.append(text[pos:])
145
+ return Masked("".join(pieces), vault, done, respelled)
146
+
147
+
148
+ def unmask_report(text: str, vault: Vault) -> Unmasked:
149
+ """Like ``unmask`` but also says what was restored and what was not."""
150
+ if not isinstance(text, str):
151
+ raise TypeError("text must be a str")
152
+ restored = 0
153
+ unknown: list[str] = []
154
+
155
+ def replace(m: re.Match[str]) -> str:
156
+ nonlocal restored
157
+ parsed = _parse_placeholder(m.group(2))
158
+ if parsed is None:
159
+ return m.group(0)
160
+ value = vault.lookup(*parsed)
161
+ if value is None:
162
+ canonical = f"[{parsed[0]}_{parsed[1]}]"
163
+ if canonical not in unknown:
164
+ unknown.append(canonical)
165
+ return m.group(0)
166
+ restored += 1
167
+ # A backslash on both sides is a Markdown-escaped placeholder: drop both.
168
+ # A backslash only in front, as in a Windows path, belongs to the text.
169
+ lead = m.group(1) if (m.group(1) and not m.group(3)) else ""
170
+ return lead + value
171
+
172
+ return Unmasked(_BRACKETED.sub(replace, text), restored, unknown)
173
+
174
+
175
+ def unmask(text: str, vault: Vault) -> str:
176
+ """Put the original values back.
177
+
178
+ Placeholders that are not in the vault are left as they are; use
179
+ ``unmask_report`` to get their list.
180
+ """
181
+ return unmask_report(text, vault).text
182
+
183
+
184
+ def redact(kind: str, value: str) -> str:
185
+ """A short hint of a value that is safe to print (used by ``scan``)."""
186
+ if kind == "email":
187
+ local, _, domain = value.partition("@")
188
+ labels = domain.split(".")
189
+ return f"{local[:1]}***@{labels[0][:1]}***.{labels[-1]}"
190
+ if kind in ("secret", "entropy"):
191
+ return f"*** ({len(value)} chars)"
192
+ if kind == "phone":
193
+ digits = normalize("phone", value)
194
+ return ("+" if digits.startswith("+") else "") + "***" + digits[-2:]
195
+ if kind == "card":
196
+ return "***" + normalize("card", value)[-4:]
197
+ if kind == "iban":
198
+ return value[:2] + "***"
199
+ if kind == "url":
200
+ m = re.match(r"([A-Za-z][A-Za-z0-9+.\-]*://)(?:[^/@\s]*@)?(.?)", value)
201
+ return f"{m.group(1)}{m.group(2)}***" if m else value[:1] + "***"
202
+ return value[:1] + "***"