maisecrets 0.9.2__tar.gz → 0.9.4__tar.gz

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.
Files changed (78) hide show
  1. {maisecrets-0.9.2 → maisecrets-0.9.4}/.claude-plugin/plugin.json +1 -1
  2. {maisecrets-0.9.2 → maisecrets-0.9.4}/PKG-INFO +20 -2
  3. {maisecrets-0.9.2 → maisecrets-0.9.4}/docs/PYPI.md +14 -1
  4. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/contract.py +3 -5
  5. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/core.py +37 -6
  6. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/encoded_mail.py +55 -5
  7. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/own_rules.py +16 -3
  8. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/personal.py +30 -3
  9. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/regions.py +42 -3
  10. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/registry.py +3 -1
  11. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/remote.py +66 -3
  12. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/leading_literals.json +25 -17
  13. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rulespec.py +2 -0
  14. maisecrets-0.9.4/maisecrets/detection/secret_table.py +83 -0
  15. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/value_checks.py +9 -1
  16. {maisecrets-0.9.2 → maisecrets-0.9.4}/pyproject.toml +7 -1
  17. {maisecrets-0.9.2 → maisecrets-0.9.4}/.gitignore +0 -0
  18. {maisecrets-0.9.2 → maisecrets-0.9.4}/LICENSE +0 -0
  19. {maisecrets-0.9.2 → maisecrets-0.9.4}/NOTICE +0 -0
  20. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/__init__.py +0 -0
  21. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/__init__.py +0 -0
  22. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/__main__.py +0 -0
  23. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/card_shape.py +0 -0
  24. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/checksums.py +0 -0
  25. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/deadline.py +0 -0
  26. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/detect-1.schema.json +0 -0
  27. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/fields.py +0 -0
  28. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/keyword_tail.py +0 -0
  29. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/label_number.py +0 -0
  30. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/lazy_regex.py +0 -0
  31. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/leaves.py +0 -0
  32. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/normalise.py +0 -0
  33. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/phone_forms.py +0 -0
  34. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/prefilter.py +0 -0
  35. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rule_filter.py +0 -0
  36. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/BETTERLEAKS_VERSION +0 -0
  37. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/DETECT_SECRETS_VERSION +0 -0
  38. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/LICENSE-betterleaks +0 -0
  39. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/LICENSE-bip39 +0 -0
  40. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/LICENSE-detect-secrets +0 -0
  41. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/LICENSE-gitleaks +0 -0
  42. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/LICENSE-presidio +0 -0
  43. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/LICENSE-scowl +0 -0
  44. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/PRESIDIO_VERSION +0 -0
  45. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/SCOWL_VERSION +0 -0
  46. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/betterleaks.json +0 -0
  47. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/betterleaks.toml +0 -0
  48. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/bip39_english.txt +0 -0
  49. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/detect_secrets.json +0 -0
  50. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/labels/cs.txt +0 -0
  51. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/labels/da.txt +0 -0
  52. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/labels/de.txt +0 -0
  53. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/labels/en.txt +0 -0
  54. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/labels/es.txt +0 -0
  55. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/labels/fi.txt +0 -0
  56. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/labels/fr.txt +0 -0
  57. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/labels/it.txt +0 -0
  58. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/labels/ja.txt +0 -0
  59. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/labels/ko.txt +0 -0
  60. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/labels/nb.txt +0 -0
  61. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/labels/nl.txt +0 -0
  62. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/labels/pl.txt +0 -0
  63. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/labels/pt.txt +0 -0
  64. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/labels/ru.txt +0 -0
  65. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/labels/sv.txt +0 -0
  66. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/labels/th.txt +0 -0
  67. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/labels/tr.txt +0 -0
  68. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/labels/zh.txt +0 -0
  69. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/own_secret_rules.json +0 -0
  70. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/patched_upstream.txt +0 -0
  71. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/prefixes.txt +0 -0
  72. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/presidio.json +0 -0
  73. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/public_test_values.txt +0 -0
  74. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/rules/words_en.txt +0 -0
  75. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/text_index.py +0 -0
  76. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/types.json +0 -0
  77. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/detection/vocabulary.py +0 -0
  78. {maisecrets-0.9.2 → maisecrets-0.9.4}/maisecrets/py.typed +0 -0
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "maisecrets",
3
3
  "displayName": "maisecrets",
4
- "version": "0.9.2",
4
+ "version": "0.9.4",
5
5
  "description": "Intercepts detected secrets and PII before they reach the cloud model: deterministic detection, a local vault with TTL, placeholders resolved only where the real call happens. Free and open source, by mcpgate.de.",
6
6
  "author": {
7
7
  "name": "mcpgate",
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: maisecrets
3
- Version: 0.9.2
3
+ Version: 0.9.4
4
4
  Summary: Find secrets and personal data in text: the detection core of the maisecrets plugin
5
5
  Project-URL: Homepage, https://mcpgate.de/maisecrets/
6
6
  Project-URL: Documentation, https://github.com/Mcpgate-de/maisecrets/blob/main/docs/DETECTION.md
@@ -22,7 +22,12 @@ Classifier: Intended Audience :: Developers
22
22
  Classifier: Operating System :: OS Independent
23
23
  Classifier: Programming Language :: Python :: 3 :: Only
24
24
  Classifier: Programming Language :: Python :: 3.9
25
+ Classifier: Programming Language :: Python :: 3.10
26
+ Classifier: Programming Language :: Python :: 3.11
25
27
  Classifier: Programming Language :: Python :: 3.12
28
+ Classifier: Programming Language :: Python :: 3.13
29
+ Classifier: Programming Language :: Python :: 3.14
30
+ Classifier: Programming Language :: Python :: 3.15
26
31
  Classifier: Topic :: Security
27
32
  Classifier: Topic :: Text Processing
28
33
  Classifier: Typing :: Typed
@@ -57,6 +62,19 @@ for m in d.findings(text, channel="tool"):
57
62
 
58
63
  A detector with these four arguments reads nothing of the computer it runs on: no home folder, no config.
59
64
 
65
+ ## From another language: one JSON request per process
66
+
67
+ The package also runs as a command line program. It reads one JSON request on stdin and writes one JSON response
68
+ on stdout. The response holds the offsets, the type and the rule of each finding, never the value.
69
+
70
+ ```bash
71
+ echo '{"contract": "maisecrets.detect/1", "text": "token: ...", "channel": "tool",
72
+ "regions": ["generic", "de"], "languages": ["en", "de"]}' | python -m maisecrets.detection
73
+ ```
74
+
75
+ The schema ships with the package (`maisecrets/detection/detect-1.schema.json`). An unknown key, region or label
76
+ language gives an error response with exit status 2.
77
+
60
78
  ## What it finds
61
79
 
62
80
  - **Secrets** (type `SECRET`): API keys and tokens of many vendors, private keys, passwords and keys after a label,
@@ -70,7 +88,7 @@ and it misses what a rule does not describe. `maisecrets.detection.TYPES` lists
70
88
  ## Links
71
89
 
72
90
  - [Library documentation](https://github.com/Mcpgate-de/maisecrets/blob/main/docs/DETECTION.md): the API, the
73
- arguments, the fields of a hit
91
+ arguments, the fields of a hit, the JSON entry point and its errors
74
92
  - [Changelog](https://github.com/Mcpgate-de/maisecrets/blob/main/CHANGELOG.md)
75
93
  - [Issues](https://github.com/Mcpgate-de/maisecrets/issues)
76
94
  - License: Apache-2.0
@@ -26,6 +26,19 @@ for m in d.findings(text, channel="tool"):
26
26
 
27
27
  A detector with these four arguments reads nothing of the computer it runs on: no home folder, no config.
28
28
 
29
+ ## From another language: one JSON request per process
30
+
31
+ The package also runs as a command line program. It reads one JSON request on stdin and writes one JSON response
32
+ on stdout. The response holds the offsets, the type and the rule of each finding, never the value.
33
+
34
+ ```bash
35
+ echo '{"contract": "maisecrets.detect/1", "text": "token: ...", "channel": "tool",
36
+ "regions": ["generic", "de"], "languages": ["en", "de"]}' | python -m maisecrets.detection
37
+ ```
38
+
39
+ The schema ships with the package (`maisecrets/detection/detect-1.schema.json`). An unknown key, region or label
40
+ language gives an error response with exit status 2.
41
+
29
42
  ## What it finds
30
43
 
31
44
  - **Secrets** (type `SECRET`): API keys and tokens of many vendors, private keys, passwords and keys after a label,
@@ -39,7 +52,7 @@ and it misses what a rule does not describe. `maisecrets.detection.TYPES` lists
39
52
  ## Links
40
53
 
41
54
  - [Library documentation](https://github.com/Mcpgate-de/maisecrets/blob/main/docs/DETECTION.md): the API, the
42
- arguments, the fields of a hit
55
+ arguments, the fields of a hit, the JSON entry point and its errors
43
56
  - [Changelog](https://github.com/Mcpgate-de/maisecrets/blob/main/CHANGELOG.md)
44
57
  - [Issues](https://github.com/Mcpgate-de/maisecrets/issues)
45
58
  - License: Apache-2.0
@@ -33,11 +33,9 @@ class RequestError(Exception):
33
33
 
34
34
 
35
35
  def known_regions() -> frozenset:
36
- """Every region a rule names: the regional rules, the Presidio recognizers and the regions with a language."""
37
- from . import core, regions
38
- presidio = json.loads((core.RULES_DIR / "presidio.json").read_text(encoding="utf-8"))["recognizers"]
39
- return frozenset({"generic"} | set(regions.REGION_LANGUAGE) | {d["region"] for d in core.REGIONAL_RULES}
40
- | {core.presidio_region(r["id"]) for r in presidio})
36
+ """Every region a rule names (regions.known_regions: the library refuses the same codes)."""
37
+ from .regions import known_regions as known
38
+ return known()
41
39
 
42
40
 
43
41
  def _no_duplicate_keys(pairs: list) -> dict:
@@ -56,6 +56,7 @@ from . import deadline as _deadline
56
56
  from .deadline import ScanIncomplete # noqa: F401 the library's name: maisecrets.detection.ScanIncomplete
57
57
  from . import registry as _registry
58
58
  from . import fields as _fields
59
+ from . import regions as _regions
59
60
  from .label_number import LabelNumbers as _LabelNumbers
60
61
  from .prefilter import NONE as _NO_PREFIX, any_keyword as _any_keyword, lacks_prefix as _lacks_prefix # noqa: F401
61
62
  from .prefilter import lacks_required as _lacks_required, response_rules as _response_rules
@@ -75,6 +76,7 @@ from .value_checks import ( # noqa: F401
75
76
  _a_version, _LABEL_WORDS_TAIL_RE, _bitlocker_key_ok,
76
77
  _re2_to_python, _POSIX_CLASSES, shannon_entropy, ENTROPY_BY_ALPHABET, ENTROPY_BY_ALPHABET_RULES, _B62, _ALPHABETS,
77
78
  alphabet_of, _base64_of_text, _entropy_ok, _luhn_ok, IBAN_LENGTH, _iban_ok, _RESOLVER_IPS, _public_ip,
79
+ _IBAN_GROUP_SEP_UPSTREAM, PRESIDIO_GROUP_SEP,
78
80
  _de_tax_id_ok, _de_social_security_ok, _de_health_insurance_ok, _de_lanr_ok, _de_vat_id_ok, _B64_PEM_PRIVATE_RE,
79
81
  _OPENSSH_MAGIC, _pem_body_ok, _B64_LINE_RE, _B64_PEM_STARTS, _b64_needles, _PRIVATE_KEY_NEEDLES, _PEM_END_RE,
80
82
  _pem_ended, _base64_wrapped_end, _base64_pem_ok, _us_ssn_ok, _DS_TEMPLATED, _DS_INDIRECT, _DS_REFERENCE,
@@ -99,12 +101,15 @@ from .value_checks import ( # noqa: F401
99
101
  _PARTS, _PLACEHOLDER_PART_RE, looks_like_placeholder, _ssh_algorithm_name, _mail_shaped_id,
100
102
  )
101
103
  from .encoded_mail import ( # noqa: F401
102
- _ENCODED_MAIL_CONTEXT_RE, _ENCODED_MAIL_TO_RE, _encoded_mail_expected, _MAIL_COLUMN_RE, _OWNER_WORDS,
104
+ _ENCODED_MAIL_CONTEXT_RE, _ENCODED_MAIL_TO_RE, _encoded_mail_expected, _MAIL_COLUMN_RE, _OWNER_WORDS, _url_userinfo,
105
+ _url_password,
103
106
  _OWNER_PAIRS, _OWNER_TAILS, _FILE_EXTENSIONS, _names_a_mail_column,
104
107
  )
105
108
 
106
109
  RULES_DIR = Path(__file__).resolve().parent / "rules"
107
110
 
111
+ CHANNELS = ("prompt", "tool")
112
+
108
113
 
109
114
  @dataclass(frozen=True)
110
115
  class Match:
@@ -116,6 +121,12 @@ class Match:
116
121
  # the score of a model finding (a remote detector, Detector.findings_with); a deterministic finding has none
117
122
  score: float | None = field(default=None, compare=False, repr=False)
118
123
 
124
+ def __repr__(self) -> str:
125
+ # never the value: a caller that logs a hit must not write the secret (issue #39)
126
+ score = "" if self.score is None else f", score={self.score!r}"
127
+ return (f"Match(kind={self.kind!r}, type={self.type!r}, start={self.start!r}, end={self.end!r}, "
128
+ f"length={len(self.value)}, value=<hidden>{score})")
129
+
119
130
 
120
131
  class _Lazy:
121
132
  """A regex compiled on first use. Rule loading then costs a dict, not 265 compilations.
@@ -539,7 +550,7 @@ VALIDATORS = {
539
550
  else v.split("@", 1)[0].strip('"').lower() not in _SYSTEM_USERS
540
551
  and not _reserved_domain(v) and not _ssh_algorithm_name(v) and not _mail_shaped_id(v)),
541
552
  # name%40firma.de in a URL query, a form body or an access log: the same address, percent-encoded
542
- "person_email_encoded": lambda v: VALIDATORS["person_email"](v.replace("%40", "@")),
553
+ "person_email_encoded": lambda v: VALIDATORS["person_email"](v.replace("%40", "@").replace("\\u0040", "@")),
543
554
  "us_ssn": _us_ssn_ok,
544
555
  # checksums.py: ports of Presidio validators that were missing, the German document number, Switzerland, Austria
545
556
  # and the crypto wallet secrets
@@ -970,7 +981,9 @@ def _label_consumed(regex: str) -> tuple[str, int]:
970
981
  def _presidio_regex(rec_id: str, regex: str) -> str:
971
982
  left = PRESIDIO_LEFT_SUBFIELD.get(rec_id)
972
983
  if left and regex.startswith(_IBAN_LEFT):
973
- return left + regex[len(_IBAN_LEFT):]
984
+ regex = left + regex[len(_IBAN_LEFT):]
985
+ sep = PRESIDIO_GROUP_SEP.get(rec_id)
986
+ return regex.replace(_IBAN_GROUP_SEP_UPSTREAM, sep) if sep else regex
974
987
  first = PRESIDIO_CARD_FIRST.get(rec_id)
975
988
  if first and regex.count(_CARD_FIRST_UPSTREAM) == 1:
976
989
  # a Visa number of 19 digits (ISO/IEC 7812 allows 13, 16 and 19): Presidio's groups end at 17 digits, and
@@ -1584,8 +1597,11 @@ def active_regions():
1584
1597
  gave,
1585
1598
  else the config of this computer."""
1586
1599
  given = _det()._given_regions
1600
+ if callable(given):
1601
+ given = given()
1602
+ _regions.check(given) # a function's result as an Active given at once: ValueError for an unknown code
1587
1603
  if given is not None:
1588
- return given() if callable(given) else given
1604
+ return given
1589
1605
  try:
1590
1606
  from ..home import regions_from_config
1591
1607
  except Exception: # noqa: BLE001 - no home.py (the standalone skill) or one that cannot load: no config, as before
@@ -1739,6 +1755,8 @@ class Detector(_LabelNumbers):
1739
1755
  use_references configure it)."""
1740
1756
 
1741
1757
  def __init__(self, regions=None, sources=None, references=None, host=None):
1758
+ if isinstance(regions, _regions.Active):
1759
+ _regions.check(regions) # ValueError, as the entry point
1742
1760
  self.host = THIS_COMPUTER if host is None else host
1743
1761
  self._given_regions = regions
1744
1762
  self._given_sources = sources
@@ -1805,9 +1823,10 @@ class Detector(_LabelNumbers):
1805
1823
  """findings(), then a remote detector (remote.RemoteDetector) for what the rules left: a Result with the
1806
1824
  findings and the RemoteStatus of this call. The service only adds a span where no finding lies; it never
1807
1825
  removes, narrows or retypes one, and a service that fails leaves the findings as they are. `deadline`: a
1808
- time.monotonic() value that ends the request earlier than its own timeout (one budget for several texts)."""
1826
+ time.monotonic() value that ends the request earlier than its own timeout (one budget for several texts), and
1827
+ the rules (ScanIncomplete, as findings())."""
1809
1828
  from .remote import OFF, Result
1810
- found = self.findings(text, channel, path, fields=fields)
1829
+ found = self.findings(text, channel, path, fields=fields, deadline=deadline)
1811
1830
  if remote is None:
1812
1831
  return Result(found, OFF)
1813
1832
  spans, status = remote.ask(text, [(m.start, m.end) for m in found], deadline)
@@ -2505,6 +2524,8 @@ def scan(text: str, enabled: set[str] | None = None, channel: str = "prompt", pa
2505
2524
  (maisecrets/detection/fields.py); without it the scan is the one of before."""
2506
2525
  if not isinstance(text, str):
2507
2526
  raise TypeError(f"text must be a str, not {type(text).__name__}")
2527
+ if channel not in CHANNELS:
2528
+ raise ValueError(f"unknown channel {channel!r}; the known ones: prompt, tool")
2508
2529
  spans = _fields.checked(text, fields)
2509
2530
  # the channel and the path travel as arguments: a nested scan (is_fixture) or a scan in another thread has its own
2510
2531
  hits = _scan(text, enabled, rule_list=rule_list, channel="tool" if channel == "tool" else "prompt", path=path or "")
@@ -2797,6 +2818,8 @@ def _scan(text: str, enabled: set[str] | None = None, _copy: bool = False,
2797
2818
  secret = text[start:end]
2798
2819
  if not secret or secret[0] in "@.":
2799
2820
  continue
2821
+ # scheme://user:<password>@host.example: a SECRET, no address (#39)
2822
+ userinfo = _url_userinfo(text, start + secret.find("@")) if "url-userinfo" in filters else None
2800
2823
  if "base64-wrapped-end" in filters:
2801
2824
  end = _base64_wrapped_end(text, start, end) # the further lines of a wrapped value
2802
2825
  secret = text[start:end]
@@ -3019,6 +3042,14 @@ def _scan(text: str, enabled: set[str] | None = None, _copy: bool = False,
3019
3042
  if ext:
3020
3043
  end = ext.end()
3021
3044
  secret = text[start:end]
3045
+ if userinfo is not None:
3046
+ a, b = userinfo
3047
+ how = _url_password(text, a, text[a:b], enabled, rule_list is None)
3048
+ if how == "drop" or how == "secret" and overlaps(a, b):
3049
+ continue
3050
+ if how == "secret":
3051
+ take(Match("ds-basic-auth", "SECRET", text[a:b], a, b), own)
3052
+ continue
3022
3053
  take(Match(rule.id, rule.type, secret, start, end), own)
3023
3054
  found.sort(key=lambda x: x.start)
3024
3055
  return found
@@ -24,12 +24,15 @@ _ENCODED_MAIL_TO_RE = _LazyRx(r"(?i)(?<![/\w])(?:sent|send|mailed|forwarded|repl
24
24
 
25
25
  def _encoded_mail_expected(text: str, start: int, end: int) -> bool:
26
26
  """Where an address with its @ as %40 is an address: after a mail word or `=` (_ENCODED_MAIL_CONTEXT_RE), after
27
- `sent to` in prose, or as a whole cell of a CSV row (a column of a roster export, holdout 2026-10-15)."""
27
+ `sent to` in prose, or as a whole cell of a CSV row (a column of a roster export, holdout 2026-10-15). The JSON
28
+ escape \\u0040 is an @ wherever it stands, and a %40 address may be a whole segment of a URL path (#39)."""
29
+ value = text[start:end]
30
+ if "\\u0040" in value or _in_url_path(text, start, end):
31
+ return not _an_asset_or_version(value)
28
32
  line = _line_start(text, start)
29
33
  if _ENCODED_MAIL_CONTEXT_RE.search(text, max(line, start - 40), start) or _ENCODED_MAIL_TO_RE.search(
30
34
  text, max(line, start - 40), start):
31
35
  return True
32
- value = text[start:end]
33
36
  # a cell may have spaces around it (`Dana, name%40host.de`) and quotes ("name%40host.de"), in that order
34
37
  while start > line and text[start - 1] == " ":
35
38
  start -= 1
@@ -49,9 +52,8 @@ def _encoded_mail_expected(text: str, start: int, end: int) -> bool:
49
52
  sep = before or (after if after in (",", ";", "\t") else ",")
50
53
  if not before and not after:
51
54
  return False # a value alone on its line is no cell of a row
52
- labels = value.rsplit("%40", 1)[-1].lower().split(".")
53
- if labels[-1] in _FILE_EXTENSIONS or sum(x.isdigit() for x in labels) >= 2:
54
- return False # logo%402x.png is an asset at twice the size, pkg%401.0.0-beta.rc a version
55
+ if _an_asset_or_version(value):
56
+ return False
55
57
  import csv # here: the hooks pay for every module at import
56
58
  col = len(next(csv.reader([text[line:start + 1]], delimiter=sep), [""])) - 1
57
59
  # the first five lines of the text, and up to 20 lines above the row within 4,000 characters: a header after a
@@ -67,6 +69,25 @@ def _encoded_mail_expected(text: str, start: int, end: int) -> bool:
67
69
  return False
68
70
 
69
71
 
72
+
73
+ def _an_asset_or_version(value: str) -> bool:
74
+ """logo%402x.png is an asset at twice the size, pkg%401.0.0-beta.rc a version: no address."""
75
+ labels = value.replace("\\u0040", "%40").rsplit("%40", 1)[-1].lower().split(".")
76
+ return labels[-1] in _FILE_EXTENSIONS or sum(x.isdigit() for x in labels) >= 2
77
+
78
+
79
+ # a URL before a path segment: scheme://host/ and any segments, up to the segment of the value
80
+ _URL_PATH_BEFORE_RE = _LazyRx(r"[A-Za-z][A-Za-z0-9+.-]{1,15}://[^\s/?#]+/(?:[^\s/?#]*/)*$")
81
+
82
+
83
+ def _in_url_path(text: str, start: int, end: int) -> bool:
84
+ """The value is a whole segment of a URL path: after a / of the path, before /, ?, # or the end of the URL
85
+ (https://click.host.example/ls/name%40host.example/abc, a link of a mail tracker)."""
86
+ if text[start - 1:start] != "/" or not (end == len(text) or text[end] in "/?#\"'<>) \t\r\n"):
87
+ return False
88
+ return bool(_URL_PATH_BEFORE_RE.search(text, max(0, start - 300), start))
89
+
90
+
70
91
  # a header cell of a column of addresses: a mail word in a few languages, or a word that names who an address
71
92
  # belongs to (contact, login, user, recipient). Before 0.6.25 only "mail" counted, and an encoded address under a
72
93
  # header such as `contact` or `login` passed. `to` and `from` are left out: a migration table has them as columns
@@ -97,3 +118,32 @@ def _names_a_mail_column(cell: str) -> bool:
97
118
  if words and words[-1] in _OWNER_TAILS and len(words) >= 2 and words[-2] in _OWNER_WORDS:
98
119
  return True
99
120
  return bool(words) and (words[-1] in _OWNER_WORDS or words[-2:] in _OWNER_PAIRS)
121
+
122
+
123
+ # the user and the password of a URL up to its @: scheme://user:<password>@ (the classes of url-password-signs)
124
+ _URL_USERINFO_RE = _LazyRx(r"(?<![\w+.-])[A-Za-z][A-Za-z0-9+.-]{1,15}://([^\s:/?#\[\]@'\"`<>]{1,64}):"
125
+ r"([^\s/@'\"`<>]{1,128})$")
126
+
127
+
128
+ def _url_userinfo(text: str, at: int) -> tuple[int, int] | None:
129
+ """(start, end) of the password of a URL whose user information ends at the @ at `at`, else None: the local part
130
+ of an address there is the password (issue #39). A password equal to the user is a default (guest:guest), as
131
+ ds-basic-auth reads it: an empty span, so no hit at all."""
132
+ if at <= 0 or text[at] != "@" or "://" not in text[max(0, at - 220):at]:
133
+ return None
134
+ m = _URL_USERINFO_RE.search(text, max(0, at - 220), at)
135
+ if not m:
136
+ return None
137
+ return (m.start(2), m.end(2) if m.group(1).lower() != m.group(2).lower() else m.start(2))
138
+
139
+
140
+ def _url_password(text: str, start: int, pw: str, enabled, allow: bool) -> str:
141
+ """What the address rule does with the password of a URL it took: "drop" a default (empty), a placeholder or a
142
+ reference; keep its EMAIL hit, as before 0.9.4, for one under 6 characters or with ds-basic-auth off; else
143
+ "secret"."""
144
+ from . import core as c # at the call: the core is loaded by then
145
+ if not pw or c.looks_like_placeholder(pw) or c._references().hit_is_a_reference(text, start, pw):
146
+ return "drop"
147
+ off = (enabled is not None and not {"ds-basic-auth", "detect-secrets:ds-basic-auth"} & set(enabled)) or (
148
+ allow and c.switched_off("ds-basic-auth", c.allow_list()[1]))
149
+ return "email" if len(pw) < 6 or off else "secret"
@@ -60,6 +60,13 @@ _SENTENCE_VALUE = (r"(?:\*\*|[\"'`\u201e\u201c\u201a\u2018\u00ab\u00bb\u300c\u30
60
60
  r"(?:\*\*|[\"'`\u201c\u201d\u2018\u2019\u00ab\u00bb\u300d\u300f])?"
61
61
  r"(?=[.,;:?)\u3002\u2026]*(?:[\s\"'`\u201c\u201d\u2018\u2019\u00ab\u00bb" + _CJK + r"]|$))")
62
62
 
63
+ # the end of the last label of an address. A letter or a label that goes on ends no address: `user@host.dev-box` and
64
+ # `user@mail.server2` are logins at a host, not user@host.dev (the alphabetic last label of 2026-09-26 must not end
65
+ # inside a label), and a Latin, Cyrillic or Greek letter glued to it ends nothing (0.6.24). Glued and outside the
66
+ # address (#39): an underscore, hyphens that no label character follows (`<address>-----`), four digits or more
67
+ # (`<address>0151 2345678`, a phone number without its space) and a CJK letter
68
+ _MAIL_END = r"(?!(?!_|-+(?![A-Za-z0-9])|\d{4,}(?![\dA-Za-z.])|[" + _CJK + r"])[\w-])"
69
+
63
70
 
64
71
  OWN_RULES: list[dict] = [
65
72
  # ?token=… / &api_key=… in a URL
@@ -75,7 +82,7 @@ OWN_RULES: list[dict] = [
75
82
  # rule took neither, and the IP rule masked only the literal (ai-gateway #1764)
76
83
  "regex": r"(?:(?=[\w.+-]{0,64}@|(?<![\w.+-])[\w.+-]{65,}@)"
77
84
  r"(?:\b[\w.+-]{1,64}|(?<![\w.+-])[\w.+-]{64,}|[\w.+-]{64})"
78
- r"@[\w-]{1,63}(?:\.[\w-]{1,63})*\.[A-Za-z]{2,63}(?!-|" + _NOT_CJK_WORD + r")"
85
+ r"@[\w-]{1,63}(?:\.[\w-]{1,63})*\.[A-Za-z]{2,63}" + _MAIL_END +
79
86
  r"|(?<![\w\"\\])\"(?![\s:,])(?=[^\"\\\n]{0,63}[^\w.+\"\\\n-])[^\"\\\n]{1,64}(?<!\s)\"@[\w-]{1,63}(?:\.[\w-]{1,63})*\.[A-Za-z]{2,63}"
80
87
  r"(?![\w-])"
81
88
  r"|(?<![\w.+-])[\w.+-]{1,64}@\[(?:(?i:ipv6):[0-9A-Fa-f:.]{2,45}|\d{1,3}(?:\.\d{1,3}){3})\])"},
@@ -87,8 +94,9 @@ OWN_RULES: list[dict] = [
87
94
  r"(?![A-Za-z0-9])"},
88
95
  {"id": "email-percent-encoded", "type": "EMAIL", "validator": "person_email_encoded",
89
96
  # the @ as %40 in a query string, a form body, an access log (public benchmark, 2026-10-11: 7 addresses
90
- # passed); scan() keeps it only where an address is expected (_ENCODED_MAIL_CONTEXT_RE)
91
- "regex": r"(?:(?<![\w.+%-])|(?<=(?i:mailto%3a))|(?<=%3[Dd]))[\w.+-]{1,64}%40"
97
+ # passed); scan() keeps it only where an address is expected (_ENCODED_MAIL_CONTEXT_RE). Also the JSON escape
98
+ # \u0040 of the @ (#39)
99
+ "regex": r"(?:(?<![\w.+%-])|(?<=(?i:mailto%3a))|(?<=%3[Dd]))[\w.+-]{1,64}(?:%40|\\u0040)"
92
100
  r"[\w-]{1,63}(?:\.[\w-]{1,63})*\.[A-Za-z]{2,63}(?![\w-])"},
93
101
  {"id": "phone", "type": "PHONE",
94
102
  # a CJK letter before or after the number is a boundary, as in the e-mail rule
@@ -99,6 +107,11 @@ OWN_RULES: list[dict] = [
99
107
  # 8 x 6 digit run passes about once in 2.9 billion. ASCII digits only; a hyphen after it ends a sentence
100
108
  {"id": "bitlocker-recovery-key", "type": "SECRET", "validator": "bitlocker_key",
101
109
  "regex": r"(?<![0-9])(?<![0-9]-)[0-9]{6}(?:-[0-9]{6}){7}(?![0-9])(?!-[0-9])"},
110
+ # the passcode of a Microsoft Teams meeting in its join link: /meet/<meeting id>?p=<passcode>. The link alone lets
111
+ # anyone join; the meeting id is no secret (field case, 2026-11-08). Only on teams.microsoft.com/meet
112
+ {"id": "secret-teams-meeting-passcode", "type": "SECRET", "secret_group": 1,
113
+ "regex": r"(?<![\w.-])https?://(?i:teams\.microsoft\.com)/meet/\d{6,24}/?\?(?:[^\s#\"'<>&]{0,200}&){0,8}?"
114
+ r"p=([A-Za-z0-9_-]{6,64})(?![A-Za-z0-9_-])"},
102
115
  # bare token prefixes newer than the vendored rulesets live in rules/prefixes.txt (see _load_prefixes)
103
116
  {"id": "auth-scheme", "type": "SECRET", "secret_group": 3,
104
117
  "regex": r"(?<![\w-])(Bearer|Basic)([ \t]+)([A-Za-z0-9._~+/=-]{16,})"},
@@ -107,6 +107,10 @@ _ID_RE = _LazyRx(r"(?i)(?<![a-z])(?:mrn|member[ -]?id|passport(?:[ _-]?(?:no|num
107
107
  # a comma too: `your health plan beneficiary number, <id>, to medical professionals` (Nemotron-PII)
108
108
  r"\s{0,3}[:=#,]?\s{0,3}[\"']?"
109
109
  r"((?-i:[A-Z0-9](?:[A-Z0-9]|[ -](?=[A-Z0-9])){4,24}))(?![A-Za-z0-9])")
110
+ # a date or the date and hour of a timestamp is no id: `2026-11-08T21` of a CI log line after `sin`, `tax id`
111
+ _ID_DATE_RE = _LazyRx(r"\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])[T ](?:[01]\d|2[0-3])(?::[0-5]\d)?")
112
+ # only a timestamp with its hour: a plain date after an id label can be the id (a licence number written as a
113
+ # date, Nemotron; the 0.9.3 release gate)
110
114
 
111
115
  # ------------------------------------------------------------------------------------- user in a URL or path --
112
116
  _URL_USER_RE = _LazyRx(r"://([^:/?#\s@\[\]]{1,64}):[^@\s/]{1,128}@")
@@ -333,7 +337,7 @@ _PERSON_LABELS = (r"full[ _-]?name|customer[ _-]?name|first[ _-]?name|last[ _-]?
333
337
  r"|patient(?:[ _-]?name)?|employee(?:[ _-]?name)?|student(?:[ _-]?name)?|contact[ _-]?person"
334
338
  r"|account[ _-]?holder|card[ _-]?holder|cardholder|passenger|tenant|landlord|signer|co-signer"
335
339
  r"|guardian|beneficiary|billed to|oncall|on-call|requested by|reviewed by|approved by|salari[ée]"
336
- r"|vorname|nachname|mieter|vermieter|ansprechpartner(?:in)?|pr[ée]nom")
340
+ r"|vorname|nachname|mieter|vermieter|ansprechpartner(?:in)?|kontaktperson|pr[ée]nom")
337
341
  # a key or label of a person's record before the company's name, in the same paragraph: the record is a person's,
338
342
  # whether or not the name rules find the name in its value (a lower-case or abbreviated name)
339
343
  _PERSON_KEY_RE = _LazyRx(r"(?i)(?<![a-z])(?:" + _PERSON_LABELS + r"|name|person|resident|bewohner(?:in)?"
@@ -565,10 +569,29 @@ def _de_title_names(text: str, regions: tuple) -> list:
565
569
  v = m.group(g).lower()
566
570
  if v in _PLACEHOLDER_NAME_WORDS or v in _DE_TITLE_NOT_A_NAME:
567
571
  continue
568
- out.append((m.start(g), m.end(g), "name-after-german-title", NAME))
572
+ end = m.end(g)
573
+ if g == 1 and m.group(2) and _de_full_name_in_salutation(text, m):
574
+ end = m.end(2)
575
+ out.append((m.start(g), end, "name-after-german-title", NAME))
569
576
  return out
570
577
 
571
578
 
579
+ # a salutation before the title, and the end of the salutation after the second word: "Sehr geehrter Herr Dr. <first
580
+ # name> <surname>," greets one person by the full name, and the surname stayed in the clear (issue #39). Elsewhere the
581
+ # second capital word may be a noun (Herrn <Name> Bescheid geben), so only the first word is the name there
582
+ _DE_SALUTATION_BEFORE_RE = _LazyRx(r"(?i)(?:^|[^\w])(?:sehr geehrte[rn]?|hallo|liebe[rn]?|guten (?:tag|morgen|abend)"
583
+ r"|hi|hey|servus|moin|grüß gott|grüezi)[ \t]+$")
584
+ _DE_SALUTATION_END_RE = _LazyRx(r"[ \t]*(?:[,!.;:]|\r?\n|$)")
585
+
586
+
587
+ def _de_full_name_in_salutation(text: str, m) -> bool:
588
+ second = m.group(2).lower()
589
+ if _de_role(second) or second in _PLACEHOLDER_NAME_WORDS or second in _DE_TITLE_NOT_A_NAME:
590
+ return False
591
+ return bool(_DE_SALUTATION_BEFORE_RE.search(text, max(field_start(text, m.start()), m.start() - 24), m.start())
592
+ and _DE_SALUTATION_END_RE.match(text, m.end(2)))
593
+
594
+
572
595
  # ------------------------------------------------------------------------------- name before an e-mail address --
573
596
  # "Erika Beispiel <erika@example.org>", a git log line, a mail header. The address is the e-mail rule's; this is the
574
597
  # name before it. A service mailbox (noreply, a bot) names no person
@@ -2662,7 +2685,8 @@ def hits(text: str, channel: str, regions: tuple, company: list | None = None) -
2662
2685
  for m in _ID_RE.finditer(text):
2663
2686
  v = m.group(1)
2664
2687
  # 17 digits and more: a snowflake id of a chat platform or a database key, no document number
2665
- if sum(c.isdigit() for c in v) >= 5 and not (v.isdigit() and len(v) >= 17) and not _placeholder_digits(v):
2688
+ if sum(c.isdigit() for c in v) >= 5 and not (v.isdigit() and len(v) >= 17) and not _placeholder_digits(v) \
2689
+ and not _ID_DATE_RE.fullmatch(v):
2666
2690
  # MRN4829173: the label glued to the number is the id's own prefix, masked with it
2667
2691
  start = m.start() if text[m.start():m.start(1)].isalpha() else m.start(1)
2668
2692
  out.append((start, m.end(1), "id-number-after-label", ID_NUMBER))
@@ -2836,6 +2860,9 @@ def hits(text: str, channel: str, regions: tuple, company: list | None = None) -
2836
2860
  out.append((m.start(1), m.end(1), "name-before-email", NAME))
2837
2861
  if "csv-personal-column" in want and "\n" in text:
2838
2862
  out += _csv_hits(text)
2863
+ if "secret-under-password-column" in want and "\n" in text and ("|" in text or "\t" in text):
2864
+ from .secret_table import secret_table_hits
2865
+ out += secret_table_hits(text)
2839
2866
  if "address-street-postcode-city" in want and "," in text:
2840
2867
  for m in _STREET_POSTCODE_CITY_RE.finditer(text):
2841
2868
  if not _STREET_WORD_RE.search(m.group(1)):
@@ -14,6 +14,7 @@ locale) gets the generic PII rules only.
14
14
  """
15
15
  from __future__ import annotations
16
16
 
17
+ import functools
17
18
  import os
18
19
  import sys
19
20
  from dataclasses import dataclass
@@ -110,7 +111,37 @@ def parse_locale(loc: str | None) -> tuple[str | None, str | None]:
110
111
 
111
112
 
112
113
  def label_languages_available() -> list[str]:
113
- return sorted(p.stem for p in LABELS_DIR.glob("*.txt"))
114
+ return list(_label_languages())
115
+
116
+
117
+ def _label_languages() -> tuple[str, ...]:
118
+ return _languages_in(LABELS_DIR)
119
+
120
+
121
+ @functools.lru_cache(maxsize=4)
122
+ def _languages_in(folder: Path) -> tuple[str, ...]:
123
+ return tuple(sorted(p.stem for p in folder.glob("*.txt")))
124
+
125
+
126
+ @functools.lru_cache(maxsize=1)
127
+ def known_regions() -> frozenset:
128
+ """Every region a rule names: the regional rules, the Presidio recognizers and the regions with a language."""
129
+ import json
130
+ from . import core
131
+ presidio = json.loads((core.RULES_DIR / "presidio.json").read_text(encoding="utf-8"))["recognizers"]
132
+ return frozenset({"generic"} | set(REGION_LANGUAGE) | {d["region"] for d in core.REGIONAL_RULES}
133
+ | {core.presidio_region(r["id"]) for r in presidio})
134
+
135
+
136
+ def check(active: Active) -> None:
137
+ """ValueError for a region or a label language that no rule names, as the JSON entry point refuses them."""
138
+ for what, given, known in (("region", active.regions, known_regions()),
139
+ ("label language", active.languages, frozenset(_label_languages()))):
140
+ if isinstance(given, str):
141
+ raise ValueError(f"the {what}s must be a tuple of codes, not a str")
142
+ for code in given:
143
+ if code not in known:
144
+ raise ValueError(f"unknown {what} {code!r}; the known ones: {', '.join(sorted(known))}")
114
145
 
115
146
 
116
147
  def resolve(cfg: dict, locale: str | None = None) -> Active:
@@ -121,18 +152,24 @@ def resolve(cfg: dict, locale: str | None = None) -> Active:
121
152
  if raw is None:
122
153
  raw, source = list(DEFAULT_REGIONS), "default"
123
154
  lang, country = parse_locale(system_locale() if locale is None else locale)
155
+ known = known_regions()
124
156
  regions: list[str] = []
125
157
  for r in raw:
126
158
  r = str(r).strip().lower()
127
159
  r = _COUNTRY_ALIAS.get(r, r)
128
160
  if r == "auto":
129
- if country:
161
+ if country in known:
130
162
  regions.append(country)
131
163
  source += f", auto = {country} from the system setting"
164
+ elif country:
165
+ # a country without rules of its own (is_IS): the generic rules, as before 0.9.4; never an error
166
+ source += f", auto = {country} from the system setting, which has no rules of its own"
132
167
  else:
133
168
  source += ", auto = none (no system setting)"
134
- elif r and r != "generic":
169
+ elif r in known and r != "generic":
135
170
  regions.append(r)
171
+ elif r and r != "generic":
172
+ source += f", {r} has no rules and is left out" # a typo or `eu` in a config: never an error
136
173
  regions = list(dict.fromkeys(regions))
137
174
  lang = _LANGUAGE_ALIAS.get(lang, lang) if lang else None
138
175
  # every label file is on (since 0.8.2): a label word of one language in a text of another is common
@@ -154,6 +191,8 @@ def load_labels(language: str) -> list[Label]:
154
191
  """rules/labels/<language>.txt: one label per line, three tab-separated fields: the prefilter
155
192
  literal, the regex (case-insensitive, matched where detect-secrets matches its own denylist),
156
193
  and example words separated by commas. The examples are documentation and test input."""
194
+ if language not in _label_languages(): # a code goes into a file path: only the shipped names
195
+ raise ValueError(f"unknown label language {language!r}; the known ones: {', '.join(_label_languages())}")
157
196
  out = []
158
197
  for n, line in enumerate((LABELS_DIR / f"{language}.txt").read_text(encoding="utf-8").splitlines(), 1):
159
198
  if not line.strip() or line.lstrip().startswith("#"):
@@ -98,7 +98,9 @@ FILTERS = {
98
98
  "hashicorp-tf-password": ("password-value", "derived-label"), # detect-secrets' value check
99
99
  "email-percent-encoded": ("encoded-mail-context",), # name%40host only where an address is expected
100
100
  "phone": ("phone-shape",),
101
- "email": ("cjk-head",), # an address glued to CJK text: the words are no part
101
+ # cjk-head: an address glued to CJK text, whose words are no part of it; url-userinfo: the local part is the
102
+ # password of a URL (scheme://user:<password>@host), a secret
103
+ "email": ("cjk-head", "url-userinfo"),
102
104
  "crypto-seed-phrase": ("seed-phrase",), # no placeholder check; compared as single-spaced words
103
105
  }
104
106
  # the filters of every rule whose id starts so: a value that ends in a backslash before its quote
@@ -378,15 +378,21 @@ class RemoteDetector:
378
378
 
379
379
  def work() -> None:
380
380
  try:
381
- sent = list(text)
382
- for a, b in occupied if self.mask else ():
381
+ # the service reads the text with its JSON escapes turned into their characters (a guest list of
382
+ # `\r\nAlexander` was the word nAlexander to it, #39); each span comes back in the offsets of the text
383
+ plain, starts, ends = unescape_json(text)
384
+ occ = occupied if starts is None else [(bisect.bisect_right(ends, a), bisect.bisect_left(starts, b))
385
+ for a, b in occupied]
386
+ sent = list(plain)
387
+ for a, b in occ if self.mask else ():
383
388
  sent[a:b] = FILLER * (b - a)
384
389
  if self.__secret:
385
390
  self._prove(deadline, gate) # no text goes to a listener that cannot prove the secret
386
391
  if time.monotonic() > deadline:
387
392
  raise TimeoutError # a proof after the deadline: the caller was told "timeout"
388
393
  raw = self._request(self._body("".join(sent)), deadline, gate)
389
- box["kept"] = self._keep(text, self._parse(raw, len(text)), occupied, deadline)
394
+ kept = self._keep(plain, self._parse(raw, len(plain)), occ, deadline)
395
+ box["kept"] = kept if starts is None else [(starts[a], ends[b - 1], t, sc) for a, b, t, sc in kept]
390
396
  except BaseException as exc: # noqa: BLE001 - handed to the caller as it is
391
397
  box["error"] = exc
392
398
  t = threading.Thread(target=work, name="maisecrets-remote", daemon=True)
@@ -465,6 +471,63 @@ PRODUCT_TAILS = frozenset({
465
471
  "opus", "pages", "registry", "runner", "server", "sonnet", "studio", "web", "workspace"})
466
472
 
467
473
 
474
+ # a JSON escape, also escaped again (`\\n` in a JSON text inside a JSON string): the backslashes and what they stand for
475
+ _ESCAPE_RE = re.compile(r"\\+(?:u([0-9A-Fa-f]{4})|([nrtbf\"/]))")
476
+ _ESCAPED = {"n": "\n", "r": "\r", "t": "\t", "b": "\b", "f": "\f", '"': '"', "/": "/"}
477
+
478
+
479
+ def unescape_json(text: str) -> tuple:
480
+ """(plain, starts, ends): the text with each JSON escape (\\n \\r \\t \\" \\uXXXX, also with more backslashes) as
481
+ the character it stands for, and for each character of `plain` the start and the end of the characters of `text`
482
+ it came from. (text, None, None) when the text holds no escape. A span of `plain` from a to b covers
483
+ text[starts[a]:ends[b - 1]]: whole escapes, never half of one."""
484
+ if "\\" not in text:
485
+ return text, None, None
486
+ plain: list = []
487
+ starts: list = []
488
+ ends: list = []
489
+ at = 0
490
+ found = list(_ESCAPE_RE.finditer(text))
491
+ skip = False
492
+ for n, m in enumerate(found):
493
+ if skip:
494
+ skip = False
495
+ continue
496
+ for i in range(at, m.start()):
497
+ plain.append(text[i])
498
+ starts.append(i)
499
+ ends.append(i + 1)
500
+ code = int(m.group(1), 16) if m.group(1) else -1
501
+ if 0xD800 <= code <= 0xDFFF:
502
+ # an emoji is two escapes, a high and a low surrogate: one character for both. A lone surrogate stays its
503
+ # raw text: as a character it cannot be sent as UTF-8, and one emoji failed the request of a whole result
504
+ nxt = found[n + 1] if n + 1 < len(found) else None
505
+ low = int(nxt.group(1), 16) if nxt is not None and nxt.start() == m.end() and nxt.group(1) else -1
506
+ if code <= 0xDBFF and 0xDC00 <= low <= 0xDFFF:
507
+ plain.append(chr(0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00)))
508
+ starts.append(m.start())
509
+ ends.append(nxt.end())
510
+ at, skip = nxt.end(), True
511
+ continue
512
+ for i in range(m.start(), m.end()):
513
+ plain.append(text[i])
514
+ starts.append(i)
515
+ ends.append(i + 1)
516
+ at = m.end()
517
+ continue
518
+ plain.append(chr(code) if code >= 0 else _ESCAPED[m.group(2)])
519
+ starts.append(m.start())
520
+ ends.append(m.end())
521
+ at = m.end()
522
+ if not plain:
523
+ return text, None, None
524
+ for i in range(at, len(text)):
525
+ plain.append(text[i])
526
+ starts.append(i)
527
+ ends.append(i + 1)
528
+ return "".join(plain), starts, ends
529
+
530
+
468
531
  def is_product_name(span: str) -> bool:
469
532
  """Whether a name span is a product word alone, or a product word followed only by product words and
470
533
  PRODUCT_TAILS ("Claude Code"). Public since 0.8.15: a caller that applies the spans itself drops these."""
@@ -75,6 +75,11 @@ false
75
75
  "ovsx",
76
76
  false
77
77
  ],
78
+ "054af8c55078b0f4a12aca26": [
79
+ "",
80
+ false,
81
+ []
82
+ ],
78
83
  "0578384c300418ee0092b5bd": [
79
84
  "sandbox-sq0cs",
80
85
  false
@@ -850,6 +855,11 @@ false,
850
855
  "fw_"
851
856
  ]
852
857
  ],
858
+ "4c8a402576561551551b8e93": [
859
+ "",
860
+ false,
861
+ []
862
+ ],
853
863
  "4cd55bf7f1c7e7bcc415ee98": [
854
864
  "",
855
865
  false,
@@ -1049,6 +1059,13 @@ false
1049
1059
  "bkaa_",
1050
1060
  false
1051
1061
  ],
1062
+ "5f936aa9bafe6594eeae2da2": [
1063
+ "",
1064
+ false,
1065
+ [
1066
+ "://teams.microsoft.com/meet/"
1067
+ ]
1068
+ ],
1052
1069
  "5fc9d8d991fac4af8cc42e7e": [
1053
1070
  "",
1054
1071
  false,
@@ -1778,13 +1795,6 @@ false,
1778
1795
  "odt_",
1779
1796
  false
1780
1797
  ],
1781
- "aa5aa093184db3ea0ebd41c6": [
1782
- "",
1783
- false,
1784
- [
1785
- "%40"
1786
- ]
1787
- ],
1788
1798
  "aaad49a042858e995c294012": [
1789
1799
  "",
1790
1800
  false,
@@ -1872,6 +1882,14 @@ false
1872
1882
  false,
1873
1883
  []
1874
1884
  ],
1885
+ "b4d47798aa71f495820a4d95": [
1886
+ "",
1887
+ false,
1888
+ [
1889
+ "%40",
1890
+ "\\u0040"
1891
+ ]
1892
+ ],
1875
1893
  "b5aeaa72d8c689bddc43e4aa": [
1876
1894
  "",
1877
1895
  false,
@@ -2022,11 +2040,6 @@ false
2022
2040
  "ATCO",
2023
2041
  false
2024
2042
  ],
2025
- "c69e339d5e8ad6bae8527c98": [
2026
- "",
2027
- false,
2028
- []
2029
- ],
2030
2043
  "c8eaa0c0c4b081328df89891": [
2031
2044
  "",
2032
2045
  false,
@@ -2264,11 +2277,6 @@ false,
2264
2277
  "sk-pyx-",
2265
2278
  false
2266
2279
  ],
2267
- "def44427412344bc1f103982": [
2268
- "",
2269
- false,
2270
- []
2271
- ],
2272
2280
  "e06e113771282d19ae2d2833": [
2273
2281
  "",
2274
2282
  false,
@@ -136,6 +136,8 @@ def presidio_patches(detect) -> dict:
136
136
  "a look-behind of variable width, which Python's re refuses; the hit is the value group")
137
137
  for rid in sorted(detect.PRESIDIO_LEFT_SUBFIELD):
138
138
  add(rid, "regex", "replace", "left boundary: also after ?NN", "an MT940 subfield code before the IBAN (0.6.24)")
139
+ for rid in sorted(detect.PRESIDIO_GROUP_SEP):
140
+ add(rid, "regex", "replace", "a no-break space between the groups", "a word processor writes it (0.9.4)")
139
141
  for rid in sorted(detect.PRESIDIO_PATTERN_CONTEXT):
140
142
  add(rid, "context_rule", "set", "required", "the same digits are also FIX tags and XML identifiers")
141
143
  for rid, words in sorted(detect.PRESIDIO_EXTRA_CONTEXT.items()):
@@ -0,0 +1,83 @@
1
+ """The values under a secret column of a table whose cells a bar or a tab separates, for personal.py (moved here:
2
+ personal.py is at the size limit of the release tree)."""
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+ from .lazy_regex import LazyRx as _LazyRx
8
+
9
+ # a header that names a secret besides a password (_password_column): a secret, a token, a passcode, a PIN. The
10
+ # columns of a table separated by bars or tabs, with or without the separator row of Markdown (field case, 2026-11-08:
11
+ # | Account | Passwort | with a password on each row; `Account | Password` and tab tables stayed in the clear)
12
+ _SECRET_COL_RE = _LazyRx(r"(?:(?!(?:hash|hashed|encrypted|enc|crypt|crypted|salted|salt|is|has)_)[a-z0-9]{1,16}_){0,2}"
13
+ r"(?:secret|token|passcode|kenncode|zugangscode)")
14
+ _PIN_COL_RE = _LazyRx(r"(?:[a-z0-9]{1,16}_)?pin(?:_?code|_?nummer|_?number)?")
15
+ _TABLE_HEAD_RE = _LazyRx(r"[^\W\d_][\w.-]{0,30}(?: [\w.-]{1,30}){0,3}")
16
+ _MD_SEP_LOOSE_RE = _LazyRx(r"[ \t]*\|?(?:[ \t]*:?-+:?[ \t]*\|)+(?:[ \t]*:?-+:?[ \t]*)?")
17
+ _IDENTIFIER_RE = _LazyRx(r"[A-Z][A-Z0-9_]*")
18
+
19
+
20
+ def _secret_column(name: str) -> str:
21
+ """"password" for a column of passwords, secrets or tokens, "pin" for one of PINs, "" for any other."""
22
+ from .personal import _fold, _password_column
23
+ folded = _fold(re.sub(r"_{2,}", "_", name))
24
+ if _password_column(name) or _SECRET_COL_RE.fullmatch(folded):
25
+ return "password"
26
+ return "pin" if _PIN_COL_RE.fullmatch(folded) else ""
27
+
28
+
29
+ def _pin_cell(v: str) -> bool:
30
+ """4 to 8 digits, no placeholder (0000, 1234) and no year."""
31
+ from .personal import _placeholder_digits
32
+ return v.isascii() and v.isdigit() and 4 <= len(v) <= 8 and not _placeholder_digits(v) \
33
+ and not (len(v) == 4 and v[:2] in ("19", "20"))
34
+
35
+
36
+ def _row_cells(line: str, sep: str) -> list:
37
+ if sep == "|":
38
+ from .personal import _md_cells
39
+ return _md_cells(line)
40
+ out, a = [], 0
41
+ for part in line.split("\t"):
42
+ out.append((a, a + len(part)))
43
+ a += len(part) + 1
44
+ return out
45
+
46
+
47
+ def secret_table_hits(text: str) -> list:
48
+ """The values under a secret column of a table whose cells a bar or a tab separates. The header row is column names
49
+ only; each row has the header's number of cells, and an empty line or another shape ends the table."""
50
+ from .personal import _CSV_ROWS, _md_column, _password_cell
51
+ out = []
52
+ lines = text.split("\n")
53
+ pos = [0]
54
+ for ln in lines:
55
+ pos.append(pos[-1] + len(ln) + 1)
56
+ li = 0
57
+ while li < len(lines) - 1:
58
+ hdr = lines[li]
59
+ sep = "|" if "|" in hdr else "\t" if "\t" in hdr else ""
60
+ li += 1
61
+ if not sep or len(hdr) > 2000:
62
+ continue
63
+ head = [hdr[a:b].strip().strip("*`").strip() for a, b in _row_cells(hdr, sep)]
64
+ kinds = [_secret_column(_md_column(h)) for h in head]
65
+ if len(head) < 2 or not any(kinds) or not all(_TABLE_HEAD_RE.fullmatch(h) for h in head):
66
+ continue
67
+ if sep == "|" and _MD_SEP_LOOSE_RE.fullmatch(lines[li]):
68
+ li += 1
69
+ rows = 0
70
+ while li < len(lines) and rows < _CSV_ROWS:
71
+ line = lines[li]
72
+ cells = _row_cells(line, sep) if line.strip() and sep in line else []
73
+ if len(cells) != len(head):
74
+ break
75
+ for (a, b), kind in zip(cells, kinds):
76
+ v = line[a:b].strip().strip("*`")
77
+ if kind and v and (_pin_cell(v) if kind == "pin" else
78
+ _password_cell(v) and not _IDENTIFIER_RE.fullmatch(v)):
79
+ s0 = pos[li] + a + line[a:b].index(v)
80
+ out.append((s0, s0 + len(v), "secret-under-password-column", "SECRET"))
81
+ li += 1
82
+ rows += 1
83
+ return out
@@ -116,8 +116,16 @@ IBAN_LENGTH = {
116
116
  }
117
117
 
118
118
 
119
+ # the groups of an IBAN with a no-break space (U+00A0, U+202F) between them, as a word processor or a bank's web page
120
+ # writes them: Presidio takes only a space or a hyphen, and the IBAN stayed in the clear (issue #39). core.py puts it
121
+ # into Presidio's IBAN pattern
122
+ _IBAN_GROUP_SEP_UPSTREAM = "[ -]"
123
+ PRESIDIO_GROUP_SEP = {"iban": "[ \u00a0\u202f-]"}
124
+
125
+
119
126
  def _iban_ok(raw: str) -> bool:
120
- s = raw.replace(" ", "").replace("-", "").upper() # the vendored pattern takes a space or a hyphen between groups
127
+ # the vendored pattern takes a space or a hyphen between groups, and the core a no-break space (PRESIDIO_GROUP_SEP)
128
+ s = re.sub(r"[ \u00a0\u202f-]", "", raw).upper()
121
129
  if not 15 <= len(s) <= 34 or not s.isalnum():
122
130
  return False
123
131
  if raw != raw.upper() and IBAN_LENGTH.get(s[:2]) != len(s):
@@ -16,14 +16,20 @@ license = "Apache-2.0"
16
16
  license-files = ["LICENSE", "NOTICE", "maisecrets/detection/rules/LICENSE-*"]
17
17
  dependencies = []
18
18
  keywords = ["secrets", "pii", "personal data", "detection", "redaction", "ai agents", "dlp"]
19
- # the Python versions CI tests (python:3.9-slim and python:3.12-slim) and the platforms of the GitHub matrix
19
+ # the Python versions the wheel runs on: CI tests 3.9 and 3.12 (python:3.9-slim, python:3.12-slim), and
20
+ # scripts/wheel_smoke.py passed on each of 3.9 to 3.15 (2026-11-09); the platforms of the GitHub matrix
20
21
  classifiers = [
21
22
  "Development Status :: 4 - Beta",
22
23
  "Intended Audience :: Developers",
23
24
  "Operating System :: OS Independent",
24
25
  "Programming Language :: Python :: 3 :: Only",
25
26
  "Programming Language :: Python :: 3.9",
27
+ "Programming Language :: Python :: 3.10",
28
+ "Programming Language :: Python :: 3.11",
26
29
  "Programming Language :: Python :: 3.12",
30
+ "Programming Language :: Python :: 3.13",
31
+ "Programming Language :: Python :: 3.14",
32
+ "Programming Language :: Python :: 3.15",
27
33
  "Topic :: Security",
28
34
  "Topic :: Text Processing",
29
35
  "Typing :: Typed",
File without changes
File without changes
File without changes