From 43681272b5a5d4bdf0ea8efa3b15d3a3840c0346 Mon Sep 17 00:00:00 2001 From: admin Date: Wed, 25 Nov 2026 20:19:55 -0600 Subject: [PATCH] Upload files to "/" --- ai_command_sessions.py | 32 ++++++ allowlist_store.py | 36 ++++++ balroc_kronic_bridge.py | 171 +++++++++++++++++++++++++++++ borg_chat_gateway.py | 238 ++++++++++++++++++++++++++++++++++++++++ kronic_chat_manager.py | 73 ++++++++++++ 5 files changed, 550 insertions(+) create mode 100644 ai_command_sessions.py create mode 100644 allowlist_store.py create mode 100644 balroc_kronic_bridge.py create mode 100644 borg_chat_gateway.py create mode 100644 kronic_chat_manager.py diff --git a/ai_command_sessions.py b/ai_command_sessions.py new file mode 100644 index 0000000..efd33fe --- /dev/null +++ b/ai_command_sessions.py @@ -0,0 +1,32 @@ +"""Per-account per-window Balroc chat-session ownership. No browser-owned session IDs.""" +from __future__ import annotations +import re +from media_accounts import open_database + +_WINDOW = re.compile(r'^[A-Za-z0-9_-]{12,80}$') + +def _schema(db): + db.execute('''CREATE TABLE IF NOT EXISTS kronic_ai_windows ( + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + window_id TEXT NOT NULL, + balroc_session TEXT, + PRIMARY KEY (user_id, window_id) + )''') + +def get(user_id, window_id): + if not isinstance(window_id,str) or not _WINDOW.fullmatch(window_id): + raise ValueError('Invalid AI window identifier') + with open_database() as db: + _schema(db) + row=db.execute('SELECT balroc_session FROM kronic_ai_windows WHERE user_id=? AND window_id=?',(int(user_id),window_id)).fetchone() + return str(row['balroc_session']) if row and row['balroc_session'] else '' + +def put(user_id, window_id, balroc_session): + if not isinstance(balroc_session,str) or len(balroc_session)>128: + raise ValueError('Invalid Balroc conversation identifier') + with open_database() as db: + _schema(db) + db.execute('''INSERT INTO kronic_ai_windows(user_id,window_id,balroc_session) VALUES(?,?,?) + ON CONFLICT(user_id,window_id) DO UPDATE SET balroc_session=excluded.balroc_session''', + (int(user_id),window_id,balroc_session)) + db.commit() diff --git a/allowlist_store.py b/allowlist_store.py new file mode 100644 index 0000000..876beee --- /dev/null +++ b/allowlist_store.py @@ -0,0 +1,36 @@ +"""Persistent device-specific approvals for Balroc Jellyfin sessions.""" +from __future__ import annotations +import json +import os +import threading +from pathlib import Path + +_LOCK = threading.Lock() +_APPROVAL_FILE = Path(__file__).resolve().parent.parent / 'data' / 'jellyfin_approved_device_ids.json' + +def approved_ids() -> set[str]: + try: + data=json.loads(_APPROVAL_FILE.read_text(encoding='utf-8')) + return {x.strip().casefold() for x in data.get('device_ids',[]) if isinstance(x,str) and x.strip()} + except FileNotFoundError: + return set() + except (ValueError, OSError, AttributeError, TypeError): + return set() + +def approve_device(device_id: str) -> dict: + device_id=str(device_id or '').strip() + if not device_id or len(device_id)>200 or any(x in device_id for x in ('\n','\r','/','\\')): + raise ValueError('Invalid device ID') + with _LOCK: + ids=approved_ids() + ids.add(device_id.casefold()) + _APPROVAL_FILE.parent.mkdir(parents=True,exist_ok=True) + temporary=_APPROVAL_FILE.with_suffix('.tmp') + with temporary.open('w',encoding='utf-8') as fd: + os.chmod(temporary,0o600) + json.dump({'device_ids':sorted(ids)},fd,indent=2) + fd.write('\n') + fd.flush() + os.fsync(fd.fileno()) + temporary.replace(_APPROVAL_FILE) + return {'approved':True,'device_id':device_id} diff --git a/balroc_kronic_bridge.py b/balroc_kronic_bridge.py new file mode 100644 index 0000000..ede4fb5 --- /dev/null +++ b/balroc_kronic_bridge.py @@ -0,0 +1,171 @@ +"""Admin-only Kronic UI -> Balroc and Whisper backend proxy. No secrets sent to browsers.""" +from __future__ import annotations +import base64 +import binascii +import subprocess +import tempfile +from pathlib import Path +import json +import os +import urllib.request +import urllib.error +import uuid + +class BridgeError(Exception): + def __init__(self, message, status=502): + super().__init__(message) + self.status=status + +def status(): + return {"configured": bool(os.getenv("KRONIC_BALROC_URL", "http://172.22.1.161:8182")), + "whisper_configured": bool(os.getenv("KRONIC_WHISPER_TRANSCRIBE_URL", "")), + "tts_configured": False} + +def _post(url, content, headers, timeout=90): + if not url.startswith(("http://", "https://")): + raise BridgeError("Invalid backend URL", 500) + req=urllib.request.Request(url, data=content, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as response: + return response.read(2_000_000) + except urllib.error.HTTPError as exc: + detail=exc.read(500).decode("utf-8", "replace") + raise BridgeError(f"Backend returned HTTP {exc.code}: {detail}", 502) from exc + except (urllib.error.URLError, TimeoutError) as exc: + raise BridgeError(f"Backend unavailable: {exc}", 502) from exc + +def chat(body): + message=str(body.get("message", "")).strip() + if not message or len(message)>6000: + raise BridgeError("Message is empty or too long",400) + api=os.getenv("KRONIC_BALROC_URL", "http://172.22.1.161:8182").rstrip("/") + session=str(body.get("session_id") or "").strip() + if len(session)>128: + raise BridgeError("Invalid session ID", 400) + payload={"message":message,"use_tools":bool(body.get("use_tools",False))} + if session: + payload["session_id"]=session + headers={"Content-Type":"application/json"} + secret=os.getenv("KRONIC_BALROC_CONTROL_KEY", "") + if secret: + headers["X-Balroc-Control-Key"]=secret + raw=_post(api+"/api/chat",json.dumps(payload).encode(),headers,timeout=120) + try: + result=json.loads(raw) + except ValueError as exc: + raise BridgeError("Balroc returned invalid JSON") from exc + return {"reply":result.get("reply", ""), + "session_id":result.get("session_id") or result.get("conversation_id") or session, + "tool_calls": [str(x.get("name", "")) for x in result.get("tool_calls", []) if isinstance(x,dict)], + "error":result.get("detail") or result.get("error")} + +def _convert_audio_to_wav(audio: bytes) -> bytes: + """Decode browser microphone audio to a standard, seekable PCM WAV file. + + whisper.cpp's /inference rejects Opus-in-WebM on many builds. We use a + temporary file only for FFmpeg's WAV output so its RIFF length is valid; + the file is removed immediately afterward. + """ + with tempfile.TemporaryDirectory(prefix="kronic-whisper-") as temporary: + wav_path = Path(temporary) / "speech.wav" + command = [ + "ffmpeg", "-hide_banner", "-loglevel", "error", "-nostdin", + "-i", "pipe:0", "-map", "0:a:0", "-vn", "-sn", "-dn", + "-t", "90", "-ar", "16000", "-ac", "1", + "-c:a", "pcm_s16le", "-f", "wav", str(wav_path), + ] + try: + result = subprocess.run( + command, input=audio, stdout=subprocess.DEVNULL, + stderr=subprocess.PIPE, timeout=45, check=False, + ) + except FileNotFoundError as exc: + raise BridgeError("FFmpeg is not installed on the Kronic server", 503) from exc + except subprocess.TimeoutExpired as exc: + raise BridgeError("Audio conversion timed out", 504) from exc + if result.returncode != 0 or not wav_path.is_file(): + detail = result.stderr.decode("utf-8", "replace")[-400:].strip() + raise BridgeError(f"Could not decode microphone recording: {detail or 'FFmpeg failed'}", 422) + wav = wav_path.read_bytes() + if not wav.startswith(b"RIFF") or wav[8:12] != b"WAVE" or len(wav) < 48: + raise BridgeError("FFmpeg produced an invalid WAV file", 502) + if len(wav) > 6_000_000: + raise BridgeError("Recording is too long; please use a shorter clip", 413) + return wav + + +def transcribe(body): + endpoint = os.getenv("KRONIC_WHISPER_TRANSCRIBE_URL", "").strip() + if not endpoint: + raise BridgeError("Whisper endpoint not configured: set KRONIC_WHISPER_TRANSCRIBE_URL", 503) + encoded = body.get("audio_base64", "") + if not isinstance(encoded, str) or len(encoded) > 8_000_000: + raise BridgeError("Invalid or oversized audio", 413) + try: + audio = base64.b64decode(encoded, validate=True) + except (ValueError, binascii.Error) as exc: + raise BridgeError("Invalid base64 audio", 400) from exc + if not audio or len(audio) > 5_000_000: + raise BridgeError("Audio must be between 1 byte and 5 MB", 413) + + wav = _convert_audio_to_wav(audio) + boundary = "KronicBalroc" + uuid.uuid4().hex + parts = [] + + def field(name, value): + parts.append( + f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n{value}\r\n'.encode() + ) + + field("response_format", "json") + parts.append( + (f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="speech.wav"\r\n' + 'Content-Type: audio/wav\r\n\r\n').encode() + wav + b"\r\n" + ) + parts.append(f"--{boundary}--\r\n".encode()) + raw = _post( + endpoint, b"".join(parts), + {"Content-Type": f"multipart/form-data; boundary={boundary}"}, + timeout=100, + ) + try: + result = json.loads(raw) + except ValueError as exc: + raise BridgeError("Whisper response must be JSON") from exc + transcript = str(result.get("text", "") or "").strip() + if not transcript: + raise BridgeError("Whisper returned no transcription", 422) + return {"text": transcript} + + +def clients(): + """Read all live Jellyfin clients via Balroc; no tokens reach the browser.""" + url = os.getenv('KRONIC_BALROC_URL', 'http://172.22.1.161:8182').strip().rstrip('/') + if not url.startswith(('http://','https://')): + raise BridgeError('Invalid Balroc backend URL', 500) + request = urllib.request.Request(url+'/api/jellyfin/clients', headers={'Accept':'application/json'}) + try: + with urllib.request.urlopen(request, timeout=12) as response: + data = json.loads(response.read(1000000)) + except (urllib.error.URLError, TimeoutError, ValueError) as exc: + raise BridgeError('Jellyfin client discovery failed: '+str(exc), 502) from exc + if not isinstance(data,dict) or not isinstance(data.get('clients'),list): + raise BridgeError('Balroc did not return a client list', 502) + return data + + +def approve_client(device_id): + '''Approve exactly one active client using Balroc's secured API.''' + if not device_id or len(device_id)>200: + raise BridgeError('Invalid Jellyfin device ID',400) + secret=os.getenv('KRONIC_BALROC_CONTROL_KEY','').strip() + if not secret: + raise BridgeError('Kronic Balroc control key not configured',503) + url=os.getenv('KRONIC_BALROC_URL','http://172.22.1.161:8182').rstrip('/') + payload=json.dumps({'device_id':device_id}).encode() + raw=_post(url+'/api/jellyfin/approve-client',payload, + {'Content-Type':'application/json','X-Balroc-Control-Key':secret},timeout=20) + try: + return json.loads(raw) + except ValueError as exc: + raise BridgeError('Invalid Balroc approval response') from exc diff --git a/borg_chat_gateway.py b/borg_chat_gateway.py new file mode 100644 index 0000000..bc959bf --- /dev/null +++ b/borg_chat_gateway.py @@ -0,0 +1,238 @@ +"""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)(? 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 diff --git a/kronic_chat_manager.py b/kronic_chat_manager.py new file mode 100644 index 0000000..22dbb2f --- /dev/null +++ b/kronic_chat_manager.py @@ -0,0 +1,73 @@ +"""Manage existing Kronic Krusaders FastAPI as a child of Kronic Media. + +No edits to the existing LiveKit Docker configuration. +""" +import os +import signal +import subprocess +import sys +import threading +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parent +CHAT_DIR = ROOT / "kronic-chat" + +class ChatManager: + def __init__(self): + self._stop = threading.Event() + self._thread = None + self._proc = None + + def start(self): + if self._thread and self._thread.is_alive(): + return + self._stop.clear() + self._thread = threading.Thread(target=self._supervise, name="kronic-chat-supervisor", daemon=True) + self._thread.start() + + def _supervise(self): + if not (CHAT_DIR / '.env').exists(): + print('[CHAT] No kronic-chat/.env yet. Chat not started.', flush=True) + return + py = CHAT_DIR / '.venv' / 'bin' / 'python' + python = str(py) if py.is_file() else sys.executable + port = int(os.getenv('KRONIC_CHAT_PORT', '8001')) + env = os.environ.copy() + # Do not let Chat fall back to its historical independent accounts DB. + # Media's resolved path is the single account/room permission source. + from media_accounts import DATABASE_PATH as shared_accounts_path + env['KRONICK_ACCOUNT_DB'] = str(shared_accounts_path) + # Existing server.py calls load_dotenv(), using the chat cwd. + env['PYTHONUNBUFFERED'] = '1' + while not self._stop.is_set(): + command = [python, '-m', 'uvicorn', 'server:app', '--host', '127.0.0.1', '--port', str(port)] + try: + self._proc = subprocess.Popen(command, cwd=str(CHAT_DIR), env=env, + start_new_session=True) + print(f'[CHAT] Started PID {self._proc.pid} on 127.0.0.1:{port}', flush=True) + code = self._proc.wait() + self._proc = None + if not self._stop.is_set(): + print(f'[CHAT] Exited with {code}; retrying in 5 seconds', flush=True) + self._stop.wait(5) + except Exception as exc: + print(f'[CHAT] Start error: {exc!r}', flush=True) + self._stop.wait(5) + + def stop(self): + self._stop.set() + proc = self._proc + if proc is not None and proc.poll() is None: + try: + os.killpg(proc.pid, signal.SIGTERM) + proc.wait(timeout=8) + except subprocess.TimeoutExpired: + os.killpg(proc.pid, signal.SIGKILL) + proc.wait(timeout=5) + except ProcessLookupError: + pass + if self._thread and self._thread.is_alive(): + self._thread.join(timeout=10) + +chat_manager = ChatManager()