"""pii-scanner — regex + checksum personal-data detection, ported from
PinkyAI's `rules::pii` engine module (see README.md "Provenance").
Two detection strategies:
* Format-only regex (email, US/IL phone, US SSN) — Confidence.LOW: a
match means "shaped like one of these," nothing more.
* Regex candidate + checksum (IBAN mod-97, payment card / IL national ID
Luhn mod-10) — Confidence.MEDIUM/HIGH: a random digit string has only
roughly a 1-in-10 (Luhn) or 1-in-97 (IBAN) chance of passing by luck,
so a checksum pass is real evidence, not just shape.
Pure stdlib, no network call. See README.md for full honest-scope notes.
"""
from __future__ import annotations
import argparse
import json
import re
import sys
from dataclasses import dataclass
from pathlib import Path
SKIPPED_DIR_NAMES = {".git", "node_modules", "target", "dist", "build", ".venv", "venv", "__pycache__"}
EMAIL_PATTERN = re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b")
US_PHONE_PATTERN = re.compile(r"\b(?:\+1[-.\s]?)?\(?[2-9]\d{2}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b")
IL_MOBILE_PHONE_PATTERN = re.compile(r"\b05\d[-.\s]?\d{7}\b")
US_SSN_PATTERN = re.compile(r"\b\d{3}-\d{2}-\d{4}\b")
IL_ID_CANDIDATE_PATTERN = re.compile(r"\b\d{9}\b")
CREDIT_CARD_CANDIDATE_PATTERN = re.compile(r"\b(?:\d[ -]?){13,19}\b")
IBAN_CANDIDATE_PATTERN = re.compile(r"\b[A-Z]{2}\d{2}[A-Z0-9]{11,30}\b")
def luhn_checksum_valid(digits: str) -> bool:
"""Luhn (mod-10) checksum over a digit string. Used both for payment
cards (13-19 digits) and, at 9 digits, the Israeli teudat zehut, which
uses the identical algorithm.
"""
total = 0
for i, ch in enumerate(reversed(digits)):
d = int(ch)
if i % 2 == 1:
d *= 2
if d > 9:
d -= 9
total += d
return total % 10 == 0
def iban_checksum_valid(candidate: str) -> bool:
"""ISO 7064 mod-97 IBAN checksum: move the first 4 characters to the
end, convert letters to digits (A=10..Z=35), check the result mod 97
equals 1.
"""
if not (15 <= len(candidate) <= 34):
return False
rearranged = candidate[4:] + candidate[:4]
remainder = 0
for ch in rearranged:
if ch.isdigit():
value = int(ch)
elif ch.isalpha():
value = ord(ch.upper()) - ord("A") + 10
else:
return False
digits = 2 if value >= 10 else 1
remainder = (remainder * (10**digits) + value) % 97
return remainder == 1
@dataclass(frozen=True)
class Finding:
rule_id: str
confidence: str
path: str
line: int
column: int
redacted: str
def to_dict(self) -> dict[str, object]:
return {
"rule_id": self.rule_id,
"confidence": self.confidence,
"path": self.path,
"line": self.line,
"column": self.column,
"match": self.redacted,
}
def redact_match(raw: str) -> str:
if len(raw) < 10:
return "*" * len(raw)
return f"{raw[:2]}***{raw[-2:]}"
def _digits_only(s: str) -> str:
return "".join(ch for ch in s if ch.isdigit())
def scan_text(text: str, *, path: str = "<stdin>") -> list[Finding]:
findings: list[Finding] = []
for line_no, line in enumerate(text.splitlines(), start=1):
for match in EMAIL_PATTERN.finditer(line):
findings.append(_finding("pii.email", "low", path, line_no, match))
for match in US_PHONE_PATTERN.finditer(line):
findings.append(_finding("pii.phone_us", "low", path, line_no, match))
for match in IL_MOBILE_PHONE_PATTERN.finditer(line):
findings.append(_finding("pii.phone_il_mobile", "low", path, line_no, match))
for match in US_SSN_PATTERN.finditer(line):
findings.append(_finding("pii.national_id_us_ssn", "low", path, line_no, match))
for match in IL_ID_CANDIDATE_PATTERN.finditer(line):
if luhn_checksum_valid(match.group(0)):
findings.append(_finding("pii.national_id_il", "medium", path, line_no, match))
for match in IBAN_CANDIDATE_PATTERN.finditer(line):
if iban_checksum_valid(match.group(0)):
findings.append(_finding("pii.iban", "high", path, line_no, match))
for match in CREDIT_CARD_CANDIDATE_PATTERN.finditer(line):
digits = _digits_only(match.group(0))
if 13 <= len(digits) <= 19 and luhn_checksum_valid(digits):
findings.append(_finding("pii.payment_card", "high", path, line_no, match))
return findings
def _finding(rule_id: str, confidence: str, path: str, line_no: int, match: re.Match[str]) -> Finding:
return Finding(
rule_id=rule_id,
confidence=confidence,
path=path,
line=line_no,
column=match.start() + 1,
redacted=redact_match(match.group(0)),
)
def _iter_scannable_files(root: Path):
if root.is_file():
yield root
return
for path in root.rglob("*"):
if not path.is_file():
continue
if any(part in SKIPPED_DIR_NAMES for part in path.parts):
continue
yield path
def scan_path(root: Path) -> list[Finding]:
findings: list[Finding] = []
for path in _iter_scannable_files(root):
try:
text = path.read_text(encoding="utf-8")
except (UnicodeDecodeError, OSError):
continue
findings.extend(scan_text(text, path=str(path)))
return findings
def _print_human(findings: list[Finding]) -> None:
if not findings:
print("pii-scanner: no matches for the patterns this tool checks (see README's honest-scope note).")
return
for f in findings:
print(f"[{f.confidence}] {f.rule_id} — {f.path}:{f.line}:{f.column} — {f.redacted}")
print(f"\n{len(findings)} finding(s). Low-confidence findings need human review before acting on them.")
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="Scan text/files for likely personal data.")
parser.add_argument("path", nargs="?", help="File or directory to scan")
parser.add_argument("--stdin", action="store_true", help="Scan piped stdin instead of a path")
parser.add_argument("--json", action="store_true", help="Print findings as JSON instead of text")
args = parser.parse_args(argv)
if args.stdin:
findings = scan_text(sys.stdin.read())
elif args.path:
findings = scan_path(Path(args.path))
else:
parser.error("provide a path or --stdin")
return 2
if args.json:
print(json.dumps([f.to_dict() for f in findings], indent=2))
else:
_print_human(findings)
return 1 if findings else 0
if __name__ == "__main__":
sys.exit(main())