Files
Kronic-Krusaders/borg_chat_gateway.py
2026-11-25 20:19:55 -06:00

239 lines
9.4 KiB
Python

"""Small HTTP gateway for Kronic Chat mounted at /borg-chat/ on Media.
Does not replace or reconfigure Uvicorn or LiveKit.
"""
import http.client
import json
import re
import time
from urllib.parse import urlsplit
PREFIX = '/borg-chat'
UPSTREAM_HOST = '127.0.0.1'
UPSTREAM_PORT = 8001
# Separate the browser-facing Chat session from Media's root-path cookie.
# Chat's FastAPI backend still receives the cookie name it already expects.
CHAT_BROWSER_COOKIE = 'borg_chat_session'
CHAT_BACKEND_COOKIE = 'kronick_session'
# The Media site and the embedded Chat keep separate sessions. If they ever
# belong to different people (for example after switching accounts on Media),
# the embedded Chat must not keep running as the previous user.
_GUARDED_ROUTES = ('/app', '/api/auth/me', '/api/my/rooms', '/api/my/room-admin')
_IDENTITY_TTL_SECONDS = 20
_IDENTITY_CACHE = {}
def expired_chat_cookie():
return CHAT_BROWSER_COOKIE + '=; Path=' + PREFIX + '/; Max-Age=0; HttpOnly; SameSite=Lax'
def _chat_cookie_value(handler):
for part in handler.headers.get('Cookie', '').split(';'):
name, _, value = part.strip().partition('=')
if name == CHAT_BROWSER_COOKIE and value:
return value
return None
def _without_chat_cookie(value):
kept = [p.strip() for p in value.split(';')
if p.strip().partition('=')[0].strip() != CHAT_BROWSER_COOKIE]
return '; '.join(p for p in kept if p)
def _chat_username(chat_cookie):
"""Username of the Chat session, '' if invalid, None if it can't be checked."""
now = time.time()
hit = _IDENTITY_CACHE.get(chat_cookie)
if hit and hit[1] > now:
return hit[0]
conn = http.client.HTTPConnection(UPSTREAM_HOST, UPSTREAM_PORT, timeout=5)
try:
conn.request('GET', '/api/auth/me', headers={
'Host': UPSTREAM_HOST + ':' + str(UPSTREAM_PORT),
'Cookie': CHAT_BACKEND_COOKIE + '=' + chat_cookie,
})
response = conn.getresponse()
body = response.read()
if response.status == 200:
username = str(json.loads(body)['user']['username']).lower()
elif response.status in (401, 403):
username = ''
else:
return None
except (OSError, http.client.HTTPException, ValueError, KeyError, TypeError):
return None
finally:
conn.close()
if len(_IDENTITY_CACHE) > 256:
_IDENTITY_CACHE.clear()
_IDENTITY_CACHE[chat_cookie] = (username, now + _IDENTITY_TTL_SECONDS)
return username
def _media_username(handler):
try:
from media_accounts import session_user
return str(session_user(handler.get_session_token())['username']).lower()
except Exception:
return None
def chat_session_is_stale(handler):
"""True when a Chat session exists that belongs to someone other than the
signed-in Media user."""
chat_cookie = _chat_cookie_value(handler)
if not chat_cookie:
return False
media_user = _media_username(handler)
if not media_user:
return False
chat_user = _chat_username(chat_cookie)
return chat_user is not None and chat_user != media_user
def logout_chat(handler):
"""Best effort: end the embedded Chat session when the Media session ends."""
chat_cookie = _chat_cookie_value(handler)
if not chat_cookie:
return
_IDENTITY_CACHE.pop(chat_cookie, None)
conn = http.client.HTTPConnection(UPSTREAM_HOST, UPSTREAM_PORT, timeout=5)
try:
conn.request('POST', '/api/auth/logout', body=b'', headers={
'Host': UPSTREAM_HOST + ':' + str(UPSTREAM_PORT),
'Cookie': CHAT_BACKEND_COOKIE + '=' + chat_cookie,
'Content-Length': '0',
})
conn.getresponse().read()
except (OSError, http.client.HTTPException):
pass
finally:
conn.close()
def rewrite_request_cookie(value):
"""Send Chat only its own session cookie, never Media's session cookie."""
pairs = []
chat_session = None
for part in value.split(';'):
part = part.strip()
if '=' not in part:
continue
name, cookie_value = part.split('=', 1)
name = name.strip()
if name == CHAT_BROWSER_COOKIE:
chat_session = cookie_value
elif name != CHAT_BACKEND_COOKIE:
pairs.append(part)
if chat_session is not None:
pairs.append(CHAT_BACKEND_COOKIE + '=' + chat_session)
return '; '.join(pairs)
def rewrite_response_cookie(value):
"""Scope Chat's session cookie to /borg-chat/ and rename it."""
value = re.sub(r'^\s*' + re.escape(CHAT_BACKEND_COOKIE) + r'(?==)',
CHAT_BROWSER_COOKIE, value, count=1)
value = re.sub(r'(?i)(?<![\w-])Path=/(?!\S)', 'Path=' + PREFIX + '/', value)
# Accommodate Path=/; and Path=/ at end without touching other paths.
value = re.sub(r'(?i)(?<![\w-])Path=/(?=\s*(?:;|$))',
'Path=' + PREFIX + '/', value)
return value
# All root-absolute URLs in the legacy chat client must remain under the proxy.
CHAT_PATHS = ('api/', 'get-token', 'js/', 'css/', 'login', 'app', 'admin',
'chat.html', 'giphy.html', 'music-browser.html', 'screenshare.css',
'kkicon.png', 'helper_modules/', 'chat_uploads/', 'uploads/', 'files/')
def rewrite_text(data, content_type):
if not any(k in content_type.lower() for k in ('javascript', 'html', 'css', 'json')):
return data
text = data.decode('utf-8', errors='replace')
for item in CHAT_PATHS:
# Rewrite root absolute route references, not URLs with hostnames.
text = text.replace('"/' + item, '"' + PREFIX + '/' + item)
text = text.replace("'/" + item, "'" + PREFIX + '/' + item)
text = text.replace('`/' + item, '`' + PREFIX + '/' + item)
text = text.replace('(/' + item, '(' + PREFIX + '/' + item) if content_type.startswith('text/css') else text
# Explicitly handle window.location.origin + '/get-token' pattern and config absolute URL.
if 'javascript' in content_type.lower() and 'app-config' in text:
text = text.replace('`${window.location.origin}/get-token`', '`${window.location.origin}' + PREFIX + '/get-token`')
if 'install-config' in text:
text = re.sub(r'(TOKEN_URL\s*:\s*)["\'][^"\']+["\']', r'\1"' + PREFIX + '/get-token"', text)
return text.encode('utf-8')
def proxy(handler):
url = urlsplit(handler.path)
if not (url.path == PREFIX or url.path.startswith(PREFIX + '/')):
return False
path = url.path[len(PREFIX):] or '/app'
if path == '/':
path = '/app'
if url.query:
path += '?' + url.query
raw_length = handler.headers.get('Content-Length', '0') or '0'
try:
length = int(raw_length)
except (ValueError, TypeError):
handler.send_error(400, 'Invalid Content-Length')
return True
if length < 0:
handler.send_error(400, 'Invalid Content-Length')
return True
if length > 32 * 1024 * 1024:
handler.send_error(413, 'Chat request too large')
return True
body = handler.rfile.read(length) if length else None
headers = {k:v for k,v in handler.headers.items() if k.lower() not in
{'host', 'connection', 'content-length', 'accept-encoding', 'transfer-encoding',
'x-forwarded-for', 'x-real-ip', 'forwarded', 'x-forwarded-host', 'x-forwarded-proto'}}
stale_session = False
if 'Cookie' in headers and path.split('?', 1)[0].rstrip('/') in _GUARDED_ROUTES:
stale_session = chat_session_is_stale(handler)
if stale_session:
# Chat is signed in as someone else: drop that session so Chat asks
# the current user to sign in instead of acting as the old one.
headers['Cookie'] = _without_chat_cookie(headers['Cookie'])
if 'Cookie' in headers:
headers['Cookie'] = rewrite_request_cookie(headers['Cookie'])
if not headers['Cookie']:
del headers['Cookie']
headers['Host'] = '127.0.0.1:8001'
headers['Accept-Encoding'] = 'identity'
conn = http.client.HTTPConnection(UPSTREAM_HOST, UPSTREAM_PORT, timeout=25)
try:
conn.request(handler.command, path, body=body, headers=headers)
resp = conn.getresponse()
output = resp.read()
content_type = resp.getheader('Content-Type', '')
output = rewrite_text(output, content_type)
handler.send_response(resp.status)
for name, value in resp.getheaders():
key = name.lower()
if key in ('content-length', 'transfer-encoding', 'connection', 'content-encoding', 'server', 'date'):
continue
if key == 'location' and value.startswith('/') and not value.startswith(PREFIX + '/'):
value = PREFIX + value
if key == 'set-cookie':
value = rewrite_response_cookie(value)
if key == 'content-security-policy':
# Original CSP paths may differ under the gateway; let browser validate.
pass
handler.send_header(name, value)
if stale_session:
handler.send_header('Set-Cookie', expired_chat_cookie())
handler.send_header('Content-Length', str(len(output)))
handler.end_headers()
if handler.command != 'HEAD':
handler.wfile.write(output)
except (OSError, http.client.HTTPException) as exc:
handler.send_error(502, 'Kronic Chat unavailable')
print('[BORG CHAT GATEWAY]', type(exc).__name__, str(exc))
finally:
conn.close()
return True