Skip to content

armgit / moli

Public Imported from GitHub
0

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

13.5 KB
Raw Blame
use super::navigation_activation::navigation_activation_value;
use super::navigation_entry::{
    history_index, navigation_current_entry, navigation_entry_referrer_policy_value,
};
use super::navigation_window::{
    child_browsing_context_handle_for_runtime_owner, runtime_window_is_global,
    runtime_window_owner, window_history_for_holder, window_navigation_for_holder,
};
use super::*;
use crate::content_security_policy::ContentSecurityPolicy;
use crate::native_bridge::{
    NavigationActivationSeed, NavigationHistoryDocumentId, NavigationHistoryEntryId,
    NavigationHistoryEntryKey, NavigationHistoryEntrySeed, NavigationHistorySerializedEntry,
};
use crate::{
    document_runtime::DomHandle, native_bridge::node_runtime_and_handle_from_object,
    referrer_policy::normalize_referrer_policy, util::context_host_ptr_from_window_object,
};

fn capture_navigation_entry_seed_for_holder<'s>(
    scope: &mut v8::PinScope<'s, '_>,
    owner: v8::Local<'s, v8::Object>,
) -> Option<NavigationHistoryEntrySeed> {
    let history = window_history_for_holder(scope, owner)?;
    let navigation = window_navigation_for_holder(scope, owner)?;
    Some(NavigationHistoryEntrySeed {
        session_history: Default::default(),
        entries: serialize_history_entries(scope, history),
        current_index: history_index(scope, history),
        activation: serialize_navigation_activation_seed(scope, navigation),
    })
}

pub(super) fn sync_child_navigation_entry_seed_from_owner<'s>(
    scope: &mut v8::PinScope<'s, '_>,
    owner: v8::Local<'s, v8::Object>,
) {
    sync_child_navigation_entry_seed_from_owner_with_document_url(
        scope,
        owner,
        true,
        moli_page_types::SessionHistoryCommit::Attach,
    );
}

pub(super) fn sync_child_pending_navigation_entry_seed_from_owner<'s>(
    scope: &mut v8::PinScope<'s, '_>,
    owner: v8::Local<'s, v8::Object>,
    commit: moli_page_types::SessionHistoryCommit,
) {
    sync_child_navigation_entry_seed_from_owner_with_document_url(scope, owner, false, commit);
}

fn sync_child_navigation_entry_seed_from_owner_with_document_url<'s>(
    scope: &mut v8::PinScope<'s, '_>,
    owner: v8::Local<'s, v8::Object>,
    sync_document_url: bool,
    commit: moli_page_types::SessionHistoryCommit,
) {
    if runtime_window_is_global(scope, owner) {
        return;
    }
    let Some(handle) = child_browsing_context_handle_for_runtime_owner(scope, owner) else {
        return;
    };
    let Some(mut entry_seed) = capture_navigation_entry_seed_for_holder(scope, owner) else {
        return;
    };
    entry_seed.session_history.commit = commit;
    let Some(host_ptr) = context_host_ptr_for_navigation_seed_owner(scope, owner) else {
        return;
    };
    let host = unsafe { &mut *host_ptr };
    if host.set_child_browsing_context_navigation_entry_seed(handle, entry_seed)
        && sync_document_url
    {
        host.sync_child_browsing_context_document_url(scope, handle);
    }
}

fn context_host_ptr_for_navigation_seed_owner(
    scope: &mut v8::PinScope<'_, '_>,
    owner: v8::Local<'_, v8::Object>,
) -> Option<*mut crate::native_bridge::JsContextHost> {
    context_host_ptr_from_global_bridge(scope)
        .or_else(|| context_host_ptr_from_window_object(scope, owner))
        .or_else(|| {
            owner
                .get(scope, v8str(scope, "parent").into())
                .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
                .and_then(|parent| context_host_ptr_from_window_object(scope, parent))
        })
}

pub(super) fn serialize_navigation_entry_object<'s>(
    scope: &mut v8::PinScope<'s, '_>,
    entry: v8::Local<'s, v8::Object>,
    history_entries: &[NavigationHistorySerializedEntry],
) -> NavigationHistorySerializedEntry {
    let Some(record) = super::history_runtime::native::entry(scope, entry) else {
        return NavigationHistorySerializedEntry {
            url: "about:blank".to_owned(),
            inherited_origin: None,
            history_state: None,
            navigation_state: None,
            scroll_restoration: Default::default(),
            referrer_policy: None,
            document_id: NavigationHistoryDocumentId::allocate(),
            history_index: 0,
            index: 0,
            id: NavigationHistoryEntryId::allocate(),
            key: NavigationHistoryEntryKey::allocate(),
        };
    };
    let record = record.borrow();
    if let Some(snapshot) = history_entries
        .iter()
        .find(|snapshot| snapshot.id.as_str() == record.id && snapshot.key == record.key)
    {
        return snapshot.clone();
    }
    snapshot_native_entry(&record, record.index)
}

fn snapshot_native_entry(
    entry: &moli_history::HistoryEntry,
    history_index: u32,
) -> NavigationHistorySerializedEntry {
    NavigationHistorySerializedEntry {
        url: entry.url.clone(),
        inherited_origin: entry.inherited_origin.clone(),
        history_state: entry.history_state.clone(),
        navigation_state: entry.navigation_state.clone(),
        scroll_restoration: entry.scroll_restoration,
        referrer_policy: entry.referrer_policy.clone(),
        document_id: entry.document.clone(),
        history_index,
        index: entry.index,
        id: NavigationHistoryEntryId::from_serialized(entry.id.clone()),
        key: entry.key.clone(),
    }
}

fn serialize_navigation_activation_seed<'s>(
    scope: &mut v8::PinScope<'s, '_>,
    navigation: v8::Local<'s, v8::Object>,
) -> Option<NavigationActivationSeed> {
    let owner = runtime_window_owner(scope, navigation);
    let history = window_history_for_holder(scope, owner)?;
    let history_entries = serialize_history_entries(scope, history);
    let activation = navigation_activation_value(scope, navigation)
        .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())?;
    let entry = get_own_static_property(scope, activation, "entry")
        .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
        .map(|entry| serialize_navigation_entry_object(scope, entry, &history_entries))?;
    let from = get_own_static_property(scope, activation, "from")
        .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
        .map(|entry| serialize_navigation_entry_object(scope, entry, &history_entries));
    let navigation_type = get_own_static_property(scope, activation, "navigationType")
        .and_then(|value| value.to_string(scope))
        .map(|value| value.to_rust_string_lossy(scope))
        .filter(|value| !value.is_empty() && value != "null");
    Some(NavigationActivationSeed {
        entry,
        from,
        navigation_type,
    })
}

pub(super) fn serialize_history_entries<'s>(
    scope: &mut v8::PinScope<'s, '_>,
    history: v8::Local<'s, v8::Object>,
) -> Vec<NavigationHistorySerializedEntry> {
    let Some(record) = super::history_runtime::native::history(scope, history) else {
        return Vec::new();
    };
    let record = record.borrow();
    let inherited_document = record.current_entry().and_then(|current| {
        let current = current.borrow();
        url::Url::parse(&current.url)
            .ok()
            .filter(super::navigation_projection::navigation_entry_url_inherits_origin)
            .map(|_| current.document.clone())
    });
    let origin = inherited_document.as_ref().and_then(|_| {
        let owner = runtime_window_owner(scope, history);
        super::navigation_projection::current_document_origin(scope, owner)
    });
    record
        .entries()
        .iter()
        .enumerate()
        .map(|(index, entry)| {
            let mut snapshot = snapshot_native_entry(&entry.borrow(), index as u32);
            if inherited_document.as_ref() == Some(&snapshot.document_id) && origin.is_some() {
                snapshot.inherited_origin = origin.clone();
            }
            snapshot
        })
        .collect()
}

pub(super) fn apply_current_document_referrer_policy_to_entry_snapshots<'s>(
    scope: &mut v8::PinScope<'s, '_>,
    owner: v8::Local<'s, v8::Object>,
    current_index: u32,
    snapshots: &mut [NavigationHistorySerializedEntry],
) {
    let current_document_id = snapshots
        .iter()
        .find(|entry| entry.history_index == current_index)
        .map(|entry| entry.document_id.clone());
    let policy = current_document_referrer_policy(scope, owner).or_else(|| {
        current_document_id
            .as_ref()
            .and_then(|current_document_id| {
                snapshots
                    .iter()
                    .find(|entry| {
                        entry.document_id == *current_document_id && entry.referrer_policy.is_some()
                    })
                    .and_then(|entry| entry.referrer_policy.clone())
            })
    });
    let mut applied = false;
    if let Some(current_document_id) = current_document_id {
        for snapshot in snapshots
            .iter_mut()
            .filter(|entry| entry.document_id == current_document_id)
        {
            snapshot.referrer_policy = policy.clone();
            applied = true;
        }
    }
    if !applied
        && let Some(current) = snapshots
            .iter_mut()
            .find(|entry| entry.history_index == current_index)
    {
        current.referrer_policy = policy;
    }
}

pub(crate) fn current_document_referrer_policy<'s>(
    scope: &mut v8::PinScope<'s, '_>,
    owner: v8::Local<'s, v8::Object>,
) -> Option<String> {
    let document = get_own_static_property(scope, owner, "document")
        .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())?;
    if let Ok((runtime_ptr, document_handle)) = node_runtime_and_handle_from_object(scope, document)
    {
        let runtime = unsafe { &*runtime_ptr };
        return document_referrer_policy_for_native_document(runtime, document_handle)
            .or_else(|| current_entry_referrer_policy(scope, owner));
    }
    let runtime_ptr = context_host_ptr_from_global_bridge(scope)?;
    let document_handle = crate::native_bridge::document::detached_native_handle_for_runtime(
        scope,
        runtime_ptr,
        document,
    )?;
    let runtime = unsafe { &*runtime_ptr };
    document_referrer_policy_for_native_document(runtime, document_handle)
        .or_else(|| current_entry_referrer_policy(scope, owner))
}

pub(super) fn document_referrer_policy_for_native_document(
    runtime: &crate::native_bridge::JsContextHost,
    document_handle: DomHandle,
) -> Option<String> {
    document_referrer_policy_in_subtree(runtime, document_handle)
        .or_else(|| {
            (document_handle == runtime.document_handle())
                .then(|| runtime.response_referrer_policy().map(ToOwned::to_owned))
                .flatten()
        })
        .or_else(|| {
            runtime
                .child_browsing_context_referrer_policy_for_document_handle(document_handle)
                .map(ToOwned::to_owned)
        })
        .or_else(|| {
            runtime
                .lightweight_popup_referrer_policy_for_document_handle(document_handle)
                .map(ToOwned::to_owned)
        })
}

pub(super) fn current_document_content_security_policies<'s>(
    scope: &mut v8::PinScope<'s, '_>,
    owner: v8::Local<'s, v8::Object>,
) -> Vec<ContentSecurityPolicy> {
    let Some(document) = get_own_static_property(scope, owner, "document")
        .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
    else {
        return Vec::new();
    };
    if let Ok((runtime_ptr, document_handle)) = node_runtime_and_handle_from_object(scope, document)
    {
        return unsafe { &*runtime_ptr }
            .meta_content_security_policies_for_document(document_handle);
    }
    let Some(runtime_ptr) = context_host_ptr_from_global_bridge(scope) else {
        return Vec::new();
    };
    let Some(document_handle) = crate::native_bridge::document::detached_native_handle_for_runtime(
        scope,
        runtime_ptr,
        document,
    ) else {
        return Vec::new();
    };
    unsafe { &*runtime_ptr }.meta_content_security_policies_for_document(document_handle)
}

fn current_entry_referrer_policy<'s>(
    scope: &mut v8::PinScope<'s, '_>,
    owner: v8::Local<'s, v8::Object>,
) -> Option<String> {
    navigation_current_entry(scope, owner)
        .and_then(|entry| navigation_entry_referrer_policy_value(scope, entry))
}

fn document_referrer_policy_in_subtree(
    runtime: &crate::native_bridge::JsContextHost,
    handle: DomHandle,
) -> Option<String> {
    if let Some(element) = runtime
        .dom_host()
        .node(handle)
        .and_then(|node| node.as_element())
        && element.local_name().eq_ignore_ascii_case("meta")
        && element
            .attribute("name")
            .is_some_and(|name| name.eq_ignore_ascii_case("referrer"))
        && let Some(policy) = element
            .attribute("content")
            .and_then(normalize_meta_referrer_policy)
    {
        return Some(policy);
    }

    let mut child = runtime.dom_host().first_child(handle);
    while let Some(child_handle) = child {
        if let Some(policy) = document_referrer_policy_in_subtree(runtime, child_handle) {
            return Some(policy);
        }
        child = runtime.dom_host().next_sibling(child_handle);
    }
    None
}

fn normalize_meta_referrer_policy(raw: &str) -> Option<String> {
    normalize_referrer_policy(raw)
}

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

    #[test]
    fn meta_referrer_policy_uses_last_valid_token() {
        assert_eq!(
            normalize_meta_referrer_policy("not-yet-standardized, no-referrer"),
            Some("no-referrer".to_owned())
        );
        assert_eq!(
            normalize_meta_referrer_policy("same-origin, not-yet-standardized"),
            Some("same-origin".to_owned())
        );
    }
}