GopiBNA commited on
Commit
49bbb08
·
verified ·
1 Parent(s): e2f13dc

Add team session helper module

Browse files
Files changed (1) hide show
  1. engine/team_session.py +143 -0
engine/team_session.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Team-lead daily session refresh.
2
+
3
+ Background
4
+ ----------
5
+ BNAmericas sits behind Cloudflare. Their bot-protection layer sometimes
6
+ flags fresh logins coming from a datacenter IP (which is what every
7
+ researcher's batch looks like once we're hosted on Hugging Face Spaces).
8
+ Even with correct credentials the auto-login can be rejected.
9
+
10
+ The cleanest workaround that requires **no researcher action** is to let
11
+ ONE person (the team lead) sign in to BNA on their own laptop once a day,
12
+ copy their browser's session cookie, and paste it into a hidden Admin tab
13
+ on the web app. The web app stores that cookie in a small JSON file on
14
+ disk; every researcher's batch reads it on startup and injects it into
15
+ the headless Chromium BEFORE attempting a fresh password login.
16
+
17
+ Cloudflare sees an already-authenticated session arriving from the
18
+ datacenter IP -- which is suspicious but already-signed-in -- rather than
19
+ a fresh login attempt, which is far more likely to be flagged.
20
+
21
+ Storage
22
+ -------
23
+ The session is stored in ``$BNA_TEAM_SESSION_PATH`` if set, otherwise in
24
+ ``/tmp/bna_team_session.json``. The file holds:
25
+
26
+ {
27
+ "cookie": "<raw cookie string from document.cookie>",
28
+ "refreshed_at": "<iso8601 timestamp>",
29
+ "refreshed_by": "<email or label>"
30
+ }
31
+
32
+ The cookie naturally expires after ~24 hours on BNA's side. We expose
33
+ ``age_hours()`` so the Admin tab can render a colour-coded warning when
34
+ the cookie is close to expiry.
35
+
36
+ Security
37
+ --------
38
+ - The cookie is owner-readable only (chmod 0600).
39
+ - It is never logged.
40
+ - It is never sent anywhere except back to BNAmericas itself.
41
+ - Cleared on demand from the Admin tab.
42
+
43
+ This module has zero external dependencies -- just stdlib -- so it can
44
+ be imported from both the Streamlit UI (app.py) and the batch worker
45
+ (batch_runner.py) without forcing an install.
46
+ """
47
+ from __future__ import annotations
48
+
49
+ import json
50
+ import os
51
+ from datetime import datetime, timezone
52
+ from pathlib import Path
53
+ from typing import Optional, TypedDict
54
+
55
+
56
+ class TeamSession(TypedDict, total=False):
57
+ cookie: str
58
+ refreshed_at: str # ISO 8601, UTC, with "+00:00" suffix
59
+ refreshed_by: str
60
+
61
+
62
+ def _path() -> Path:
63
+ """Resolve the session file path. Override with $BNA_TEAM_SESSION_PATH."""
64
+ raw = os.environ.get("BNA_TEAM_SESSION_PATH")
65
+ if raw:
66
+ return Path(raw)
67
+ return Path("/tmp/bna_team_session.json")
68
+
69
+
70
+ def save_session(cookie: str, refreshed_by: str = "") -> TeamSession:
71
+ """Persist a fresh BNA cookie. Returns the stored record."""
72
+ record: TeamSession = {
73
+ "cookie": (cookie or "").strip(),
74
+ "refreshed_at": datetime.now(timezone.utc).isoformat(),
75
+ "refreshed_by": (refreshed_by or "").strip(),
76
+ }
77
+ p = _path()
78
+ p.parent.mkdir(parents=True, exist_ok=True)
79
+ p.write_text(json.dumps(record), encoding="utf-8")
80
+ try:
81
+ os.chmod(p, 0o600)
82
+ except Exception:
83
+ # Filesystems that don't support chmod (e.g. some HF tmpfs
84
+ # mounts) silently ignore -- the JSON is still owner-only by
85
+ # virtue of the container's user namespace.
86
+ pass
87
+ return record
88
+
89
+
90
+ def load_session() -> Optional[TeamSession]:
91
+ """Return the stored session, or None if the file is missing or unreadable."""
92
+ p = _path()
93
+ if not p.exists():
94
+ return None
95
+ try:
96
+ return json.loads(p.read_text(encoding="utf-8"))
97
+ except Exception:
98
+ return None
99
+
100
+
101
+ def clear_session() -> None:
102
+ """Wipe the session file (Admin tab 'Clear' button)."""
103
+ p = _path()
104
+ try:
105
+ if p.exists():
106
+ p.unlink()
107
+ except Exception:
108
+ pass
109
+
110
+
111
+ def age_hours() -> Optional[float]:
112
+ """How old is the stored cookie, in hours? None if no cookie on file."""
113
+ rec = load_session()
114
+ if not rec or not rec.get("refreshed_at"):
115
+ return None
116
+ try:
117
+ ts = datetime.fromisoformat(rec["refreshed_at"])
118
+ # Make naive timestamps safe to subtract.
119
+ if ts.tzinfo is None:
120
+ ts = ts.replace(tzinfo=timezone.utc)
121
+ delta = datetime.now(timezone.utc) - ts
122
+ return delta.total_seconds() / 3600.0
123
+ except Exception:
124
+ return None
125
+
126
+
127
+ def get_cookie_if_fresh(max_age_hours: float = 22.0) -> Optional[str]:
128
+ """Return the cookie string ONLY if newer than max_age_hours.
129
+
130
+ Used by batch_runner.run_batch() on the pre-login pass. A BNA
131
+ session cookie expires in ~24h; we treat anything older than 22h as
132
+ stale to avoid handing the researcher a cookie that dies mid-batch.
133
+ """
134
+ age = age_hours()
135
+ if age is None:
136
+ return None
137
+ if age > max_age_hours:
138
+ return None
139
+ rec = load_session()
140
+ if not rec:
141
+ return None
142
+ cookie = (rec.get("cookie") or "").strip()
143
+ return cookie or None