Files

296 lines
11 KiB
Python

"""Shared OWA (Exchange) JSON-API client for the BBS mailbox (Kati).
Used by the mail MCP server (server.py) and by the calendar fetcher
(/opt/owa-kati-calendar/owa_fetch.py).
Exchange 2019 (S25-EXCHANGE) with classic OWA form login under
https://bbsbex.bbsb.org/owa/. EWS basic auth is disabled (401), so access
goes through the OWA form flow with an HTTP session and the internal
OWA JSON API (/owa/service.svc?action=...).
HARTE REGEL (lockout protection): exactly ONE login attempt per process.
On any login failure the caller aborts immediately, no retry, so Kati's work
password is never locked by automatic repetitions.
"""
import os
import re
import time
import urllib.parse
import requests
OWA_BASE = os.environ.get("OWA_BASE", "https://bbsbex.bbsb.org/owa").rstrip("/")
AUTH_FILE = os.environ.get(
"OWA_AUTH_FILE", "/opt/mcp-servers/owamail/auth.txt"
)
LOGIN_URL = OWA_BASE + "/auth.owa"
SERVICE_URL = OWA_BASE + "/service.svc"
SESSION_MAX_AGE_S = 600 # 10 min, then a fresh login
class OWASessionError(Exception):
"""Session expired / login failed."""
_DISTINGUISHED = {
"msgfolderroot", "inbox", "sentitems", "drafts", "deleteditems",
"junkemail", "outbox", "calendar", "contacts", "tasks", "notes",
"journal", "searchfolders",
}
_FOLDER_ALIASES = {
"posteingang": "inbox",
"inbox": "inbox",
"gesendet": "sentitems",
"sent": "sentitems",
"gesendete objekte": "sentitems",
"entwürfe": "drafts",
"entwuerfe": "drafts",
"drafts": "drafts",
"gelöschte objekte": "deleteditems",
"geloeschte objekte": "deleteditems",
"papierkorb": "deleteditems",
"deleted": "deleteditems",
"junk": "junkemail",
"spam": "junkemail",
}
def load_creds(auth_file: str = AUTH_FILE):
with open(auth_file) as f:
data = {}
for line in f:
line = line.strip()
if "=" in line and not line.startswith("#"):
k, v = line.split("=", 1)
data[k.strip()] = v.strip()
return data.get("BBS_USER", ""), data.get("BBS_PASSWORD", "")
def new_session() -> requests.Session:
s = requests.Session()
s.headers.update({
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/120.0 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
})
return s
class OWAClient:
"""OWA JSON-API client with a single-process session cache."""
def __init__(self, base: str = OWA_BASE, auth_file: str = AUTH_FILE,
session_max_age: int = SESSION_MAX_AGE_S):
self.base = base.rstrip("/")
self.auth_file = auth_file
self.session_max_age = session_max_age
self._session = None
self._session_ts = 0.0
# ------------------------------------------------------------------
# Login (lockout protection: EXACTLY ONE attempt)
# ------------------------------------------------------------------
def login(self) -> str:
"""Exactly ONE login attempt. Aborts immediately on failure, no retry."""
user, password = load_creds(self.auth_file)
if not user or not password:
return f"Fehler: BBS-Credentials fehlen in {self.auth_file}"
s = new_session()
login_url = self.base + "/auth.owa"
try:
r = s.get(login_url, timeout=30)
r.raise_for_status()
fields = {
"destination": self.base,
"flags": "4",
"forcedownlevel": "0",
"isUtf8": "1",
"username": user,
"password": password,
"passwordText": "",
}
r2 = s.post(login_url, data=fields, allow_redirects=True, timeout=30)
cookie_names = [c.name for c in s.cookies]
# Exchange 2019 sets X-OWA-CANARY + X-BackEndCookie on success,
# not an 'OWASession' cookie. These two are the success criterion.
has_session_cookie = (
"X-OWA-CANARY" in cookie_names and "X-BackEndCookie" in cookie_names
)
if has_session_cookie:
self._session = s
self._session_ts = time.time()
return "LOGIN_OK"
if r2.status_code == 200 and "logon.aspx" in r2.url:
return ("LOGIN_FEHLGESCHLAGEN: OWA-Login abgelehnt (falsche "
"Zugangsdaten oder Konto gesperrt). Kein Retry.")
return (
"LOGIN_FEHLGESCHLAGEN: Keine OWA-Session gesetzt "
f"(Status {r2.status_code}, Cookies: {cookie_names}). Kein Retry."
)
except Exception as e:
return f"LOGIN_FEHLGESCHLAGEN: {e}"
def ensure_session(self) -> str:
if self._session is None:
return self.login()
if time.time() - self._session_ts > self.session_max_age:
self._session = None
return self.login()
return "LOGIN_OK"
def session(self) -> requests.Session:
res = self.ensure_session()
if res != "LOGIN_OK":
raise OWASessionError(res)
return self._session
# ------------------------------------------------------------------
# OWA JSON-API
# ------------------------------------------------------------------
@staticmethod
def header(server_version: str = "Exchange2013") -> dict:
return {
"__type": "JsonRequestHeaders:#Exchange",
"RequestServerVersion": server_version,
}
@staticmethod
def get_canary(sess: requests.Session) -> str:
for c in sess.cookies:
if c.name == "X-OWA-CANARY" and c.value:
return c.value
return ""
def api(self, action: str, payload: dict, *, timeout: int = 30) -> dict:
"""POST to the OWA JSON API. Raises OWASessionError on session expiry."""
s = self.session()
canary = self.get_canary(s)
url = f"{self.base}/service.svc?action={action}&EP=1&ID=-1&AC=1"
headers = {
"Content-Type": "application/json; charset=utf-8",
"Action": action,
"X-OWA-CANARY": canary,
"X-Requested-With": "XMLHttpRequest",
}
try:
r = s.post(url, json=payload, headers=headers, timeout=timeout)
except requests.exceptions.RequestException as e:
raise OWASessionError(f"Request fehlgeschlagen: {e}")
new_canary = self.get_canary(s)
if new_canary:
s.cookies.set("X-OWA-CANARY", new_canary)
if r.status_code in (401, 440):
raise OWASessionError(f"Session abgelaufen (HTTP {r.status_code})")
if "text/html" in r.headers.get("Content-Type", ""):
raise OWASessionError(
f"Session abgelaufen oder ungueltige Action (HTML, HTTP {r.status_code})"
)
try:
return r.json()
except ValueError:
raise OWASessionError(f"Unerwartete Antwort (HTTP {r.status_code})")
@staticmethod
def items(data: dict) -> list:
try:
return data["Body"]["ResponseMessages"]["Items"]
except (KeyError, TypeError):
return []
def resolve_folder_id(self, name: str):
"""Folder name (de/en) -> real numeric Exchange FolderId."""
alias = _FOLDER_ALIASES.get(name.strip().lower(), name.strip().lower())
if alias in _DISTINGUISHED:
payload = {
"__type": "GetFolderJsonRequest:#Exchange",
"Header": self.header(),
"Body": {
"__type": "GetFolderRequest:#Exchange",
"FolderShape": {
"__type": "FolderResponseShape:#Exchange",
"BaseShape": "IdOnly",
},
"FolderIds": [
{"__type": "DistinguishedFolderId:#Exchange", "Id": alias}
],
},
}
data = self.api("GetFolder", payload)
for msg in self.items(data):
if "Folders" in msg:
for f in msg["Folders"]:
fid = f.get("FolderId", {}).get("Id")
if fid:
return fid
payload = {
"__type": "FindFolderJsonRequest:#Exchange",
"Header": self.header(),
"Body": {
"__type": "FindFolderRequest:#Exchange",
"FolderShape": {
"__type": "FolderResponseShape:#Exchange",
"BaseShape": "Default",
},
"ParentFolderIds": [
{"__type": "DistinguishedFolderId:#Exchange", "Id": "msgfolderroot"}
],
"Traversal": "Shallow",
"Paging": {
"__type": "IndexedPageView:#Exchange",
"BasePoint": "Beginning",
"Offset": 0,
"MaxEntriesReturned": 200,
},
},
}
data = self.api("FindFolder", payload)
for msg in self.items(data):
if "RootFolder" in msg and "Folders" in msg["RootFolder"]:
for f in msg["RootFolder"]["Folders"]:
if f.get("DisplayName", "").lower() == name.strip().lower():
return f.get("FolderId", {}).get("Id")
return None
def download_file(self, attachment_id: str, timeout: int = 60):
"""Download an attachment via GetFileAttachment. Returns (bytes, filename, content_type)."""
s = self.session()
canary = self.get_canary(s)
url = (
f"{self.base}/service.svc/s/GetFileAttachment"
f"?id={urllib.parse.quote(attachment_id)}&X-OWA-CANARY={urllib.parse.quote(canary)}"
)
try:
resp = s.get(url, timeout=timeout)
except requests.exceptions.RequestException as e:
raise OWASessionError(f"Download fehlgeschlagen: {e}")
if resp.status_code in (401, 440):
raise OWASessionError(f"Session abgelaufen (HTTP {resp.status_code})")
if "text/html" in resp.headers.get("Content-Type", ""):
raise OWASessionError("Session abgelaufen (HTML-Antwort beim Download)")
filename = "attachment"
cd = resp.headers.get("Content-Disposition", "")
if cd:
m = re.search(r'filename\*=(?:UTF-8\'\'|utf-8\'\')(.+?)(?:;|$)', cd)
if m:
filename = urllib.parse.unquote(m.group(1).strip())
else:
m = re.search(r'filename="?([^";]+)"?', cd)
if m:
filename = urllib.parse.unquote(m.group(1).strip())
content_type = resp.headers.get("Content-Type", "application/octet-stream")
if ";" in content_type:
content_type = content_type.split(";", 1)[0].strip()
return resp.content, filename, content_type
# Default client for single-process consumers (mail MCP server).
client = OWAClient()