dossier.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. """Subject dossier management + consent gate + least-disclosure field selection."""
  2. from __future__ import annotations
  3. import datetime as _dt
  4. import hashlib
  5. import os
  6. from pathlib import Path
  7. import paths
  8. import storage
  9. # Identifiers we never volunteer in an opt-out (would expand exposure, not reduce it).
  10. NEVER_VOLUNTEER = {"ssn", "social_security_number", "passport", "drivers_license"}
  11. VALID_CONSENT_METHODS = {"self", "written_authorization", "poa"}
  12. def now() -> str:
  13. return _dt.datetime.now(_dt.UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
  14. def new_subject_id(full_name: str = "") -> str:
  15. # Opaque id: derives NOTHING from the name, so PII never leaks into directory names,
  16. # case ids, drafts, or the audit log. full_name kept only for call compatibility.
  17. return "sub_" + hashlib.sha1(os.urandom(8)).hexdigest()[:10]
  18. def create(identity: dict, consent: dict, residency: str = "US", prefs: dict | None = None) -> dict:
  19. dossier = {
  20. "subject_id": new_subject_id(identity.get("full_name", "subject")),
  21. "consent": consent,
  22. "identity": identity,
  23. "residency_jurisdiction": residency,
  24. "preferences": prefs or {"email_mode": "draft_only", "rescan_interval_days": 120},
  25. "created_at": now(),
  26. }
  27. save(dossier)
  28. return dossier
  29. def load(subject_id: str) -> dict | None:
  30. return storage.read_json(paths.dossier_path(subject_id), None)
  31. def save(dossier: dict) -> Path:
  32. return storage.write_json(paths.dossier_path(dossier["subject_id"]), dossier)
  33. def is_authorized(dossier: dict) -> bool:
  34. c = dossier.get("consent") or {}
  35. return bool(c.get("authorized")) and c.get("method") in VALID_CONSENT_METHODS
  36. def require_authorized(dossier: dict) -> None:
  37. if not is_authorized(dossier):
  38. raise PermissionError(
  39. f"subject {dossier.get('subject_id')!r} has no recorded authorization; refusing to act"
  40. )
  41. def all_names(dossier: dict) -> list[str]:
  42. """Primary name + aliases (maiden/married/nicknames), deduped, in priority order."""
  43. ident = dossier.get("identity", {})
  44. out: list[str] = []
  45. seen: set[str] = set()
  46. for n in [ident.get("full_name"), *(ident.get("also_known_as") or [])]:
  47. if n and n.lower() not in seen:
  48. seen.add(n.lower())
  49. out.append(n)
  50. return out
  51. def all_addresses(dossier: dict) -> list[dict]:
  52. """Current + prior addresses, each tagged with `kind` (current|prior)."""
  53. ident = dossier.get("identity", {})
  54. out: list[dict] = []
  55. cur = ident.get("current_address")
  56. if cur:
  57. out.append({**cur, "kind": cur.get("kind", "current")})
  58. for a in ident.get("prior_addresses") or []:
  59. out.append({**a, "kind": a.get("kind", "prior")})
  60. return out
  61. def all_locations(dossier: dict) -> list[dict]:
  62. """Distinct city/state pairs across all addresses (the vectors for name searches)."""
  63. out: list[dict] = []
  64. seen: set[tuple] = set()
  65. for a in all_addresses(dossier):
  66. city = a.get("city")
  67. key = ((city or "").lower(), (a.get("state") or "").lower())
  68. if city and key not in seen:
  69. seen.add(key)
  70. out.append({"city": city, "state": a.get("state")})
  71. return out
  72. def contact_email(dossier: dict) -> str | None:
  73. """The single email used for opt-out correspondence (designated, else the first)."""
  74. ident = dossier.get("identity", {})
  75. prefs = dossier.get("preferences", {})
  76. emails = ident.get("emails") or []
  77. return prefs.get("contact_email_for_optouts") or (emails[0] if emails else None)
  78. def focus_phone(dossier: dict) -> str | None:
  79. """The number a phone-led (spam-call) run is scrubbing, if one was designated at intake.
  80. `select_disclosure` uses it as the `phone` field so a phone-asking opt-out form gets
  81. the number being scrubbed even when it is not `phones[0]`.
  82. """
  83. return (dossier.get("preferences") or {}).get("focus_phone")
  84. def select_disclosure(dossier: dict, inputs: list[str], override_email: str | None = None) -> dict:
  85. """Return ONLY the dossier fields a broker's opt-out actually requires.
  86. Enforces least-disclosure: skips anything in NEVER_VOLUNTEER, and skips
  87. `profile_url` (that is captured per-listing at submit time, not from the dossier).
  88. A single contact email is used for correspondence even when the subject has several
  89. (see all_names / all_addresses / search vectors for using every alternate to *find* listings).
  90. """
  91. ident = dossier.get("identity", {})
  92. addr = ident.get("current_address") or {}
  93. phones = ident.get("phones") or []
  94. available = {
  95. "full_name": ident.get("full_name"),
  96. "first_name": (ident.get("full_name") or "").split(" ")[0] or None,
  97. "contact_email": override_email or contact_email(dossier),
  98. "current_address": addr or None,
  99. "street": addr.get("line1"),
  100. "city": addr.get("city"),
  101. "state": addr.get("state"),
  102. "postal": addr.get("postal"),
  103. "date_of_birth": ident.get("date_of_birth"),
  104. "phone": focus_phone(dossier) or (phones[0] if phones else None),
  105. }
  106. out: dict = {}
  107. for key in inputs:
  108. if key in NEVER_VOLUNTEER or key == "profile_url":
  109. continue
  110. if available.get(key) is not None:
  111. out[key] = available[key]
  112. return out