129 行
4.4 KiB
Python
129 行
4.4 KiB
Python
"""Signed media URL helpers."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import binascii
|
|
import hashlib
|
|
import hmac
|
|
import json
|
|
import mimetypes
|
|
import os
|
|
import time
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
from backend.dto.common import ApiError, ErrorCode
|
|
from core.storage import VfsStorage
|
|
|
|
|
|
DEFAULT_MEDIA_TTL_SECONDS = 300
|
|
MEDIA_FETCH_PATH = "/api/v1/plugins/extensions/astrbot_plugin_imagestudio/media/fetch"
|
|
|
|
|
|
class MediaProxy:
|
|
def __init__(
|
|
self,
|
|
storage: VfsStorage | None = None,
|
|
*,
|
|
signing_secret: str | None = None,
|
|
ttl_seconds: int = DEFAULT_MEDIA_TTL_SECONDS,
|
|
):
|
|
self.storage = storage or VfsStorage()
|
|
self.signing_secret = signing_secret or os.environ.get(
|
|
"IMAGESTUDIO_MEDIA_SIGNING_SECRET",
|
|
"imagestudio-dev-media-signing-secret",
|
|
)
|
|
self.ttl_seconds = ttl_seconds
|
|
|
|
def sign(self, uri: str) -> dict[str, Any]:
|
|
path = self.storage.ensure_file(uri)
|
|
expires_at = int(time.time()) + self.ttl_seconds
|
|
payload = {"uri": uri, "expires_at": expires_at}
|
|
token = self._encode(payload)
|
|
return {
|
|
"uri": uri,
|
|
"token": token,
|
|
"expires_at": expires_at,
|
|
"url": f"{MEDIA_FETCH_PATH}?token={token}",
|
|
"content_type": _guess_content_type(path),
|
|
"size_bytes": path.stat().st_size,
|
|
}
|
|
|
|
def fetch_metadata(self, token: str) -> dict[str, Any]:
|
|
path, metadata = self._resolve_token(token)
|
|
return metadata
|
|
|
|
def fetch_payload(self, token: str) -> dict[str, Any]:
|
|
path, metadata = self._resolve_token(token)
|
|
return {
|
|
**metadata,
|
|
"filename": path.name,
|
|
"cache_control": "private, max-age=300",
|
|
"body_base64": _b64encode(path.read_bytes()),
|
|
}
|
|
|
|
def _resolve_token(self, token: str) -> tuple[Path, dict[str, Any]]:
|
|
payload = self._decode(token)
|
|
uri = str(payload.get("uri") or "")
|
|
expires_at = int(payload.get("expires_at") or 0)
|
|
if int(time.time()) > expires_at:
|
|
raise ApiError(ErrorCode.FORBIDDEN, "media token expired", {"expires_at": expires_at})
|
|
path = self.storage.ensure_file(uri)
|
|
return path, {
|
|
"uri": uri,
|
|
"expires_at": expires_at,
|
|
"content_type": _guess_content_type(path),
|
|
"size_bytes": path.stat().st_size,
|
|
}
|
|
|
|
def _encode(self, payload: dict[str, Any]) -> str:
|
|
payload_bytes = json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8")
|
|
payload_part = _b64encode(payload_bytes)
|
|
signature = hmac.new(
|
|
self.signing_secret.encode("utf-8"),
|
|
payload_part.encode("ascii"),
|
|
hashlib.sha256,
|
|
).digest()
|
|
return f"{payload_part}.{_b64encode(signature)}"
|
|
|
|
def _decode(self, token: str) -> dict[str, Any]:
|
|
try:
|
|
payload_part, signature_part = token.split(".", 1)
|
|
except ValueError as exc:
|
|
raise ApiError(ErrorCode.FORBIDDEN, "invalid media token") from exc
|
|
expected = hmac.new(
|
|
self.signing_secret.encode("utf-8"),
|
|
payload_part.encode("ascii"),
|
|
hashlib.sha256,
|
|
).digest()
|
|
actual = _safe_b64decode(signature_part)
|
|
if not hmac.compare_digest(expected, actual):
|
|
raise ApiError(ErrorCode.FORBIDDEN, "invalid media token signature")
|
|
try:
|
|
payload = json.loads(_safe_b64decode(payload_part).decode("utf-8"))
|
|
except (json.JSONDecodeError, UnicodeDecodeError) as exc:
|
|
raise ApiError(ErrorCode.FORBIDDEN, "invalid media token payload") from exc
|
|
if not isinstance(payload, dict):
|
|
raise ApiError(ErrorCode.FORBIDDEN, "invalid media token payload")
|
|
return payload
|
|
|
|
|
|
def _guess_content_type(path: Path) -> str:
|
|
return mimetypes.guess_type(path.name)[0] or "application/octet-stream"
|
|
|
|
|
|
def _b64encode(value: bytes) -> str:
|
|
return base64.urlsafe_b64encode(value).decode("ascii").rstrip("=")
|
|
|
|
|
|
def _b64decode(value: str) -> bytes:
|
|
padding = "=" * (-len(value) % 4)
|
|
return base64.urlsafe_b64decode(value + padding)
|
|
|
|
|
|
def _safe_b64decode(value: str) -> bytes:
|
|
try:
|
|
return _b64decode(value)
|
|
except (binascii.Error, ValueError) as exc:
|
|
raise ApiError(ErrorCode.FORBIDDEN, "invalid media token encoding") from exc
|