registry.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. """Ingest the California Data Broker Registry into broker records (coverage breadth).
  2. The CA registry (CPPA, under the Delete Act) is the authoritative universe of data
  3. brokers doing business with California residents -- ~545 businesses in 2025, each
  4. required to publish a name, website, contact email, and a CCPA-rights/deletion URL.
  5. This is the same universe commercial services (DeleteMe/Incogni/Optery) draw from,
  6. plus the FCRA/GLBA-regulated and marketing/risk brokers most lists omit.
  7. These are NOT people-search sites you scan with a name -- most have no per-person
  8. lookup UI. They are worked through the LEGAL lane: the CA DROP portal
  9. (privacy.ca.gov/drop) is a single request that deletes from ALL registered brokers
  10. at once (CA residents), and per-broker CCPA deletion emails to the contact address
  11. are the fallback / non-CA path. So registry records are kept in their own lane
  12. (loaded only when asked) and never dumped into the people-search scan pipeline.
  13. `parse()` is pure (CSV text in, records out) so it is tested offline; `fetch()` is
  14. the only network call and can be bypassed by passing csv_text directly to refresh().
  15. """
  16. from __future__ import annotations
  17. import csv
  18. import datetime
  19. import io
  20. import re
  21. import urllib.request
  22. from pathlib import Path
  23. import storage
  24. # CA CPPA registry CSVs are published per year (registry2024.csv, registry2025.csv, ...).
  25. # 2025 is the latest COMPLETE dataset; the current year's file is empty until the Jan
  26. # registration window closes. DEFAULT_URL is the known-good fallback; `ca_candidate_urls`
  27. # probes newer years first so coverage auto-advances when the next year is published.
  28. _CA_CSV = "https://cppa.ca.gov/data_broker_registry/registry{year}.csv"
  29. _CA_FLOOR_YEAR = 2025
  30. DEFAULT_URL = _CA_CSV.format(year=_CA_FLOOR_YEAR)
  31. DROP_URL = "https://privacy.ca.gov/drop"
  32. # National Do Not Call Registry (FTC): the US-wide personal-number list for spam-call runs.
  33. DNC_URL = "https://www.donotcall.gov/register.html"
  34. def phone_digits(phone: str) -> str:
  35. """Best-effort NANP normalization: keep digits, strip a leading country-code 1."""
  36. d = re.sub(r"\D", "", str(phone or ""))
  37. return d[1:] if len(d) == 11 and d.startswith("1") else d
  38. _NANP = re.compile(r"^[2-9]\d{2}[2-9]\d{6}$")
  39. def dnc_eligible(dossier: dict) -> list:
  40. """The subject's numbers eligible for the National Do Not Call Registry: NANP only.
  41. A US-residency subject can still carry a non-NANP number (or a Canadian NANP one -- the
  42. residency check lives with the caller), and the FTC form rejects non-US numbers, so the
  43. surfaced list is digits-normalized and deduped: "555-123-4567" and "5551234567" are ONE
  44. number, never two registrations.
  45. """
  46. out: list = []
  47. seen: set = set()
  48. for p in (dossier.get("identity") or {}).get("phones") or []:
  49. d = phone_digits(p)
  50. if _NANP.match(d) and d not in seen:
  51. seen.add(d)
  52. out.append(d)
  53. return out
  54. USER_AGENT = "Mozilla/5.0 (compatible; unbroker/1.0; data opt-out)"
  55. def ca_candidate_urls(today: datetime.date | None = None) -> list[str]:
  56. """Newest-year-first CA registry URLs to try (auto-advances; never below the 2025 floor)."""
  57. year = (today or datetime.date.today()).year
  58. years = list(range(max(year, _CA_FLOOR_YEAR), _CA_FLOOR_YEAR - 1, -1))
  59. return [_CA_CSV.format(year=y) for y in years]
  60. # Multi-source registry lane. Only California publishes a clean bulk CSV (with contact email +
  61. # CCPA-rights URL per broker) AND offers a one-shot deletion portal (DROP). Vermont, Oregon, and
  62. # Texas maintain registries too, but only as searchable PORTALS (no reliable bulk export) and with
  63. # no DROP-equivalent -- and they overlap CA heavily (CA is effectively the superset). So they are
  64. # wired as first-class portal sources (official URL surfaced to the operator) rather than scraped.
  65. # Adding any state that later publishes a CSV is a one-line "format: csv" entry (the parser is
  66. # column-detection based, not CA-specific).
  67. SOURCES = {
  68. "ca": {"jurisdiction": "US-CA", "format": "csv", "url": DEFAULT_URL, "has_drop": True,
  69. "name": "California Data Broker Registry (CPPA)"},
  70. "vt": {"jurisdiction": "US-VT", "format": "portal", "has_drop": False,
  71. "url": "https://bizfilings.vermont.gov/online/DatabrokerInquire/",
  72. "name": "Vermont Data Broker Registry (Secretary of State)"},
  73. "or": {"jurisdiction": "US-OR", "format": "portal", "has_drop": False,
  74. "url": "https://dfr.oregon.gov/business/licensing/data-broker-registry/Pages/index.aspx",
  75. "name": "Oregon Data Broker Registry (DCBS)"},
  76. "tx": {"jurisdiction": "US-TX", "format": "portal", "has_drop": False,
  77. "url": "https://texas-sos.appianportalsgov.com/data-broker-registry",
  78. "name": "Texas Data Broker Registry (Secretary of State)"},
  79. }
  80. def portals() -> list[dict]:
  81. """Registry sources that are searchable portals (no bulk export) -- surfaced to the operator."""
  82. return [{"key": k, "jurisdiction": s["jurisdiction"], "name": s["name"], "url": s["url"]}
  83. for k, s in SOURCES.items() if s["format"] == "portal"]
  84. # Field label -> substring to locate its column on the header row (robust to
  85. # year-to-year column shifts; the registry re-orders/adds columns between years).
  86. _LABELS = {
  87. "name": "data broker name:",
  88. "dba": "doing business as",
  89. "website": "data broker primary website:",
  90. "email": "primary contact email",
  91. "rights_url": "exercise their ca consumer privacy act rights",
  92. "fcra": "regulated by the federal fair credit reporting act (fcra):",
  93. }
  94. def _norm(s: str) -> str:
  95. """Registry CSVs use NBSPs and a BOM; normalize for matching + clean values."""
  96. return re.sub(r"\s+", " ", (s or "").replace("\ufeff", "").replace("\xa0", " ")).strip()
  97. def slug(name: str, website: str = "") -> str:
  98. base = re.sub(r"\.(com|org|net|io|ai|inc|co|us|info|llc)\b", "", (name or "").strip(), flags=re.IGNORECASE)
  99. s = re.sub(r"[^a-z0-9]+", "", base.lower())
  100. if s:
  101. return s
  102. dom = re.sub(r"^https?://(www\.)?", "", (website or "").lower())
  103. return re.sub(r"[^a-z0-9]+", "", dom.split("/")[0]) or "broker"
  104. def _domain(website: str) -> str:
  105. dom = re.sub(r"^https?://(www\.)?", "", (website or "").strip().lower())
  106. return dom.split("/")[0]
  107. def _find_colmap(rows: list[list[str]]) -> tuple[int, dict[str, int]]:
  108. """Locate the label row (col0 == 'Data broker name:') and map fields to columns."""
  109. for i, row in enumerate(rows[:5]):
  110. if row and _norm(row[0]).lower().startswith("data broker name:"):
  111. colmap: dict[str, int] = {}
  112. for field, needle in _LABELS.items():
  113. for j, cell in enumerate(row):
  114. c = _norm(cell).lower()
  115. if needle in c and not c.startswith("if the data broker"):
  116. colmap[field] = j
  117. break
  118. return i, colmap
  119. raise ValueError("CA registry: could not locate the header row")
  120. def _get(row: list[str], idx: int | None) -> str:
  121. return _norm(row[idx]) if idx is not None and idx < len(row) else ""
  122. def _build(row: list[str], cm: dict[str, int], jurisdiction: str = "US-CA",
  123. has_drop: bool = True) -> dict | None:
  124. name = _get(row, cm.get("name"))
  125. website = _get(row, cm.get("website"))
  126. if not (name or website):
  127. return None
  128. email = _get(row, cm.get("email"))
  129. rights = _get(row, cm.get("rights_url"))
  130. dba = _get(row, cm.get("dba"))
  131. fcra = _get(row, cm.get("fcra")).lower().startswith("y")
  132. state = jurisdiction.split("-")[-1]
  133. method = "email" if email else ("web_form" if rights else "drop")
  134. if has_drop:
  135. notes = ("Registered CA data broker. One CA DROP request (privacy.ca.gov/drop) deletes from "
  136. "this and every registered broker at once; or send a CCPA deletion request to the "
  137. "contact email.")
  138. else:
  139. notes = (f"Registered {state} data broker (no one-shot delete portal in {state}). Send a "
  140. "CCPA/state-law deletion request to the contact email.")
  141. if fcra:
  142. notes += (" FCRA-regulated: some data is credit-reporting data with separate rules -- deletion "
  143. "may be limited; a consumer report dispute/security-freeze may apply instead.")
  144. return {
  145. "id": slug(name, website),
  146. "name": name or _domain(website),
  147. "dba": dba or None,
  148. "category": "data_broker",
  149. "priority": "long_tail",
  150. "jurisdictions": [jurisdiction],
  151. "search": {"method": "none", "url": website, "fetch": "none", "by": ["registry"]},
  152. "optout": {
  153. "method": method,
  154. "url": rights or website or None,
  155. "email": email or None,
  156. "requires": {"profile_url": False, "email_verification": False, "captcha": False,
  157. "gov_id": False, "account": False, "phone_callback": False, "payment": False},
  158. "inputs": ["full_name", "contact_email"],
  159. "deletion": {
  160. "via": "drop" if has_drop else "email",
  161. "email": email or None,
  162. "url": rights or None,
  163. "kinds": ["ccpa", "generic"],
  164. "notes": ("Covered by the CA DROP one-shot (privacy.ca.gov/drop); CCPA email fallback."
  165. if has_drop else "CCPA/state-law deletion email (no one-shot portal)."),
  166. },
  167. "fcra": fcra,
  168. "est_processing_days": 45,
  169. "notes": notes,
  170. },
  171. "source": f"{state}-registry",
  172. "confidence": "registry",
  173. "last_verified": None,
  174. }
  175. def parse(csv_text: str, jurisdiction: str = "US-CA", has_drop: bool = True) -> list[dict]:
  176. """Parse a data-broker-registry CSV into broker records (deduped by id).
  177. Column detection is by header label, not fixed position, so any state that publishes a
  178. registry CSV with name/website/email/rights columns parses without new code.
  179. """
  180. rows = list(csv.reader(io.StringIO(csv_text)))
  181. if not rows:
  182. return []
  183. header_i, cm = _find_colmap(rows)
  184. out: list[dict] = []
  185. seen: dict[str, int] = {}
  186. for row in rows[header_i + 1:]:
  187. if not any(c.strip() for c in row):
  188. continue
  189. rec = _build(row, cm, jurisdiction, has_drop)
  190. if not rec:
  191. continue
  192. bid = rec["id"]
  193. if bid in seen: # disambiguate id collisions by domain, then a counter
  194. dom = re.sub(r"[^a-z0-9]+", "", _domain(rec["search"]["url"]))
  195. cand = f"{bid}-{dom}" if dom and dom != bid else bid
  196. while cand in seen:
  197. seen[bid] += 1
  198. cand = f"{bid}-{seen[bid]}"
  199. rec["id"] = cand
  200. seen.setdefault(rec["id"], 0)
  201. seen.setdefault(bid, 0)
  202. out.append(rec)
  203. return out
  204. MIN_EXPECTED_CA = 100 # CA registry has ~500+; far fewer => wrong/empty file, warn
  205. def fetch(url: str = DEFAULT_URL, timeout: int = 60) -> str:
  206. req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
  207. with urllib.request.urlopen(req, timeout=timeout) as resp:
  208. return resp.read().decode("utf-8", errors="replace")
  209. def _fetch_ca_latest() -> tuple[str, list[dict]]:
  210. """Try newest CA registry year first; return (url, records) for the first non-empty."""
  211. last: tuple[str, list[dict]] = (DEFAULT_URL, [])
  212. for url in ca_candidate_urls():
  213. try:
  214. recs = parse(fetch(url), jurisdiction="US-CA", has_drop=True)
  215. except Exception:
  216. continue
  217. if recs:
  218. return url, recs
  219. last = (url, recs)
  220. return last
  221. def refresh(cache_path: Path, url: str = DEFAULT_URL, csv_text: str | None = None) -> dict:
  222. """CA single-source refresh: fetch (or accept) the CA CSV and write the cache."""
  223. text = csv_text if csv_text is not None else fetch(url)
  224. records = parse(text)
  225. storage.write_json(cache_path, records)
  226. fcra = sum(1 for r in records if (r.get("optout") or {}).get("fcra"))
  227. return {"parsed": len(records), "fcra_regulated": fcra,
  228. "cache_path": str(cache_path), "source_url": url}
  229. def refresh_all(cache_path: Path, fetched: dict[str, str] | None = None) -> dict:
  230. """Multi-source refresh: pull every CSV source, dedupe across states by domain, cache.
  231. `fetched` optionally supplies {source_key: csv_text} to bypass the network (tests). CSV
  232. sources are ingested as broker records; portal sources contribute their URL for the operator
  233. (no bulk export exists) but no records. CA is processed first so it wins domain collisions.
  234. """
  235. all_recs: list[dict] = []
  236. seen_domains: set[str] = set()
  237. per_source: dict[str, dict] = {}
  238. for key, src in SOURCES.items():
  239. if src["format"] != "csv":
  240. per_source[key] = {"jurisdiction": src["jurisdiction"], "format": "portal",
  241. "url": src["url"], "records": 0,
  242. "note": "searchable portal (no bulk export); operator/agent searches by name"}
  243. continue
  244. used_url = src["url"]
  245. try:
  246. if fetched is not None:
  247. text = fetched.get(key)
  248. if text is None:
  249. raise RuntimeError("no CSV text supplied")
  250. recs = parse(text, jurisdiction=src["jurisdiction"], has_drop=src["has_drop"])
  251. elif key == "ca":
  252. used_url, recs = _fetch_ca_latest() # newest-year-first with fallback
  253. else:
  254. recs = parse(fetch(src["url"]), jurisdiction=src["jurisdiction"], has_drop=src["has_drop"])
  255. except Exception as exc:
  256. per_source[key] = {"jurisdiction": src["jurisdiction"], "format": "csv", "error": str(exc)}
  257. continue
  258. added = 0
  259. for r in recs:
  260. dom = _domain(r["search"]["url"])
  261. if dom and dom in seen_domains:
  262. continue
  263. if dom:
  264. seen_domains.add(dom)
  265. all_recs.append(r)
  266. added += 1
  267. entry = {"jurisdiction": src["jurisdiction"], "format": "csv", "url": used_url,
  268. "parsed": len(recs), "added_after_dedupe": added,
  269. "fcra": sum(1 for r in recs if (r.get("optout") or {}).get("fcra"))}
  270. if key == "ca" and len(recs) < MIN_EXPECTED_CA:
  271. entry["warning"] = (f"only {len(recs)} parsed (expected >{MIN_EXPECTED_CA}); the CA "
  272. "registry file may be empty/moved - verify the source URL")
  273. per_source[key] = entry
  274. storage.write_json(cache_path, all_recs)
  275. return {"total": len(all_recs), "sources": per_source, "portals": portals(),
  276. "cache_path": str(cache_path)}