Skip to content

Open-source download manager & offline media toolbox for YouTube, music, social media, learning platforms & 1,800+ sites. Built with Tauri 2.0, Rust & Svelte.

40.8 KB
Raw Blame
//! Localhost HTTP bridge between the browser extension and the desktop app.
//!
//! Replaces the previous Chrome native-messaging path, which required
//! hard-coding extension IDs in an OS-installed manifest. This bridge listens
//! on `127.0.0.1:<port>` and authenticates extension requests with a single
//! random token that the user pairs once via the app's settings UI.
//!
//! The token is regenerated by hand from the settings (or by deleting it from
//! `settings.json`); the port is picked at first launch from a small range
//! and persisted so the extension always knows where to connect.
//!
//! Endpoints:
//!
//! * `GET  /v1/health`  — unauthenticated; returns `{ ok, version }` so the
//!                         extension can detect that the app is running.
//! * `POST /v1/enqueue` — authenticated; same payload as the legacy native
//!                         host accepted (`ExtensionPayload`). Validates the
//!                         URL, writes cookies + metadata to disk, then queues
//!                         the URL through `external_url::handle_external_url`.
//! * `GET  /media/{t}`  — unauthenticated by design; streams one file the app
//!   itself granted via `media_stream_url` (unguessable, expiring token).
//!   This is how the webview plays local video/audio: WebKitGTK's media
//!   loader bypasses the custom asset scheme entirely, so it needs a real
//!   HTTP endpoint with Range support.

use std::collections::HashMap;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicI64, AtomicU16, Ordering};
use std::sync::{Arc, Mutex, OnceLock, RwLock};

static ACTIVE_TOKEN: RwLock<Option<String>> = RwLock::new(None);

pub fn update_token(new_token: &str) {
    if let Ok(mut lock) = ACTIVE_TOKEN.write() {
        *lock = Some(new_token.to_string());
    }
}

pub fn active_token() -> Option<String> {
    ACTIVE_TOKEN.read().ok().and_then(|l| l.clone())
}

use axum::{
    body::Body,
    extract::{DefaultBodyLimit, Path as AxumPath, State},
    http::{HeaderMap, HeaderName, Method, StatusCode},
    response::{IntoResponse, Response},
    routing::{get, post},
    Json, Router,
};
use base64::Engine;
use serde::{Deserialize, Serialize};
use socket2::{Domain, Protocol, Socket, Type};
use tauri::{AppHandle, Emitter};
use tokio::io::{AsyncReadExt, AsyncSeekExt};
use tokio::net::TcpListener;
use tokio_util::io::ReaderStream;
use tower_http::cors::{Any, CorsLayer};

use crate::extension_storage::{
    cookie_limit, write_extension_metadata, ExtensionCookie, ExtensionPayload,
};
use crate::storage::config;
use tauri::Manager;

/// Range of ports we'll try when picking a fresh `bridge.port`. Chosen above
/// the most common dev-server / Vite ranges so collisions are rare.
const PORT_RANGE: std::ops::Range<u16> = 47720..47730;

/// The port the bridge actually bound this run; `0` until [`spawn`] gets that
/// far. Media URLs handed to the webview are built from it.
static BOUND_PORT: AtomicU16 = AtomicU16::new(0);

/// One playback capability per file: unguessable token → (path, deadline).
///
/// WHY this exists: WebKitGTK's media loader never consults Tauri's registered
/// asset scheme — the GStreamer source element performs a real HTTP request,
/// so a `convertFileSrc` URL dies before the first byte and the player spins
/// forever. Media therefore streams from this bridge instead. The grant, not
/// the path, is the capability: only files the app itself handed a token for
/// can be read, only from localhost, and only until the deadline — a webpage
/// probing the port finds nothing to name.
static MEDIA_GRANTS: OnceLock<Mutex<HashMap<String, MediaGrant>>> = OnceLock::new();

struct MediaGrant {
    path: PathBuf,
    expires_ms: i64,
}

/// Grants outlive a single request on purpose — the player re-requests the
/// same URL for every seek and every quality probe — but not forever.
const MEDIA_GRANT_TTL_MS: i64 = 6 * 60 * 60 * 1000;

/// Upper bound so a long session with hundreds of opened files cannot grow
/// the map without limit; the soonest-to-expire grant is dropped first.
const MEDIA_GRANT_CAP: usize = 512;

fn media_grants() -> &'static Mutex<HashMap<String, MediaGrant>> {
    MEDIA_GRANTS.get_or_init(|| Mutex::new(HashMap::new()))
}

fn media_grants_prune(map: &mut HashMap<String, MediaGrant>) {
    let now = now_ms();
    map.retain(|_, grant| grant.expires_ms > now);
    while map.len() >= MEDIA_GRANT_CAP {
        let victim = map
            .iter()
            .min_by_key(|(_, grant)| grant.expires_ms)
            .map(|(token, _)| token.clone());
        match victim {
            Some(token) => {
                map.remove(&token);
            }
            None => break,
        }
    }
}

fn is_media_extension(path: &Path) -> bool {
    path.extension()
        .and_then(|ext| ext.to_str())
        .map(|ext| {
            matches!(
                ext.to_ascii_lowercase().as_str(),
                "mp4"
                    | "m4v"
                    | "mov"
                    | "mkv"
                    | "webm"
                    | "mp3"
                    | "m4a"
                    | "flac"
                    | "ogg"
                    | "opus"
                    | "wav"
                    | "vtt"
                    | "srt"
                    | "aac"
            )
        })
        .unwrap_or(false)
}

/// Mints a playback URL for one local media file, for [`media_stream_url`].
fn mint_media_grant(path: &str) -> Result<String, String> {
    let p = Path::new(path);
    if !p.is_file() {
        return Err(format!("media: not a file: {path}"));
    }
    if !is_media_extension(p) {
        return Err("media: unauthorized or unsupported file type".to_string());
    }
    let canonical = p
        .canonicalize()
        .map_err(|e| format!("media: invalid path: {e}"))?;
    let port = BOUND_PORT.load(Ordering::SeqCst);
    if port == 0 {
        return Err("media: the local bridge is not running".to_string());
    }
    let token = generate_token();
    let mut map = media_grants()
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner());
    media_grants_prune(&mut map);
    map.insert(
        token.clone(),
        MediaGrant {
            path: canonical,
            expires_ms: now_ms() + MEDIA_GRANT_TTL_MS,
        },
    );
    Ok(format!("http://127.0.0.1:{port}/media/{token}"))
}

/// Looks a token up for [`media_stream`], dropping it when expired.
fn media_grant_lookup(token: &str) -> Option<MediaGrant> {
    let mut map = media_grants()
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner());
    let grant = map.get(token)?;
    if grant.expires_ms <= now_ms() {
        map.remove(token);
        return None;
    }
    Some(MediaGrant {
        path: grant.path.clone(),
        expires_ms: grant.expires_ms,
    })
}

/// The Tauri command the player calls instead of `convertFileSrc`. Sync on
/// purpose: it only stats the file and mints a token, and keeping it off the
/// async runtime means it can never trip the nested-runtime class of bugs.
#[tauri::command]
pub fn media_stream_url(path: String) -> Result<String, String> {
    mint_media_grant(&path)
}

/// MIME types the player asks this bridge for. `typefind` sniffs the bytes
/// anyway; the header just stops WebKit from guessing a container wrong.
fn media_mime(path: &Path) -> &'static str {
    match path
        .extension()
        .and_then(|ext| ext.to_str())
        .map(|ext| ext.to_ascii_lowercase())
        .as_deref()
    {
        Some("mp4" | "m4v" | "mov") => "video/mp4",
        Some("mkv") => "video/x-matroska",
        Some("webm") => "video/webm",
        Some("mp3") => "audio/mpeg",
        Some("m4a") => "audio/mp4",
        Some("flac") => "audio/flac",
        Some("ogg" | "opus") => "audio/ogg",
        Some("wav") => "audio/wav",
        Some("vtt") => "text/vtt",
        Some("srt") => "text/plain",
        _ => "application/octet-stream",
    }
}

/// Streams one granted file with HTTP Range support. WebKit requests
/// `bytes=0-` for preload, then arbitrary windows for every seek; answering
/// 200-with-full-body to those breaks the pipeline, so a real 206 is the
/// contract here, same as the asset protocol serves on the other platforms.
async fn media_stream(AxumPath(token): AxumPath<String>, headers: HeaderMap) -> Response {
    let Some(grant) = media_grant_lookup(&token) else {
        return StatusCode::NOT_FOUND.into_response();
    };
    let Ok(mut file) = tokio::fs::File::open(&grant.path).await else {
        return StatusCode::NOT_FOUND.into_response();
    };
    let total = file
        .metadata()
        .await
        .map(|meta| meta.len())
        .unwrap_or_default();
    let mime = media_mime(&grant.path);

    let range = headers
        .get("range")
        .and_then(|value| value.to_str().ok())
        .map(parse_byte_range);
    let (status, start, end) = match range {
        Some(Ok(spec)) => {
            let (start, end) = match spec {
                ByteRange::From(start, Some(end)) => (start, end),
                ByteRange::From(start, None) => (start, total.saturating_sub(1)),
                ByteRange::LastBytes(suffix) => {
                    (total.saturating_sub(suffix), total.saturating_sub(1))
                }
            };
            if start >= total {
                (StatusCode::RANGE_NOT_SATISFIABLE, 0, 0)
            } else {
                (
                    StatusCode::PARTIAL_CONTENT,
                    start,
                    end.min(total.saturating_sub(1)),
                )
            }
        }
        _ => (StatusCode::OK, 0, total.saturating_sub(1)),
    };
    if status == StatusCode::RANGE_NOT_SATISFIABLE {
        let mut headers = HeaderMap::new();
        headers.insert(
            HeaderName::from_static("content-range"),
            format!("bytes */{total}").parse().expect("valid header"),
        );
        return (status, headers, Body::empty()).into_response();
    }
    let length = end - start + 1;

    if file.seek(std::io::SeekFrom::Start(start)).await.is_err() {
        return StatusCode::INTERNAL_SERVER_ERROR.into_response();
    }
    let stream = ReaderStream::new(file.take(length));

    let mut response_headers = HeaderMap::new();
    response_headers.insert(
        HeaderName::from_static("content-type"),
        mime.parse().expect("valid header"),
    );
    response_headers.insert(
        HeaderName::from_static("content-length"),
        length.to_string().parse().expect("valid header"),
    );
    response_headers.insert(
        HeaderName::from_static("accept-ranges"),
        "bytes".parse().expect("valid header"),
    );
    if status == StatusCode::PARTIAL_CONTENT {
        response_headers.insert(
            HeaderName::from_static("content-range"),
            format!("bytes {start}-{end}/{total}")
                .parse()
                .expect("valid header"),
        );
    }

    (status, response_headers, Body::from_stream(stream)).into_response()
}

/// One parsed `Range` header. Multi-range requests are refused (nobody sends
/// them for media) by parsing to `Err(())`, which answers 416.
enum ByteRange {
    From(u64, Option<u64>),
    LastBytes(u64),
}

/// `bytes=start-end`, `bytes=start-` or `bytes=-suffix`.
fn parse_byte_range(raw: &str) -> Result<ByteRange, ()> {
    let spec = raw.strip_prefix("bytes=").ok_or(())?;
    let spec = spec.split(',').next().ok_or(())?.trim();
    let (start_str, end_str) = spec.split_once('-').ok_or(())?;
    if start_str.is_empty() {
        let suffix: u64 = end_str.trim().parse().map_err(|_| ())?;
        return Ok(ByteRange::LastBytes(suffix));
    }
    let start: u64 = start_str.trim().parse().map_err(|_| ())?;
    let end = if end_str.trim().is_empty() {
        None
    } else {
        Some(end_str.trim().parse::<u64>().map_err(|_| ())?)
    };
    if end.is_some_and(|end| end < start) {
        return Err(());
    }
    Ok(ByteRange::From(start, end))
}

#[derive(Clone)]
pub struct BridgeState {
    pub app: AppHandle,
    /// Authoritative copy of the bearer token, kept in `Arc` so cloning the
    /// state for each handler doesn't allocate, and so reading it is lock-free.
    pub token: Arc<String>,
}

#[derive(Debug, Serialize)]
struct HealthResponse {
    ok: bool,
    version: &'static str,
}

#[derive(Debug, Serialize)]
struct EnqueueResponse {
    ok: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    code: Option<&'static str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    message: Option<String>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct EnqueueRequest {
    #[serde(flatten)]
    payload: ExtensionPayload,
    #[serde(default)]
    protocol_version: Option<u32>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct CookiesRequest {
    #[serde(default)]
    cookies: Vec<ExtensionCookie>,
    #[serde(default)]
    protocol_version: Option<u32>,
    #[serde(default)]
    source_url: Option<String>,
    #[serde(default)]
    page_title: Option<String>,
    #[serde(default)]
    alias: Option<String>,
}

const HOST_MAX_PROTOCOL_VERSION: u32 = 1;

/// Body cap for `/v1/enqueue`, kept a little above the extension's own 4 MiB
/// ceiling on the manifest text so the payload's metadata and cookies fit too.
const ENQUEUE_BODY_LIMIT: usize = 8 * 1024 * 1024;

/// Generate a random bearer token (32 bytes, URL-safe base64, no padding).
pub fn generate_token() -> String {
    let mut buf = [0u8; 32];
    rand::Rng::fill_bytes(&mut rand::rng(), &mut buf);
    base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(buf)
}

/// Bind a TCP listener on `127.0.0.1:port` with `SO_REUSEADDR` enabled so
/// the port can be re-bound immediately across app restarts (the previous
/// socket stays in `TIME_WAIT` for ~60 s otherwise, which would otherwise
/// kick us off our persisted port and force re-pairing).
fn bind_with_reuse(port: u16) -> std::io::Result<TcpListener> {
    let addr: SocketAddr = ([127, 0, 0, 1], port).into();
    let socket = Socket::new(Domain::IPV4, Type::STREAM, Some(Protocol::TCP))?;
    socket.set_reuse_address(true)?;
    socket.set_nonblocking(true)?;
    socket.bind(&addr.into())?;
    socket.listen(128)?;
    let std_listener: std::net::TcpListener = socket.into();
    TcpListener::from_std(std_listener)
}

/// Try to bind a free TCP listener — first the persisted port, then the
/// preferred range, finally `0` (OS-picked) as last resort.
async fn bind_listener(preferred: u16) -> std::io::Result<(u16, TcpListener)> {
    if preferred != 0 {
        if let Ok(listener) = bind_with_reuse(preferred) {
            return Ok((preferred, listener));
        }
    }

    for port in PORT_RANGE {
        if let Ok(listener) = bind_with_reuse(port) {
            return Ok((port, listener));
        }
    }

    let listener = bind_with_reuse(0)?;
    let port = listener.local_addr()?.port();
    Ok((port, listener))
}

/// Ensure `settings.bridge.{token,port}` are populated and persisted.
/// Returns the resolved (token, port) pair to use for this run.
fn ensure_bridge_settings(app: &AppHandle, bound_port: u16) -> anyhow::Result<(String, u16)> {
    let mut settings = config::load_settings(app);
    let mut dirty = false;

    if settings.bridge.token.trim().is_empty() {
        settings.bridge.token = generate_token();
        dirty = true;
    }
    if settings.bridge.port != bound_port {
        settings.bridge.port = bound_port;
        dirty = true;
    }

    if dirty {
        config::save_settings(app, &settings)?;
    }

    Ok((settings.bridge.token, settings.bridge.port))
}

/// Spawn the localhost bridge in a background tokio task.
///
/// Returns once the listener has been bound (so the port is known and
/// persisted), then continues serving on the spawned task. Errors during
/// binding are logged but never propagated up — the deep-link path remains
/// usable as a fallback.
pub async fn spawn(app: AppHandle) {
    let settings = config::load_settings(&app);

    if !settings.bridge.enabled {
        tracing::info!("local bridge disabled by settings; not starting HTTP server");
        return;
    }

    let preferred_port = settings.bridge.port;
    let (port, listener) = match bind_listener(preferred_port).await {
        Ok(pair) => pair,
        Err(error) => {
            tracing::warn!(
                "failed to bind local bridge on 127.0.0.1: {} — extension cookie path disabled",
                error
            );
            return;
        }
    };

    let (token, _port) = match ensure_bridge_settings(&app, port) {
        Ok(pair) => pair,
        Err(error) => {
            tracing::warn!("failed to persist bridge settings: {}", error);
            return;
        }
    };

    update_token(&token);
    BOUND_PORT.store(port, Ordering::SeqCst);

    let state = BridgeState {
        app: app.clone(),
        token: Arc::new(token),
    };

    let cors = CorsLayer::new()
        // The token is the actual auth boundary, so we accept any browser
        // origin (extension or webpage). Requests without a valid bearer are
        // still rejected by the handler.
        .allow_origin(Any)
        .allow_methods([Method::GET, Method::POST, Method::OPTIONS])
        .allow_headers(Any);

    let router = Router::new()
        .route("/v1/health", get(health))
        .route("/v1/pair", get(pair))
        // Media grants are their own capability: the token in the path is
        // unguessable and short-lived, so this stays out of the bearer check.
        .route("/media/{token}", get(media_stream))
        .route(
            "/v1/enqueue",
            // The extension may attach the full text of a captured HLS playlist
            // (`manifestText`), which it caps at 4 MiB. Axum's default cap is
            // 2 MiB, and hitting it fails the whole enqueue with a 413 — the
            // download would not merely lose its manifest, it would never be
            // queued at all.
            post(enqueue).layer(DefaultBodyLimit::max(ENQUEUE_BODY_LIMIT)),
        )
        .route("/v1/queue", get(queue_state))
        .route("/v1/log/{id}", get(download_log))
        .route("/v1/cookies", post(cookies_export))
        .route("/mcp", post(mcp_post).get(mcp_get).delete(mcp_get))
        .route("/api/reset", post(slides_reset))
        .route(
            "/api/slide",
            post(slides_receive).layer(DefaultBodyLimit::max(32 * 1024 * 1024)),
        )
        .route("/api/compile", post(slides_compile))
        .with_state(state)
        .layer(cors);

    tracing::info!("local bridge listening on http://127.0.0.1:{port}");

    tokio::spawn(async move {
        if let Err(error) = axum::serve(listener, router).await {
            tracing::warn!("local bridge stopped: {error}");
        }
    });
}

/// Estado da fila, o mesmo `QueueItemInfo` que a tela recebe. Serve para a
/// extensão mostrar progresso e para harness de teste observar o app por
/// fora sem instrumentar a UI. Mesmo bearer do `enqueue`.
async fn queue_state(State(state): State<BridgeState>, headers: HeaderMap) -> Response {
    if !check_bearer(&headers, &state.token) {
        return unauthorized();
    }
    let app_state = state.app.state::<crate::AppState>();
    let items = {
        let q = app_state.download_queue.lock().await;
        q.get_state()
    };
    (StatusCode::OK, Json(items)).into_response()
}

/// Últimas linhas do log de um download (até 200, redigidas na origem).
async fn download_log(
    State(state): State<BridgeState>,
    headers: HeaderMap,
    axum::extract::Path(id): axum::extract::Path<u64>,
) -> Response {
    if !check_bearer(&headers, &state.token) {
        return unauthorized();
    }
    let lines = crate::core::download_log::get(id);
    (StatusCode::OK, Json(lines)).into_response()
}

async fn health() -> Json<HealthResponse> {
    Json(HealthResponse {
        ok: true,
        version: env!("CARGO_PKG_VERSION"),
    })
}

/// Seconds the pairing window stays open after the user clicks "Pair" in the
/// app. The window is single-use (closed on the first successful hand-out).
pub const PAIR_WINDOW_SECS: i64 = 120;

/// Unix-ms deadline until which `GET /v1/pair` will return the token.
/// `0` means the pairing window is closed.
static PAIR_OPEN_UNTIL_MS: AtomicI64 = AtomicI64::new(0);

fn now_ms() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_millis() as i64)
        .unwrap_or(0)
}

/// Opens the user-consented pairing window. Returns the window length (s).
pub fn open_pairing_window() -> i64 {
    PAIR_OPEN_UNTIL_MS.store(now_ms() + PAIR_WINDOW_SECS * 1000, Ordering::SeqCst);
    PAIR_WINDOW_SECS
}

fn pairing_open() -> bool {
    PAIR_OPEN_UNTIL_MS.load(Ordering::SeqCst) > now_ms()
}

#[derive(Debug, Serialize)]
struct PairResponse {
    ok: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    token: Option<String>,
}

fn is_allowed_pair_origin(origin: &str) -> bool {
    let o = origin.trim();
    if o.starts_with("chrome-extension://")
        || o.starts_with("moz-extension://")
        || o.starts_with("safari-web-extension://")
        || o.starts_with("tauri://")
    {
        return true;
    }
    if let Ok(parsed) = url::Url::parse(o) {
        if matches!(parsed.scheme(), "http" | "https") {
            return matches!(parsed.host_str(), Some("localhost" | "127.0.0.1"));
        }
    }
    false
}

async fn pair(State(state): State<BridgeState>, headers: HeaderMap) -> Response {
    if let Some(origin) = headers.get("origin").and_then(|v| v.to_str().ok()) {
        if !is_allowed_pair_origin(origin) {
            tracing::warn!("[bridge] rejected pairing request from untrusted origin: {origin}");
            return (
                StatusCode::FORBIDDEN,
                Json(PairResponse {
                    ok: false,
                    token: None,
                }),
            )
                .into_response();
        }
    }

    if !pairing_open() {
        return (
            StatusCode::FORBIDDEN,
            Json(PairResponse {
                ok: false,
                token: None,
            }),
        )
            .into_response();
    }
    PAIR_OPEN_UNTIL_MS.store(0, Ordering::SeqCst);
    tracing::info!("[bridge] pairing token handed out (window closed, single-use)");

    // Tell the Settings UI that pairing actually succeeded, so it can flip
    // from the countdown to a success state instead of silently expiring.
    let user_agent = headers
        .get("user-agent")
        .and_then(|v| v.to_str().ok())
        .map(str::to_string);
    if let Err(error) = state.app.emit(
        "bridge-paired",
        serde_json::json!({ "userAgent": user_agent }),
    ) {
        tracing::warn!("[bridge] failed to emit bridge-paired event: {error}");
    }

    let token_out = active_token().unwrap_or_else(|| (*state.token).clone());
    (
        StatusCode::OK,
        Json(PairResponse {
            ok: true,
            token: Some(token_out),
        }),
    )
        .into_response()
}

fn unauthorized() -> Response {
    let body = Json(EnqueueResponse {
        ok: false,
        code: Some("UNAUTHORIZED"),
        message: Some("Invalid or missing bearer token".to_string()),
    });
    (StatusCode::UNAUTHORIZED, body).into_response()
}

fn check_bearer(headers: &HeaderMap, fallback: &str) -> bool {
    let header = match headers.get("authorization") {
        Some(v) => v,
        None => return false,
    };
    let raw = match header.to_str() {
        Ok(s) => s,
        Err(_) => return false,
    };
    let provided = match raw
        .strip_prefix("Bearer ")
        .or_else(|| raw.strip_prefix("bearer "))
    {
        Some(s) => s.trim(),
        None => return false,
    };
    let current_token = active_token();
    let expected = current_token.as_deref().unwrap_or(fallback);
    constant_time_eq::constant_time_eq(provided.as_bytes(), expected.as_bytes())
}

async fn enqueue(
    State(state): State<BridgeState>,
    headers: HeaderMap,
    Json(request): Json<EnqueueRequest>,
) -> Response {
    if !check_bearer(&headers, &state.token) {
        return unauthorized();
    }

    if let Some(client_version) = request.protocol_version {
        if client_version > HOST_MAX_PROTOCOL_VERSION {
            return error_response(
                StatusCode::BAD_REQUEST,
                "UNSUPPORTED_PROTOCOL",
                format!(
                    "Extension protocol v{client_version} is newer than host v{HOST_MAX_PROTOCOL_VERSION}. Please update LibreGet."
                ),
            );
        }
    }

    let payload = request.payload;

    if !crate::external_url::is_external_url(&payload.url) {
        return error_response(
            StatusCode::BAD_REQUEST,
            "INVALID_URL",
            "The requested URL is invalid".to_string(),
        );
    }

    if let Some(ref cookies) = payload.cookies {
        if cookies.len() > cookie_limit() {
            return error_response(
                StatusCode::BAD_REQUEST,
                "TOO_MANY_COOKIES",
                format!(
                    "Request contains {} cookies; max allowed is {}",
                    cookies.len(),
                    cookie_limit()
                ),
            );
        }
        if !cookies.is_empty() {
            if let Err(error) = crate::cookies::ingest_batch(
                cookies,
                crate::cookies::IngestSource {
                    source_url: payload
                        .page_url
                        .clone()
                        .or_else(|| Some(payload.url.clone())),
                    source_label: "Browser extension".to_string(),
                    alias_hint: payload.title.clone(),
                },
            ) {
                tracing::warn!("failed to ingest cookies into manager: {error}");
            }
        }
    }

    if payload.referer.is_some()
        || payload.headers.is_some()
        || payload.media_type.is_some()
        || payload.title.is_some()
        || payload.thumbnail.is_some()
        || payload.open_app.is_some()
        || payload.page_url.is_some()
        || payload.user_agent.is_some()
    {
        if let Err(error) = write_extension_metadata(&payload) {
            tracing::warn!("failed to write extension metadata: {error}");
        }
    }

    // Deep search can recover an HLS playlist that only ever existed as a
    // `blob:` URL inside the tab, so the extension ships its text instead of
    // an address. Park it on disk keyed by URL; the HLS downloader picks it
    // up when the item finally leaves the queue. A failure here only costs us
    // the shortcut, never the enqueue.
    if let Some(text) = payload.manifest_text.as_deref() {
        if !text.trim().is_empty() {
            match libreget_core::core::extension_manifest::store_manifest(&payload.url, text) {
                Ok(()) => tracing::info!(
                    "stored extension-captured playlist ({} bytes) for {}",
                    text.len(),
                    payload.url
                ),
                Err(error) => {
                    tracing::warn!("failed to store extension playlist text: {error}")
                }
            }
        }
    }

    let app = state.app.clone();
    let url = payload.url.clone();
    tauri::async_runtime::spawn(async move {
        if let Err(error) = crate::external_url::handle_external_url(&app, url, "bridge").await {
            tracing::warn!("failed to handle bridge URL: {error}");
        }
    });

    let body = Json(EnqueueResponse {
        ok: true,
        code: None,
        message: None,
    });
    (StatusCode::OK, body).into_response()
}

async fn cookies_export(
    State(state): State<BridgeState>,
    headers: HeaderMap,
    Json(request): Json<CookiesRequest>,
) -> Response {
    if !check_bearer(&headers, &state.token) {
        return unauthorized();
    }

    if let Some(client_version) = request.protocol_version {
        if client_version > HOST_MAX_PROTOCOL_VERSION {
            return error_response(
                StatusCode::BAD_REQUEST,
                "UNSUPPORTED_PROTOCOL",
                format!(
                    "Extension protocol v{client_version} is newer than host v{HOST_MAX_PROTOCOL_VERSION}. Please update LibreGet."
                ),
            );
        }
    }

    if request.cookies.len() > cookie_limit() {
        return error_response(
            StatusCode::BAD_REQUEST,
            "TOO_MANY_COOKIES",
            format!(
                "cookies:export contains {} cookies; max is {}",
                request.cookies.len(),
                cookie_limit()
            ),
        );
    }

    if !request.cookies.is_empty() {
        let label = if request.source_url.is_some() || request.alias.is_some() {
            "Browser extension (manual capture)".to_string()
        } else {
            "Browser extension (auto-capture)".to_string()
        };
        let alias_hint = request.alias.clone().or_else(|| request.page_title.clone());
        if let Err(error) = crate::cookies::ingest_batch(
            &request.cookies,
            crate::cookies::IngestSource {
                source_url: request.source_url.clone(),
                source_label: label,
                alias_hint,
            },
        ) {
            return error_response(
                StatusCode::INTERNAL_SERVER_ERROR,
                "WRITE_FAILED",
                format!("ingest cookies: {error}"),
            );
        }
    }

    let body = Json(EnqueueResponse {
        ok: true,
        code: None,
        message: None,
    });
    (StatusCode::OK, body).into_response()
}

fn error_response(status: StatusCode, code: &'static str, message: String) -> Response {
    let body = Json(EnqueueResponse {
        ok: false,
        code: Some(code),
        message: Some(message),
    });
    (status, body).into_response()
}

pub fn build_pairing_url(port: u16) -> String {
    format!("http://127.0.0.1:{port}")
}

// ── MCP (Streamable HTTP, só JSON) ─────────────────────────────────────

/// `POST /mcp`: JSON-RPC do MCP. Mesmo bearer da extensão; 403 quando a
/// tool "Servidor MCP" está desligada; 202 sem corpo para notificações.
async fn mcp_post(
    State(state): State<BridgeState>,
    headers: HeaderMap,
    body: axum::body::Bytes,
) -> Response {
    if !check_bearer(&headers, &state.token) {
        return unauthorized();
    }
    if !crate::mcp::enabled() {
        return (StatusCode::FORBIDDEN, Json(serde_json::json!({ "error": "MCP server is disabled in LibreGet → Tools → MCP server" }))).into_response();
    }
    let msg: serde_json::Value = match serde_json::from_slice(&body) {
        Ok(v) => v,
        Err(e) => {
            return (
                StatusCode::BAD_REQUEST,
                Json(serde_json::json!({ "jsonrpc": "2.0", "id": null, "error": { "code": -32700, "message": format!("parse error: {}", e) } })),
            )
                .into_response()
        }
    };
    match crate::mcp::handle_body(&state.app, &msg).await {
        Some(resp) => (StatusCode::OK, Json(resp)).into_response(),
        None => StatusCode::ACCEPTED.into_response(),
    }
}

/// Sem canal SSE: quem pedir GET recebe 405 e continua só com POST.
async fn mcp_get() -> Response {
    StatusCode::METHOD_NOT_ALLOWED.into_response()
}

// ── Receptor local de diapositivas Google Slides (/api/reset, /api/slide, /api/compile) ──

#[derive(Default)]
struct SlidesSession {
    title: Option<String>,
    slides: Vec<(usize, String)>,
    last_output: Option<String>,
}

static SLIDES_BUFFER: OnceLock<Mutex<SlidesSession>> = OnceLock::new();

fn slides_buffer() -> &'static Mutex<SlidesSession> {
    SLIDES_BUFFER.get_or_init(|| Mutex::new(SlidesSession::default()))
}

#[derive(Debug, Clone, Serialize)]
pub struct SlidesBridgeStatus {
    pub port: u16,
    pub slide_count: usize,
    pub last_output: Option<String>,
    pub script: String,
}

pub fn slides_bridge_status() -> SlidesBridgeStatus {
    let port = BOUND_PORT.load(Ordering::SeqCst);
    let effective_port = if port == 0 { 47720 } else { port };
    let token = active_token().unwrap_or_default();
    let (slide_count, last_output) = slides_buffer()
        .lock()
        .ok()
        .map(|s| (s.slides.len(), s.last_output.clone()))
        .unwrap_or((0, None));
    SlidesBridgeStatus {
        port: effective_port,
        slide_count,
        last_output,
        script: libreget_core::core::tools::gslides::browser_extractor_script(
            effective_port,
            &token,
        ),
    }
}

#[derive(Debug, Deserialize, Default)]
struct SlideResetBody {
    #[serde(default)]
    title: Option<String>,
}

#[derive(Debug, Deserialize)]
struct SlideReceiveBody {
    index: usize,
    svg_content: String,
    #[serde(default)]
    title: Option<String>,
}

async fn slides_reset(
    State(state): State<BridgeState>,
    headers: HeaderMap,
    body: Option<Json<SlideResetBody>>,
) -> Response {
    if !check_bearer(&headers, &state.token) {
        return unauthorized();
    }
    if let Ok(mut guard) = slides_buffer().lock() {
        guard.slides.clear();
        guard.title = body
            .and_then(|b| b.0.title)
            .filter(|t| !t.trim().is_empty());
    }
    let _ = state.app.emit(
        "gslides-bridge-progress",
        serde_json::json!({ "slide_count": 0 }),
    );
    (
        StatusCode::OK,
        Json(serde_json::json!({ "status": "reset_successful" })),
    )
        .into_response()
}

async fn slides_receive(
    State(state): State<BridgeState>,
    headers: HeaderMap,
    Json(data): Json<SlideReceiveBody>,
) -> Response {
    if !check_bearer(&headers, &state.token) {
        return unauthorized();
    }
    let count = if let Ok(mut guard) = slides_buffer().lock() {
        if let Some(t) = data.title.filter(|t| !t.trim().is_empty()) {
            guard.title = Some(t);
        }
        if let Some(existing) = guard.slides.iter_mut().find(|(idx, _)| *idx == data.index) {
            existing.1 = data.svg_content;
        } else {
            guard.slides.push((data.index, data.svg_content));
        }
        guard.slides.len()
    } else {
        0
    };
    let _ = state.app.emit(
        "gslides-bridge-progress",
        serde_json::json!({ "slide_count": count, "index": data.index }),
    );
    (
        StatusCode::OK,
        Json(serde_json::json!({ "status": "ok", "slide_count": count })),
    )
        .into_response()
}

async fn slides_compile(
    State(state): State<BridgeState>,
    headers: HeaderMap,
    body: Option<Json<SlideResetBody>>,
) -> Response {
    if !check_bearer(&headers, &state.token) {
        return unauthorized();
    }
    let (mut indexed_svgs, title) = match slides_buffer().lock() {
        Ok(mut guard) => {
            if let Some(t) = body
                .and_then(|b| b.0.title)
                .filter(|t| !t.trim().is_empty())
            {
                guard.title = Some(t);
            }
            (
                guard.slides.clone(),
                guard
                    .title
                    .clone()
                    .unwrap_or_else(|| "presentacion_compilada".to_string()),
            )
        }
        Err(_) => (Vec::new(), "presentacion_compilada".to_string()),
    };

    if indexed_svgs.is_empty() {
        return (
            StatusCode::BAD_REQUEST,
            Json(serde_json::json!({ "status": "error", "detail": "No hay diapositivas acumuladas." })),
        )
            .into_response();
    }

    indexed_svgs.sort_by_key(|(idx, _)| *idx);
    let svgs: Vec<String> = indexed_svgs.into_iter().map(|(_, s)| s).collect();
    let pages = svgs.len();

    let settings = config::load_settings(&state.app);
    let out_dir = if !settings.download.default_output_dir.as_os_str().is_empty() {
        settings.download.default_output_dir.clone()
    } else {
        dirs::download_dir().unwrap_or_else(|| PathBuf::from("."))
    };
    let _ = std::fs::create_dir_all(&out_dir);
    let safe_title = libreget_core::core::tools::sanitize_name(&title);
    let out_file = out_dir.join(format!("{}.pdf", safe_title));

    let compile_res = tokio::task::spawn_blocking(move || {
        libreget_core::core::tools::gslides::compile_svgs_to_pdf(
            &svgs,
            &libreget_core::core::tools::noop_progress(),
            "bridge-compile",
        )
    })
    .await;

    let pdf_bytes = match compile_res {
        Ok(Ok(b)) => b,
        Ok(Err(e)) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(serde_json::json!({ "status": "error", "detail": e.to_string() })),
            )
                .into_response();
        }
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(serde_json::json!({ "status": "error", "detail": e.to_string() })),
            )
                .into_response();
        }
    };

    if let Err(e) = tokio::fs::write(&out_file, &pdf_bytes).await {
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(serde_json::json!({ "status": "error", "detail": e.to_string() })),
        )
            .into_response();
    }

    let file_str = out_file.to_string_lossy().to_string();
    if let Ok(mut guard) = slides_buffer().lock() {
        guard.last_output = Some(file_str.clone());
        guard.slides.clear();
    }

    let _ = state.app.emit(
        "gslides-bridge-complete",
        serde_json::json!({ "file": file_str, "pages": pages }),
    );

    (
        StatusCode::OK,
        Json(serde_json::json!({ "status": "success", "file": file_str, "pages": pages })),
    )
        .into_response()
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::http::HeaderValue;

    fn header_with_auth(value: &str) -> HeaderMap {
        let mut headers = HeaderMap::new();
        headers.insert(
            "authorization",
            HeaderValue::from_str(value).expect("valid header"),
        );
        headers
    }

    #[test]
    fn token_is_url_safe_base64_with_no_padding() {
        let t = generate_token();
        assert!(t.len() >= 40);
        assert!(!t.contains('+'));
        assert!(!t.contains('/'));
        assert!(!t.contains('='));
    }

    #[test]
    fn check_bearer_accepts_valid_token() {
        let headers = header_with_auth("Bearer abc.def-ghi");
        assert!(check_bearer(&headers, "abc.def-ghi"));
    }

    #[test]
    fn check_bearer_is_case_insensitive_on_scheme() {
        let headers = header_with_auth("bearer abc");
        assert!(check_bearer(&headers, "abc"));
    }

    #[test]
    fn check_bearer_rejects_missing_header() {
        let headers = HeaderMap::new();
        assert!(!check_bearer(&headers, "abc"));
    }

    #[test]
    fn check_bearer_rejects_wrong_token() {
        let headers = header_with_auth("Bearer different");
        assert!(!check_bearer(&headers, "abc"));
    }

    #[test]
    fn check_bearer_rejects_missing_scheme_prefix() {
        let headers = header_with_auth("abc");
        assert!(!check_bearer(&headers, "abc"));
    }

    #[test]
    fn build_pairing_url_uses_loopback_address() {
        assert_eq!(build_pairing_url(47720), "http://127.0.0.1:47720");
    }

    #[test]
    fn allowed_pair_origin_rejects_spoofed_subdomains() {
        assert!(is_allowed_pair_origin(
            "chrome-extension://abcdefghijklmnop"
        ));
        assert!(is_allowed_pair_origin("moz-extension://1234-5678"));
        assert!(is_allowed_pair_origin("tauri://localhost"));
        assert!(is_allowed_pair_origin("http://localhost:1420"));
        assert!(is_allowed_pair_origin("https://localhost:47720"));
        assert!(is_allowed_pair_origin("http://127.0.0.1:47720"));
        assert!(!is_allowed_pair_origin("https://localhost.evil.com"));
        assert!(!is_allowed_pair_origin(
            "http://localhost.attacker.tld:8080"
        ));
        assert!(!is_allowed_pair_origin("http://127.0.0.1.evil.com"));
        assert!(!is_allowed_pair_origin("https://evil.com"));
    }

    #[test]
    fn byte_ranges_parse_into_specs() {
        use ByteRange::*;
        assert!(matches!(parse_byte_range("bytes=0-"), Ok(From(0, None))));
        assert!(matches!(
            parse_byte_range("bytes=100-199"),
            Ok(From(100, Some(199)))
        ));
        assert!(matches!(parse_byte_range("bytes=-500"), Ok(LastBytes(500))));
        // Whitespace, a single range out of a multi-range request, and an
        // end before start are all part of the contract.
        assert!(matches!(parse_byte_range("bytes=0 -"), Ok(From(0, None))));
        assert!(matches!(
            parse_byte_range("bytes=0-9, 50-59"),
            Ok(From(0, Some(9)))
        ));
        assert!(parse_byte_range("bytes=9-0").is_err());
        assert!(parse_byte_range("attachments=0-9").is_err());
    }

    #[test]
    fn media_mime_covers_the_players_formats() {
        assert_eq!(media_mime(Path::new("a/b/lesson.mp4")), "video/mp4");
        assert_eq!(media_mime(Path::new("a/b/lesson.MKV")), "video/x-matroska");
        assert_eq!(media_mime(Path::new("a/b/track.flac")), "audio/flac");
        assert_eq!(media_mime(Path::new("a/b/lyrics.vtt")), "text/vtt");
        assert_eq!(
            media_mime(Path::new("a/b/blob.bin")),
            "application/octet-stream"
        );
    }
}