Upload files to "kronic-chat"
This commit is contained in:
@@ -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,
|
||||
}
|
||||
Reference in New Issue
Block a user