"""Team-lead daily session refresh. Background ---------- BNAmericas sits behind Cloudflare. Their bot-protection layer sometimes flags fresh logins coming from a datacenter IP (which is what every researcher's batch looks like once we're hosted on Hugging Face Spaces). Even with correct credentials the auto-login can be rejected. The cleanest workaround that requires **no researcher action** is to let ONE person (the team lead) sign in to BNA on their own laptop once a day, copy their browser's session cookie, and paste it into a hidden Admin tab on the web app. The web app stores that cookie in a small JSON file on disk; every researcher's batch reads it on startup and injects it into the headless Chromium BEFORE attempting a fresh password login. Cloudflare sees an already-authenticated session arriving from the datacenter IP -- which is suspicious but already-signed-in -- rather than a fresh login attempt, which is far more likely to be flagged. Storage ------- The session is stored in ``$BNA_TEAM_SESSION_PATH`` if set, otherwise in ``/tmp/bna_team_session.json``. The file holds: { "cookie": "", "refreshed_at": "", "refreshed_by": "" } The cookie naturally expires after ~24 hours on BNA's side. We expose ``age_hours()`` so the Admin tab can render a colour-coded warning when the cookie is close to expiry. Security -------- - The cookie is owner-readable only (chmod 0600). - It is never logged. - It is never sent anywhere except back to BNAmericas itself. - Cleared on demand from the Admin tab. This module has zero external dependencies -- just stdlib -- so it can be imported from both the Streamlit UI (app.py) and the batch worker (batch_runner.py) without forcing an install. """ from __future__ import annotations import json import os from datetime import datetime, timezone from pathlib import Path from typing import Optional, TypedDict class TeamSession(TypedDict, total=False): cookie: str refreshed_at: str # ISO 8601, UTC, with "+00:00" suffix refreshed_by: str def _path() -> Path: """Resolve the session file path. Override with $BNA_TEAM_SESSION_PATH.""" raw = os.environ.get("BNA_TEAM_SESSION_PATH") if raw: return Path(raw) return Path("/tmp/bna_team_session.json") def save_session(cookie: str, refreshed_by: str = "") -> TeamSession: """Persist a fresh BNA cookie. Returns the stored record.""" record: TeamSession = { "cookie": (cookie or "").strip(), "refreshed_at": datetime.now(timezone.utc).isoformat(), "refreshed_by": (refreshed_by or "").strip(), } p = _path() p.parent.mkdir(parents=True, exist_ok=True) p.write_text(json.dumps(record), encoding="utf-8") try: os.chmod(p, 0o600) except Exception: # Filesystems that don't support chmod (e.g. some HF tmpfs # mounts) silently ignore -- the JSON is still owner-only by # virtue of the container's user namespace. pass return record def load_session() -> Optional[TeamSession]: """Return the stored session, or None if the file is missing or unreadable.""" p = _path() if not p.exists(): return None try: return json.loads(p.read_text(encoding="utf-8")) except Exception: return None def clear_session() -> None: """Wipe the session file (Admin tab 'Clear' button).""" p = _path() try: if p.exists(): p.unlink() except Exception: pass def age_hours() -> Optional[float]: """How old is the stored cookie, in hours? None if no cookie on file.""" rec = load_session() if not rec or not rec.get("refreshed_at"): return None try: ts = datetime.fromisoformat(rec["refreshed_at"]) # Make naive timestamps safe to subtract. if ts.tzinfo is None: ts = ts.replace(tzinfo=timezone.utc) delta = datetime.now(timezone.utc) - ts return delta.total_seconds() / 3600.0 except Exception: return None def get_cookie_if_fresh(max_age_hours: float = 22.0) -> Optional[str]: """Return the cookie string ONLY if newer than max_age_hours. Used by batch_runner.run_batch() on the pre-login pass. A BNA session cookie expires in ~24h; we treat anything older than 22h as stale to avoid handing the researcher a cookie that dies mid-batch. """ age = age_hours() if age is None: return None if age > max_age_hours: return None rec = load_session() if not rec: return None cookie = (rec.get("cookie") or "").strip() return cookie or None