Source code for fleetmesh_protocols.textile.fiber_routes

"""`/api/fibers*` HTTP routing for `StandaloneFiberStore` (`node.protocols.textile.fiber_routes`).

- `GET  /api/fibers`                    the caller's own fiber manifests
- `GET  /api/fibers/<root>`             bytes as an opaque download (`?format=json` for base64 + manifest)
- `GET  /api/fibers/<root>/manifest`    manifest only
- `GET  /api/fibers/interactions?target=<strand_id>`  public interaction counts by kind
- `POST /api/fibers`                    `{data_b64, kind, mime_type?, visibility?, target_strand_id?}`
- `POST /api/fibers/visibility`         `{fiber_root, visibility}` on the caller's claim
- `POST /api/fibers/release`            `{fiber_root}` drops the caller's claim

Unreadable and missing fibers both answer 404.
"""
from __future__ import annotations

import base64
import re
import urllib.parse
from typing import Any, Dict, Mapping, Optional, Tuple

from fleetmesh_core.textile.bao import bao_root_1024
from fleetmesh_core.textile.principal import MeshAccessError, Principal, decode_b64
from .fiber_store import MAX_FIBER_BYTES

HttpResult = Tuple[int, Any, str, Dict[str, str]]
JSON_CT = "application/json; charset=utf-8"

# Served with their own type; anything else (HTML, JSON, SVG...) goes out as an opaque download.
_SAFE_BINARY_MIME = {
    "application/octet-stream",
    "application/wasm",
    "application/x-gameboy-rom",
    "application/x-gameboy-color-rom",
    "audio/mpeg",
    "audio/ogg",
    "audio/flac",
    "audio/wav",
    "video/mp4",
    "video/webm",
    "image/png",
    "image/jpeg",
    "image/webp",
    "image/gif",
    "text/vtt",
}
_ROOT_RE = re.compile(r"^[0-9a-f]{64}$")
_RANGE_HEADER_RE = re.compile(r"^bytes=(\d*)-(\d*)$")


[docs]def binary_http_response( raw: bytes, *, bao_root: str, sha256_hex: str, mime_type: str, public: bool, filename: str, as_json: bool, json_extra: Optional[Mapping[str, Any]] = None, ) -> HttpResult: """Serve stored bytes so they can never render as a page on the app's origin.""" cache = "public, max-age=3600, immutable" if public else "private, no-store" hdrs = { "X-Bao-Tree-Root": bao_root, "Cache-Control": cache, "X-Content-Type-Options": "nosniff", "Accept-Ranges": "bytes", } mime = str(mime_type or "").strip().lower() if as_json: return ( 200, { "ok": True, **dict(json_extra or {}), "bao_root": bao_root, "sha256_hex": sha256_hex, "mime_type": mime or "application/octet-stream", "size_bytes": len(raw), "data_b64": base64.b64encode(raw).decode("ascii"), }, JSON_CT, hdrs, ) fname = re.sub(r"[^A-Za-z0-9._-]", "_", filename or "fiber.bin")[:120] hdrs["Content-Disposition"] = f'attachment; filename="{fname}"' hdrs["Content-Security-Policy"] = "default-src 'none'; sandbox" return 200, raw, (mime if mime in _SAFE_BINARY_MIME else "application/octet-stream"), hdrs
[docs]def is_fiber_route(route: str) -> bool: return route == "/api/fibers" or route.startswith("/api/fibers/")
def _not_found(root: str) -> HttpResult: return 404, {"ok": False, "error": "fiber_not_found", "fiber_root": root}, JSON_CT, {} def _parse_range(rng: str, total: int) -> Optional[Tuple[int, int]]: """The inclusive byte span a single `bytes=` range names within `total`, or `None` if unsatisfiable.""" m = _RANGE_HEADER_RE.match(rng) if not m or total <= 0 or (m.group(1) == "" and m.group(2) == ""): return None if m.group(1) == "": start, end = max(0, total - int(m.group(2))), total - 1 else: start, end = int(m.group(1)), int(m.group(2)) if m.group(2) else total - 1 return (start, min(end, total - 1)) if start < total and start <= end else None def _serve_range(store: Any, root: str, manifest: Mapping[str, Any], rng: str, *, head: bool) -> HttpResult: """HEAD and `Range` reads. Slices come from `get_blob_slice_by_root`, which both fiber stores implement, so a range never loads the whole fiber. `X-Bao-Range-Root` is the slice's own 1024-byte-leaf Bao root, sent only with slice bytes of at most 1 MiB (one chunk); clients verify the slice against it. Larger slices and HEAD carry none. """ total = int(manifest.get("byte_length") or 0) span = _parse_range(rng, total) if rng else (0, total - 1) if span is None: return ( 416, {"ok": False, "error": "range_not_satisfiable"}, JSON_CT, {"Content-Range": f"bytes */{total}", "Accept-Ranges": "bytes"}, ) start, end = span chunk = b"" if head else store.get_blob_slice_by_root(root, start, end - start + 1) if chunk is None: return _not_found(root) _st, body, ct, hdrs = binary_http_response( chunk, bao_root=root, sha256_hex=manifest["sha256_hex"], mime_type=manifest.get("mime_type") or "", public=manifest.get("visibility") == "public", filename=f"{root[:16]}.bin", as_json=False, ) if not rng: hdrs["Content-Length"] = str(total) return 200, b"", ct, hdrs hdrs["Content-Range"] = f"bytes {start}-{end}/{total}" if head: hdrs["Content-Length"] = str(end - start + 1) elif len(chunk) <= 1024 * 1024: hdrs["X-Bao-Range-Root"] = bao_root_1024(chunk)[0] return 206, body, ct, hdrs
[docs]def handle_fiber_http( store: Any, method: str, route: str, query: Any = "", body: Optional[Mapping[str, Any]] = None, principal: Principal = None, *, range_header: str = "", ) -> Optional[HttpResult]: """Route `/api/fibers*`. `principal` must come from the server's own session resolution.""" qp = query if isinstance(query, Mapping) else urllib.parse.parse_qs(str(query or "")) try: if method in ("GET", "HEAD"): if route == "/api/fibers": if not principal: raise MeshAccessError(401, "authentication_required") return 200, {"ok": True, "fibers": store.list_own(principal)}, JSON_CT, {"Cache-Control": "private, no-store"} if route == "/api/fibers/interactions": target = (qp.get("target", [""])[0] or "").strip() if not target: raise MeshAccessError(400, "target_required") return ( 200, {"ok": True, "target": target, "counts": store.interaction_counts(target)}, JSON_CT, {"Cache-Control": "public, max-age=15"}, ) parts = [p for p in route[len("/api/fibers/") :].split("/") if p] if not parts or len(parts) > 2 or not _ROOT_RE.match(parts[0]): return None root = parts[0] if len(parts) == 2: if parts[1] != "manifest": return None manifest = store.manifest(root, principal) return ( (200, {"ok": True, "fiber": manifest}, JSON_CT, {"Cache-Control": "private, no-store"}) if manifest else _not_found(root) ) as_json = (qp.get("format", [""])[0] or "").strip().lower() == "json" rng = str(range_header or "").strip() if (method == "HEAD" or rng) and not as_json: manifest = store.manifest(root, principal) return _serve_range(store, root, manifest, rng, head=method == "HEAD") if manifest else _not_found(root) found = store.get(root, principal) if found is None: return _not_found(root) raw, manifest = found return binary_http_response( raw, bao_root=root, sha256_hex=manifest["sha256_hex"], mime_type=manifest.get("mime_type") or "", public=manifest.get("visibility") == "public", filename=f"{root[:16]}.bin", as_json=as_json, json_extra={"fiber": manifest}, ) if method != "POST" or not is_fiber_route(route): return None payload: Mapping[str, Any] = body or {} if route in ("/api/fibers", "/api/fibers/put"): raw = decode_b64(payload.get("data_b64"), MAX_FIBER_BYTES) if raw is None: raise MeshAccessError(400, "data_b64_required") manifest = store.put( raw, principal, kind=str(payload.get("kind") or ""), mime_type=str(payload.get("mime_type") or ""), visibility=str(payload.get("visibility") or "vault_only"), target_strand_id=str(payload.get("target_strand_id") or ""), ) return 200, {"ok": True, "fiber": manifest}, JSON_CT, {} if route == "/api/fibers/visibility": manifest = store.set_visibility( str(payload.get("fiber_root") or ""), principal, str(payload.get("visibility") or "") ) return 200, {"ok": True, "fiber": manifest}, JSON_CT, {} if route == "/api/fibers/release": root = str(payload.get("fiber_root") or "") released = store.release(root, principal) return (200 if released else 404), {"ok": released, "fiber_root": root}, JSON_CT, {} return None except MeshAccessError as exc: return exc.status, {"ok": False, "error": exc.error}, JSON_CT, {}