Skip to main content

http_quik/client/
request.rs

1use crate::profile::ChromeProfile;
2use http::header::{HeaderMap, HeaderValue, ACCEPT, ACCEPT_ENCODING, ACCEPT_LANGUAGE, USER_AGENT};
3
4/// Defines the context of the network request, mimicking browser fetch metadata.
5#[allow(dead_code)]
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum RequestContext {
8    /// A top-level page navigation (e.g., clicking a link or typing in the URL bar).
9    Navigate,
10    /// An asynchronous XMLHttpRequest or Fetch API call.
11    Xhr,
12    /// A form submission navigation.
13    Form,
14    /// An iframe navigation.
15    Iframe,
16    /// A parser-blocking or async script subresource.
17    NoCorsScript,
18    /// A stylesheet subresource.
19    NoCorsStyle,
20    /// An image subresource.
21    NoCorsImage,
22    /// A font subresource.
23    NoCorsFont,
24    /// A media subresource.
25    NoCorsMedia,
26    /// A Web Worker script.
27    Worker,
28    /// A Service Worker script.
29    ServiceWorker,
30    /// A prefetch request.
31    Prefetch,
32}
33
34/// Injects Chrome-identical headers into the provided request map.
35///
36/// Populates navigation metadata, Client Hints, compression preferences,
37/// and HPACK sensitivity flags in the exact order and format emitted by
38/// the target Chrome version.
39///
40/// ## Cross-Platform Consistency
41/// The `sec-ch-ua-platform` and `sec-ch-ua-platform-version` values are
42/// sourced from the active [`ChromeProfile`], ensuring they match the
43/// OS persona declared during the TLS handshake.
44///
45/// ## HPACK Sensitivity
46/// `cookie` and `authorization` headers are marked as sensitive to force
47/// the HPACK encoder into "Literal Never Indexed" mode, preventing
48/// side-channel leaks (CRIME mitigation).
49pub fn inject_chrome_headers(
50    headers: &mut HeaderMap,
51    profile: &ChromeProfile,
52    sec_fetch_site: &str,
53    is_initial_navigation: bool,
54    context: RequestContext,
55    accept_ch: bool,
56    referer: Option<&str>,
57) {
58    // 1. Client Hints (Sec-CH-UA)
59    // These headers provide granular version and platform information to the server.
60    if let Ok(val) = HeaderValue::from_str(&profile.headers.sec_ch_ua) {
61        headers.insert("sec-ch-ua", val);
62    }
63    headers.insert("sec-ch-ua-mobile", HeaderValue::from_static("?0"));
64    if let Ok(val) = HeaderValue::from_str(&profile.headers.sec_ch_ua_platform) {
65        headers.insert("sec-ch-ua-platform", val);
66    }
67    // Chrome only sends platform-version if explicitly solicited via Accept-CH in previous responses.
68    if accept_ch {
69        if let Ok(val) = HeaderValue::from_str(&profile.headers.sec_ch_ua_platform_version) {
70            headers.insert("sec-ch-ua-platform-version", val);
71        }
72    }
73
74    // 2. Navigation / Fetch metadata
75    headers.insert("upgrade-insecure-requests", HeaderValue::from_static("1"));
76    if let Ok(val) = HeaderValue::from_str(&profile.headers.user_agent) {
77        headers.insert(USER_AGENT, val);
78    }
79
80    // Inject dynamic sec-fetch-* state based on the current redirect context.
81    if let Ok(val) = HeaderValue::from_str(sec_fetch_site) {
82        headers.insert("sec-fetch-site", val);
83    }
84    let (mode, dest, accept_val) = match context {
85        RequestContext::Navigate | RequestContext::Form => ("navigate", "document", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"),
86        RequestContext::Iframe => ("navigate", "iframe", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"),
87        RequestContext::Xhr => ("cors", "empty", "*/*"),
88        RequestContext::NoCorsScript => ("no-cors", "script", "*/*"),
89        RequestContext::NoCorsStyle => ("no-cors", "style", "text/css,*/*;q=0.1"),
90        RequestContext::NoCorsImage => ("no-cors", "image", "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8"),
91        RequestContext::NoCorsFont => ("no-cors", "font", "*/*"),
92        RequestContext::NoCorsMedia => ("no-cors", "video", "*/*"),
93        RequestContext::Worker => ("same-origin", "worker", "*/*"),
94        RequestContext::ServiceWorker => ("same-origin", "serviceworker", "*/*"),
95        RequestContext::Prefetch => ("no-cors", "empty", "*/*"),
96    };
97    headers.insert(ACCEPT, HeaderValue::from_static(accept_val));
98    headers.insert("sec-fetch-mode", HeaderValue::from_static(mode));
99
100    // The 'sec-fetch-user' header is present ONLY on the first hop of a user-initiated navigation.
101    if is_initial_navigation && (context == RequestContext::Navigate || context == RequestContext::Form || context == RequestContext::Iframe) {
102        headers.insert("sec-fetch-user", HeaderValue::from_static("?1"));
103    }
104
105    headers.insert("sec-fetch-dest", HeaderValue::from_static(dest));
106
107    if let Some(r) = referer {
108        if let Ok(val) = HeaderValue::from_str(r) {
109            headers.insert(http::header::REFERER, val);
110        }
111    }
112
113    // 3. Compression & Language
114    let encoding = if profile.headers.zstd_encoding {
115        "gzip, deflate, br, zstd"
116    } else {
117        "gzip, deflate, br"
118    };
119    headers.insert(ACCEPT_ENCODING, HeaderValue::from_static(encoding));
120    if let Ok(val) = HeaderValue::from_str(&profile.headers.accept_language) {
121        headers.insert(ACCEPT_LANGUAGE, val);
122    }
123
124    // 4. Chrome Priority Header (u=0, i for navigations)
125    if profile.headers.include_priority_header {
126        headers.insert("priority", HeaderValue::from_static("u=0, i"));
127    }
128
129    // 5. HPACK "Never Index" (Sensitive) markers.
130    // Chrome explicitly marks cookies and auth headers as sensitive. This forces
131    // the HPACK encoder to use the "Literal Header Field Never Indexed" representation,
132    // which prevents these values from entering the dynamic table (CRIME mitigation).
133    for (name, value) in headers.iter_mut() {
134        if name == "cookie" || name == "authorization" {
135            value.set_sensitive(true);
136        }
137    }
138
139    // TODO(agent): Intelligent `:path` indexing.
140    // If the request path exceeds a certain entropy/length threshold (e.g., > 40 chars
141    // for unique REST API IDs), we should flag the `:path` pseudo-header as sensitive
142    // to prevent dynamic table bloat, matching Chrome's behavior. This requires a patch
143    // in the upstream `0x676e67/http2` fork to support `no_index` on pseudo-headers.
144}