File size: 4,725 Bytes
49bbb08
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
"""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": "<raw cookie string from document.cookie>",
      "refreshed_at": "<iso8601 timestamp>",
      "refreshed_by": "<email or label>"
    }

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