Upload files to "kronic-chat"
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Kronic Krusaders Admin</title><link rel="stylesheet" href="/css/admin.css?v=1"><script src="/js/admin.js?v=1" defer></script></head><body><header><div><strong>Kronic Krusaders</strong><span> ADMIN</span></div><div><a href="/app">Open Chat</a><button id="logoutBtn">Logout</button></div></header><main>
|
||||
<section><h2>Pending users</h2><div id="pendingUsers"></div></section>
|
||||
<section><h2>Users</h2><div id="users"></div></section>
|
||||
<section><h2>Groups</h2><form id="groupForm" class="inline"><input id="groupName" placeholder="Group name" required><input id="groupSlug" placeholder="group-slug" required><input id="groupMaxUsers" type="number" min="1" value="10" title="Max users"><input id="groupMaxRooms" type="number" min="1" value="10" title="Max rooms"><button>Create group</button></form><div id="groups"></div></section>
|
||||
<section><h2>Memberships</h2><form id="memberForm" class="inline"><select id="memberGroup"></select><select id="memberUser"></select><select id="memberRole"><option>member</option><option>moderator</option><option>admin</option><option>owner</option></select><button>Assign / update</button></form><div id="memberships"></div></section>
|
||||
<section><h2>Registration</h2>
|
||||
<p>Automatic approval assigns selected rooms. Invitation-only registration requires a valid room invite. Manual requires your approval.</p>
|
||||
<form id="registrationForm">
|
||||
<label>Signup policy <select id="registrationMode"><option value="manual">Manual approval</option><option value="automatic">Automatic approval</option><option value="invite_only">Invite only</option></select></label>
|
||||
<div id="registrationRooms"></div>
|
||||
<button>Save registration settings</button>
|
||||
</form></section>
|
||||
<section><h2>Room roles</h2>
|
||||
<p>Assign a room owner, administrator, moderator or member. Only the selected room is affected.</p>
|
||||
<form id="roomRoleForm" class="inline">
|
||||
<select id="roomRoleRoom" aria-label="Room"></select>
|
||||
<select id="roomRoleUser" aria-label="Account"></select>
|
||||
<select id="roomRoleRole" aria-label="Room role"><option>member</option><option>moderator</option><option>admin</option><option>owner</option></select>
|
||||
<button>Assign room role</button></form></section>
|
||||
<section><h2>Rooms</h2><form id="roomForm" class="inline"><select id="roomGroup"></select><input id="roomName" placeholder="room-name" required><input id="roomDisplay" placeholder="Display name"><button>Create room</button></form><div id="rooms"></div></section>
|
||||
<div id="status"></div></main></body></html>
|
||||
@@ -0,0 +1,481 @@
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import sqlite3
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Callable, Optional
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException
|
||||
from fastapi.responses import FileResponse
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
router = APIRouter(prefix="/api/helper", tags=["Kronic Helper"])
|
||||
|
||||
_database_path: Optional[Path] = None
|
||||
_modules_dir: Optional[Path] = None
|
||||
_token_ttl_seconds = 90 * 24 * 60 * 60
|
||||
_authenticate_account: Optional[Callable[[str, str], Optional[dict]]] = None
|
||||
_helper_token_secret = b""
|
||||
|
||||
|
||||
class HelperAuthRequest(BaseModel):
|
||||
username: str = Field(min_length=1, max_length=128)
|
||||
password: str = Field(min_length=1, max_length=256)
|
||||
device_id: str = Field(min_length=8, max_length=256)
|
||||
device_name: str = Field(default="", max_length=128)
|
||||
platform: str = Field(default="", max_length=64)
|
||||
helper_version: str = Field(default="", max_length=32)
|
||||
|
||||
|
||||
class HelperRevokeRequest(BaseModel):
|
||||
device_id: str = Field(min_length=8, max_length=256)
|
||||
|
||||
|
||||
def configure_helper_api(
|
||||
*,
|
||||
database_path: Path,
|
||||
modules_dir: Path,
|
||||
token_ttl_days: int = 90,
|
||||
authenticate_account: Optional[Callable[[str, str], Optional[dict]]] = None,
|
||||
) -> None:
|
||||
global _database_path
|
||||
global _modules_dir
|
||||
global _token_ttl_seconds
|
||||
global _authenticate_account
|
||||
global _helper_token_secret
|
||||
|
||||
configured_secret = (
|
||||
os.getenv("HELPER_TOKEN_SECRET")
|
||||
or os.getenv("ROOM_OWNER_TOKEN_SECRET")
|
||||
or os.getenv("LIVEKIT_API_SECRET")
|
||||
or ""
|
||||
).strip()
|
||||
|
||||
if not configured_secret:
|
||||
raise RuntimeError(
|
||||
"HELPER_TOKEN_SECRET must be set in .env."
|
||||
)
|
||||
|
||||
_helper_token_secret = configured_secret.encode("utf-8")
|
||||
_database_path = Path(database_path).resolve()
|
||||
_modules_dir = Path(modules_dir).resolve()
|
||||
_modules_dir.mkdir(parents=True, exist_ok=True)
|
||||
_token_ttl_seconds = max(1, int(token_ttl_days)) * 86400
|
||||
_authenticate_account = authenticate_account
|
||||
|
||||
|
||||
def _require_configured() -> None:
|
||||
if _database_path is None or _modules_dir is None:
|
||||
raise RuntimeError("Kronic Helper API has not been configured.")
|
||||
if not _helper_token_secret:
|
||||
raise RuntimeError("Kronic Helper token secret is not configured.")
|
||||
|
||||
|
||||
def _open_database() -> sqlite3.Connection:
|
||||
_require_configured()
|
||||
connection = sqlite3.connect(_database_path, timeout=15)
|
||||
connection.row_factory = sqlite3.Row
|
||||
connection.execute("PRAGMA foreign_keys = ON")
|
||||
connection.execute("PRAGMA busy_timeout = 15000")
|
||||
return connection
|
||||
|
||||
|
||||
def initialize_helper_database() -> None:
|
||||
_require_configured()
|
||||
|
||||
with _open_database() as connection:
|
||||
connection.execute("PRAGMA journal_mode = WAL")
|
||||
connection.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS helper_devices (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
account_id INTEGER NOT NULL,
|
||||
device_id TEXT NOT NULL UNIQUE,
|
||||
device_name TEXT NOT NULL DEFAULT '',
|
||||
platform TEXT NOT NULL DEFAULT '',
|
||||
helper_version TEXT NOT NULL DEFAULT '',
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
created_at INTEGER NOT NULL,
|
||||
last_used_at INTEGER NOT NULL,
|
||||
expires_at INTEGER NOT NULL,
|
||||
revoked_at INTEGER
|
||||
)
|
||||
"""
|
||||
)
|
||||
connection.execute(
|
||||
"""
|
||||
CREATE INDEX IF NOT EXISTS idx_helper_devices_account_id
|
||||
ON helper_devices(account_id)
|
||||
"""
|
||||
)
|
||||
connection.commit()
|
||||
|
||||
|
||||
def _hash_token(token: str) -> str:
|
||||
return hmac.new(
|
||||
_helper_token_secret,
|
||||
token.encode("utf-8"),
|
||||
hashlib.sha256,
|
||||
).hexdigest()
|
||||
|
||||
|
||||
def _extract_bearer(authorization: Optional[str]) -> str:
|
||||
if not authorization:
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail="Kronic Helper authorization is required.",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
scheme, separator, token = authorization.partition(" ")
|
||||
|
||||
if (
|
||||
separator != " "
|
||||
or scheme.lower() != "bearer"
|
||||
or not token.strip()
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail="Use Authorization: Bearer <helper-token>.",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
return token.strip()
|
||||
|
||||
|
||||
def _require_device(authorization: Optional[str]) -> dict:
|
||||
token_hash = _hash_token(_extract_bearer(authorization))
|
||||
now = int(time.time())
|
||||
|
||||
with _open_database() as connection:
|
||||
row = connection.execute(
|
||||
"SELECT * FROM helper_devices WHERE token_hash = ?",
|
||||
(token_hash,),
|
||||
).fetchone()
|
||||
|
||||
if row is None:
|
||||
raise HTTPException(status_code=401, detail="Invalid Helper token.")
|
||||
|
||||
if row["revoked_at"] is not None:
|
||||
raise HTTPException(status_code=401, detail="Helper device is revoked.")
|
||||
|
||||
if int(row["expires_at"]) <= now:
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail="Helper authorization expired. Sign in again.",
|
||||
)
|
||||
|
||||
connection.execute(
|
||||
"UPDATE helper_devices SET last_used_at = ? WHERE id = ?",
|
||||
(now, row["id"]),
|
||||
)
|
||||
connection.commit()
|
||||
|
||||
return dict(row)
|
||||
|
||||
|
||||
def _read_manifest(module_dir: Path) -> Optional[dict]:
|
||||
path = module_dir / "manifest.json"
|
||||
|
||||
if not path.is_file():
|
||||
return None
|
||||
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
return None
|
||||
|
||||
if not all(data.get(key) for key in ("id", "name", "version")):
|
||||
return None
|
||||
|
||||
package = str(data.get("package", "")).strip()
|
||||
package_path = module_dir / package if package else None
|
||||
|
||||
if package and not package_path.is_file():
|
||||
package = ""
|
||||
package_path = None
|
||||
|
||||
return {
|
||||
"id": str(data["id"]),
|
||||
"name": str(data["name"]),
|
||||
"version": str(data["version"]),
|
||||
"description": str(data.get("description", "")),
|
||||
"platforms": data.get("platforms", []),
|
||||
"package": package,
|
||||
"sha256": str(data.get("sha256", "")),
|
||||
"size": package_path.stat().st_size if package_path else 0,
|
||||
"requires_helper": str(data.get("requires_helper", "")),
|
||||
"capabilities": data.get("capabilities", {}),
|
||||
}
|
||||
|
||||
|
||||
def _find_module(module_id: str):
|
||||
module_id = str(module_id or "").strip()
|
||||
|
||||
if (
|
||||
not module_id
|
||||
or "/" in module_id
|
||||
or "\\" in module_id
|
||||
or ".." in module_id
|
||||
):
|
||||
raise HTTPException(status_code=400, detail="Invalid module ID.")
|
||||
|
||||
module_dir = _modules_dir / module_id
|
||||
manifest = _read_manifest(module_dir) if module_dir.is_dir() else None
|
||||
|
||||
if not manifest:
|
||||
raise HTTPException(status_code=404, detail="Module not found.")
|
||||
|
||||
return module_dir, manifest
|
||||
|
||||
|
||||
def _catalogue() -> list[dict]:
|
||||
_require_configured()
|
||||
|
||||
modules = []
|
||||
|
||||
for module_dir in sorted(_modules_dir.iterdir()):
|
||||
if not module_dir.is_dir():
|
||||
continue
|
||||
|
||||
manifest = _read_manifest(module_dir)
|
||||
if manifest:
|
||||
modules.append(manifest)
|
||||
|
||||
return modules
|
||||
|
||||
|
||||
@router.get("/status")
|
||||
async def helper_status():
|
||||
return {
|
||||
"ok": True,
|
||||
"service": "kronic-helper-api",
|
||||
"auth": "device-token",
|
||||
}
|
||||
|
||||
|
||||
@router.post("/auth")
|
||||
async def helper_auth(request: HelperAuthRequest):
|
||||
if _authenticate_account is None:
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail="Helper account authentication is unavailable.",
|
||||
)
|
||||
|
||||
account = _authenticate_account(
|
||||
request.username.strip(),
|
||||
request.password,
|
||||
)
|
||||
|
||||
if not account:
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail="Incorrect username/email or password, or account is not active.",
|
||||
)
|
||||
|
||||
account_id = int(account["id"])
|
||||
username = str(account.get("username", request.username))
|
||||
display_name = username
|
||||
|
||||
now = int(time.time())
|
||||
expires_at = now + _token_ttl_seconds
|
||||
raw_token = secrets.token_urlsafe(48)
|
||||
token_hash = _hash_token(raw_token)
|
||||
|
||||
with _open_database() as connection:
|
||||
existing = connection.execute(
|
||||
"SELECT id FROM helper_devices WHERE device_id = ?",
|
||||
(request.device_id,),
|
||||
).fetchone()
|
||||
|
||||
if existing:
|
||||
connection.execute(
|
||||
"""
|
||||
UPDATE helper_devices
|
||||
SET
|
||||
account_id = ?,
|
||||
device_name = ?,
|
||||
platform = ?,
|
||||
helper_version = ?,
|
||||
token_hash = ?,
|
||||
last_used_at = ?,
|
||||
expires_at = ?,
|
||||
revoked_at = NULL
|
||||
WHERE device_id = ?
|
||||
""",
|
||||
(
|
||||
account_id,
|
||||
request.device_name.strip(),
|
||||
request.platform.strip(),
|
||||
request.helper_version.strip(),
|
||||
token_hash,
|
||||
now,
|
||||
expires_at,
|
||||
request.device_id,
|
||||
),
|
||||
)
|
||||
else:
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO helper_devices (
|
||||
account_id,
|
||||
device_id,
|
||||
device_name,
|
||||
platform,
|
||||
helper_version,
|
||||
token_hash,
|
||||
created_at,
|
||||
last_used_at,
|
||||
expires_at,
|
||||
revoked_at
|
||||
)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL)
|
||||
""",
|
||||
(
|
||||
account_id,
|
||||
request.device_id,
|
||||
request.device_name.strip(),
|
||||
request.platform.strip(),
|
||||
request.helper_version.strip(),
|
||||
token_hash,
|
||||
now,
|
||||
now,
|
||||
expires_at,
|
||||
),
|
||||
)
|
||||
|
||||
connection.commit()
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"account_id": account_id,
|
||||
"username": username,
|
||||
"display_name": display_name,
|
||||
"device_id": request.device_id,
|
||||
"device_token": raw_token,
|
||||
"expires_at": expires_at,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/modules")
|
||||
async def helper_modules(
|
||||
authorization: Optional[str] = Header(default=None),
|
||||
):
|
||||
device = _require_device(authorization)
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"device_id": device["device_id"],
|
||||
"modules": _catalogue(),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/modules/{module_id}")
|
||||
async def helper_module(
|
||||
module_id: str,
|
||||
authorization: Optional[str] = Header(default=None),
|
||||
):
|
||||
_require_device(authorization)
|
||||
_module_dir, manifest = _find_module(module_id)
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"module": manifest,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/modules/{module_id}/download")
|
||||
async def helper_module_download(
|
||||
module_id: str,
|
||||
authorization: Optional[str] = Header(default=None),
|
||||
):
|
||||
_require_device(authorization)
|
||||
module_dir, manifest = _find_module(module_id)
|
||||
|
||||
package = manifest["package"]
|
||||
|
||||
if not package:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail="No downloadable package exists for this module.",
|
||||
)
|
||||
|
||||
return FileResponse(
|
||||
module_dir / package,
|
||||
filename=package,
|
||||
media_type="application/octet-stream",
|
||||
)
|
||||
|
||||
|
||||
@router.get("/devices")
|
||||
async def helper_devices(
|
||||
authorization: Optional[str] = Header(default=None),
|
||||
):
|
||||
current = _require_device(authorization)
|
||||
|
||||
with _open_database() as connection:
|
||||
rows = connection.execute(
|
||||
"""
|
||||
SELECT
|
||||
device_id,
|
||||
device_name,
|
||||
platform,
|
||||
helper_version,
|
||||
created_at,
|
||||
last_used_at,
|
||||
expires_at,
|
||||
revoked_at
|
||||
FROM helper_devices
|
||||
WHERE account_id = ?
|
||||
ORDER BY last_used_at DESC
|
||||
""",
|
||||
(current["account_id"],),
|
||||
).fetchall()
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"devices": [dict(row) for row in rows],
|
||||
}
|
||||
|
||||
|
||||
@router.post("/revoke")
|
||||
async def helper_revoke(
|
||||
request: HelperRevokeRequest,
|
||||
authorization: Optional[str] = Header(default=None),
|
||||
):
|
||||
current = _require_device(authorization)
|
||||
now = int(time.time())
|
||||
|
||||
with _open_database() as connection:
|
||||
target = connection.execute(
|
||||
"""
|
||||
SELECT id, account_id
|
||||
FROM helper_devices
|
||||
WHERE device_id = ?
|
||||
""",
|
||||
(request.device_id,),
|
||||
).fetchone()
|
||||
|
||||
if target is None:
|
||||
raise HTTPException(status_code=404, detail="Helper device not found.")
|
||||
|
||||
if int(target["account_id"]) != int(current["account_id"]):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="You may revoke only your own Helper devices.",
|
||||
)
|
||||
|
||||
connection.execute(
|
||||
"UPDATE helper_devices SET revoked_at = ? WHERE id = ?",
|
||||
(now, target["id"]),
|
||||
)
|
||||
connection.commit()
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"device_id": request.device_id,
|
||||
"revoked": True,
|
||||
}
|
||||
+1
File diff suppressed because one or more lines are too long
@@ -0,0 +1,151 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
|
||||
<meta
|
||||
name="viewport"
|
||||
content="width=device-width, initial-scale=1"
|
||||
>
|
||||
|
||||
<title>Kronick Media Browser</title>
|
||||
|
||||
<link
|
||||
rel="stylesheet"
|
||||
href="/css/music-browser.css"
|
||||
>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div
|
||||
id="musicBrowser"
|
||||
class="music-browser"
|
||||
>
|
||||
<div class="music-browser-header">
|
||||
<h3 id="musicBrowserTitle">
|
||||
Media Browser
|
||||
</h3>
|
||||
|
||||
<button
|
||||
id="musicBrowserClose"
|
||||
type="button"
|
||||
aria-label="Close media browser"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
id="nav"
|
||||
class="music-breadcrumb"
|
||||
></div>
|
||||
|
||||
<input
|
||||
id="searchInput"
|
||||
class="music-search"
|
||||
type="search"
|
||||
placeholder="Search videos..."
|
||||
autocomplete="off"
|
||||
>
|
||||
|
||||
<div
|
||||
id="status"
|
||||
class="music-status"
|
||||
></div>
|
||||
|
||||
<div class="music-browser-layout">
|
||||
|
||||
<aside
|
||||
class="
|
||||
media-side-panel
|
||||
history-panel
|
||||
"
|
||||
>
|
||||
<div class="side-panel-header">
|
||||
|
||||
<div>
|
||||
<span class="side-panel-title">
|
||||
History
|
||||
</span>
|
||||
|
||||
<span
|
||||
id="historyCount"
|
||||
class="side-panel-count"
|
||||
>
|
||||
0
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<button
|
||||
id="clearHistoryBtn"
|
||||
type="button"
|
||||
class="side-panel-clear"
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
|
||||
</div>
|
||||
|
||||
<div
|
||||
id="historyList"
|
||||
class="side-panel-list"
|
||||
></div>
|
||||
</aside>
|
||||
|
||||
<main class="browser-main-column">
|
||||
<div id="list"></div>
|
||||
</main>
|
||||
|
||||
<aside
|
||||
class="
|
||||
media-side-panel
|
||||
queue-panel
|
||||
"
|
||||
>
|
||||
<div class="side-panel-header">
|
||||
|
||||
<div>
|
||||
<span class="side-panel-title">
|
||||
Queue
|
||||
</span>
|
||||
|
||||
<span
|
||||
id="queueCount"
|
||||
class="side-panel-count"
|
||||
>
|
||||
0
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<button
|
||||
id="clearQueueBtn"
|
||||
type="button"
|
||||
class="side-panel-clear"
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
|
||||
</div>
|
||||
|
||||
<button
|
||||
id="playNextBtn"
|
||||
type="button"
|
||||
class="queue-play-next"
|
||||
disabled
|
||||
>
|
||||
▶ Play Next
|
||||
</button>
|
||||
|
||||
<div
|
||||
id="queueList"
|
||||
class="side-panel-list"
|
||||
></div>
|
||||
|
||||
</aside>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="/js/music-browser.js?v=20260918-3"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,7 @@
|
||||
fastapi
|
||||
uvicorn
|
||||
python-dotenv
|
||||
argon2-cffi
|
||||
livekit-api
|
||||
python-multipart
|
||||
requests
|
||||
Reference in New Issue
Block a user