Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

6.9 KB
Raw Blame
use super::super::{ChildBrowsingContextBootstrap, ChildBrowsingContextSnapshot, JsContextHost};
use crate::document_response_decoder::decode_document_response;
use crate::document_runtime::{DocumentPolicyContainer, DomHandle};
use moli_web_mime::{
    is_html_document_mime, resource_mime_essence_for_url, response_document_content_type,
};
use url::Url;

impl JsContextHost {
    pub(in crate::native_bridge::context_host) fn apply_page_csp_bypass_to_child_snapshot(
        &self,
        mut snapshot: ChildBrowsingContextSnapshot,
    ) -> ChildBrowsingContextSnapshot {
        if self.bypass_content_security_policy() {
            snapshot
                .policy_container
                .clear_content_security_policy_for_bypass();
        }
        snapshot
    }

    pub(crate) fn materialize_local_child_snapshot_for_navigation_url(
        &self,
        handle: DomHandle,
        url: &Url,
    ) -> Option<ChildBrowsingContextSnapshot> {
        let snapshot = self.apply_page_csp_bypass_to_child_snapshot(
            self.materialize_local_child_snapshot_for_url(url)?,
        );
        if moli_url::is_about_blank(&snapshot.url) {
            Some(snapshot.with_fallback_base_url(self.document_base_url_for_child_context(handle)))
        } else {
            Some(snapshot)
        }
    }

    pub(crate) fn materialize_local_child_snapshot_for_url(
        &self,
        url: &Url,
    ) -> Option<ChildBrowsingContextSnapshot> {
        match url.scheme() {
            "about" if url.path() == "blank" => Some(ChildBrowsingContextSnapshot::html(
                url.clone(),
                "<!DOCTYPE html><html><head></head><body></body></html>".into(),
            )),
            "http" | "https" => None,
            "blob" => {
                let (body, mime_type) = crate::blob::object_url_body_and_type(url.as_str())?;
                if !mime_type.is_empty() && !is_html_document_mime(&mime_type) {
                    return None;
                }
                let character_set = self.document_character_set().to_owned();
                Some(ChildBrowsingContextSnapshot::with_character_set(
                    url.clone(),
                    body,
                    child_document_content_type_from_header_value(&mime_type)
                        .or_else(|| Some("text/html".to_owned())),
                    character_set,
                ))
            }
            "data" => crate::network_host::local_url_response(url).map(|response| {
                let head = response.head();
                let content_type = child_document_content_type_from_headers(&head.headers);
                let (body, character_set) = decode_document_response(
                    response.body_bytes(),
                    &head.headers,
                    content_type.as_deref(),
                    &head.final_url,
                    Some(self.document_character_set()),
                );
                let policy_container = DocumentPolicyContainer::from_navigation_response_headers(
                    &head.headers,
                    &head.final_url,
                );
                ChildBrowsingContextSnapshot::with_character_set(
                    head.final_url,
                    body,
                    content_type,
                    character_set,
                )
                .with_policy_container(policy_container)
            }),
            _ => None,
        }
    }

    pub(in crate::native_bridge::context_host) fn materialize_local_child_snapshot_for_bootstrap(
        &self,
        handle: DomHandle,
        bootstrap: &ChildBrowsingContextBootstrap,
    ) -> Option<ChildBrowsingContextSnapshot> {
        match bootstrap {
            ChildBrowsingContextBootstrap::AboutBlank => {
                let policy_container =
                    self.initial_child_about_blank_policy_container_from_parent(handle);
                Some(
                    self.apply_page_csp_bypass_to_child_snapshot(
                        ChildBrowsingContextSnapshot::about_blank(
                            self.document_base_url_for_child_context(handle),
                        )
                        .with_policy_container(policy_container),
                    ),
                )
            }
            ChildBrowsingContextBootstrap::Srcdoc { base_url, markup } => Some(
                self.apply_page_csp_bypass_to_child_snapshot(ChildBrowsingContextSnapshot::srcdoc(
                    base_url.clone(),
                    markup.clone(),
                    self.document_character_set().to_owned(),
                )),
            ),
            ChildBrowsingContextBootstrap::Url(url) => {
                self.materialize_local_child_snapshot_for_navigation_url(handle, url)
            }
            ChildBrowsingContextBootstrap::Request(_) => None,
        }
    }
}

pub(in crate::native_bridge::context_host) fn child_document_content_type_from_headers(
    headers: &[(String, Vec<u8>)],
) -> Option<String> {
    response_document_content_type(headers)
}

fn child_document_content_type_from_header_value(value: &str) -> Option<String> {
    moli_web_mime::mime_essence(value)
}

pub(in crate::native_bridge::context_host) fn child_document_content_type_for_url(
    url: &Url,
) -> Option<String> {
    resource_mime_essence_for_url(url.as_str(), url.path())
}

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

    #[test]
    fn child_document_content_type_routes_through_web_mime_helpers() {
        let headers: Vec<(String, Vec<u8>)> = vec![
            ("content-type".to_owned(), b"text/plain".to_vec()),
            (
                "Content-Type".to_owned(),
                b" Image/SVG+XML ; charset=utf-8 ".to_vec(),
            ),
        ];
        assert_eq!(
            child_document_content_type_from_headers(&headers).as_deref(),
            Some("image/svg+xml")
        );
        assert_eq!(
            child_document_content_type_from_headers(&[("Content-Type".to_owned(), b" ".to_vec())]),
            None
        );
        assert_eq!(
            child_document_content_type_for_url(
                &Url::parse("https://example.test/frame.PNG").unwrap()
            )
            .as_deref(),
            Some("image/png")
        );
        assert_eq!(
            child_document_content_type_for_url(
                &Url::parse("data:Image/SVG+XML,<svg></svg>").unwrap()
            )
            .as_deref(),
            Some("image/svg+xml")
        );
        let data_url = Url::parse("data:font/woff2;base64,AA==").unwrap();
        assert_eq!(
            child_document_content_type_for_url(&data_url).as_deref(),
            Some("font/woff2")
        );
        let video_url = Url::parse("https://example.test/media/clip.WEBM").unwrap();
        assert_eq!(
            child_document_content_type_for_url(&video_url).as_deref(),
            Some("video/webm")
        );
        assert_eq!(
            child_document_content_type_for_url(
                &Url::parse("https://example.test/frame.json").unwrap()
            ),
            None
        );
    }
}