badbool.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. """Pull and parse the Big-Ass Data Broker Opt-Out List (BADBOOL) into broker records.
  2. BADBOOL (https://github.com/yaelwrites/Big-Ass-Data-Broker-Opt-Out-List) is a
  3. maintained, frequently-updated markdown list. `refresh` fetches it and parses the
  4. "People Search Sites" section into records that merge UNDER the curated DB (curated
  5. records always win). Auto-parsed records carry source="BADBOOL-auto" and
  6. confidence="auto" so the agent treats their URLs as best guesses to verify first.
  7. `parse()` is pure (markdown in, records out) so it is tested offline; `fetch()` is
  8. the only network call and can be bypassed by passing markdown directly to refresh().
  9. """
  10. from __future__ import annotations
  11. import re
  12. import urllib.request
  13. from pathlib import Path
  14. import storage
  15. DEFAULT_URL = (
  16. "https://raw.githubusercontent.com/yaelwrites/"
  17. "Big-Ass-Data-Broker-Opt-Out-List/master/README.md"
  18. )
  19. USER_AGENT = "Mozilla/5.0 (compatible; unbroker/1.0; data opt-out)"
  20. # BADBOOL legend symbols.
  21. SYMBOLS = {
  22. "crucial": "\U0001F490", # 💐
  23. "high": "\u2620", # ☠
  24. "gov_id": "\U0001F3AB", # 🎫
  25. "phone": "\U0001F4DE", # 📞
  26. "payment": "\U0001F4B0", # 💰
  27. }
  28. _LINK_RE = re.compile(r"\[([^\]]+)\]\(([^)]+)\)")
  29. _OPTOUT_HINT = re.compile(
  30. r"opt[\- ]?out|optout|removal|remove|suppress|control-privacy|delete", re.IGNORECASE
  31. )
  32. _FIND_HINT = re.compile(r"find|your information|search|look ?up|look for", re.IGNORECASE)
  33. def slug(name: str) -> str:
  34. # Drop a trailing .com/.org/.info on the displayed name so "FastPeopleSearch.com"
  35. # matches the curated id "fastpeoplesearch"; keep .net/.id so distinct sites differ.
  36. n = re.sub(r"\.(com|org|info)\b", "", name.strip(), flags=re.IGNORECASE)
  37. return re.sub(r"[^a-z0-9]+", "", n.lower())
  38. def _heading_flags(heading: str) -> tuple[str, dict]:
  39. flags = {key: (sym in heading) for key, sym in SYMBOLS.items()}
  40. name = heading
  41. for sym in SYMBOLS.values():
  42. name = name.replace(sym, "")
  43. name = name.replace("\ufe0f", "").strip()
  44. return name, flags
  45. def _priority(flags: dict) -> str:
  46. if flags["crucial"]:
  47. return "crucial"
  48. if flags["high"]:
  49. return "high"
  50. return "standard"
  51. def _pick(links: list[tuple[str, str]], hint: re.Pattern) -> str | None:
  52. for _text, url in links:
  53. if hint.search(url):
  54. return url
  55. for text, url in links:
  56. if hint.search(text):
  57. return url
  58. return None
  59. def _clean(text: str) -> str:
  60. return re.sub(r"\s+", " ", text).strip()[:600]
  61. def _build(name: str, flags: dict, body: str) -> dict:
  62. links = _LINK_RE.findall(body)
  63. web = [(t, u) for t, u in links if u.lower().startswith("http")]
  64. mailtos = [u[7:] for _t, u in links if u.lower().startswith("mailto:")]
  65. optout_url = _pick(web, _OPTOUT_HINT)
  66. search_url = _pick(web, _FIND_HINT) or (web[0][1] if web else None)
  67. if flags["phone"]:
  68. method = "phone"
  69. elif optout_url:
  70. method = "web_form"
  71. elif mailtos:
  72. method = "email"
  73. else:
  74. method = "manual"
  75. return {
  76. "id": slug(name),
  77. "name": name,
  78. "category": "people_search",
  79. "priority": _priority(flags),
  80. "jurisdictions": ["US"],
  81. "search": {"method": "url_pattern", "url": search_url, "fetch": "browser",
  82. "match_signal": "result", "by": ["name", "phone", "address"]},
  83. "optout": {
  84. "method": method,
  85. "url": optout_url,
  86. "email": mailtos[0] if mailtos else None,
  87. "requires": {
  88. "gov_id": flags["gov_id"],
  89. "phone_voice": flags["phone"],
  90. "payment": flags["payment"],
  91. "email_verification": False,
  92. "captcha": False,
  93. "account": False,
  94. "phone_callback": False,
  95. },
  96. "inputs": ["full_name", "contact_email"],
  97. "notes": _clean(body),
  98. "links": [{"text": t, "url": u} for t, u in links],
  99. "est_processing_days": 14, # unknown for auto records; drives next_recheck_at
  100. },
  101. "source": "BADBOOL-auto",
  102. "confidence": "auto",
  103. "last_verified": None,
  104. }
  105. def parse(markdown: str) -> list[dict]:
  106. """Parse the 'People Search Sites' section of BADBOOL into broker records."""
  107. records: list[dict] = []
  108. in_people = False
  109. heading: str | None = None
  110. body: list[str] = []
  111. def flush() -> None:
  112. nonlocal heading, body
  113. if heading is not None:
  114. name, flags = _heading_flags(heading)
  115. if name:
  116. records.append(_build(name, flags, "\n".join(body).strip()))
  117. heading, body = None, []
  118. for line in markdown.splitlines():
  119. if line.startswith("## "):
  120. flush()
  121. in_people = line[3:].strip().lower().startswith("people search")
  122. continue
  123. if not in_people:
  124. continue
  125. if line.startswith("### "):
  126. flush()
  127. heading = line[4:].strip()
  128. elif heading is not None:
  129. body.append(line)
  130. flush()
  131. return records
  132. def fetch(url: str = DEFAULT_URL, timeout: int = 30) -> str:
  133. req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
  134. with urllib.request.urlopen(req, timeout=timeout) as resp:
  135. return resp.read().decode("utf-8", errors="replace")
  136. MIN_EXPECTED = 20 # BADBOOL's People Search section lists ~47; far fewer => upstream reorg, warn
  137. def refresh(cache_path: Path, url: str = DEFAULT_URL, markdown: str | None = None) -> dict:
  138. """Fetch (or accept) BADBOOL markdown, parse it, and write the snapshot cache."""
  139. md = markdown if markdown is not None else fetch(url)
  140. records = parse(md)
  141. storage.write_json(cache_path, records)
  142. out = {"parsed": len(records), "cache_path": str(cache_path), "source_url": url}
  143. if len(records) < MIN_EXPECTED:
  144. out["warning"] = (f"only {len(records)} parsed (expected >{MIN_EXPECTED}); BADBOOL's "
  145. "'People Search Sites' section may have moved/reorganized - check the parser")
  146. return out