1use chromiumoxide::cdp::browser_protocol::network::{CookieParam, TimeSinceEpoch};
11use std::fmt;
12use thiserror::Error;
13
14pub const MAX_COOKIES_FILE_BYTES: usize = 4 * 1024 * 1024;
16pub const MAX_COOKIES: usize = 10_000;
19
20#[derive(Clone, PartialEq, Eq)]
22struct SecretValue(String);
23
24impl fmt::Debug for SecretValue {
25 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26 f.write_str("<redacted>")
27 }
28}
29
30#[derive(Clone, PartialEq, Eq)]
35#[non_exhaustive]
36pub struct NetscapeCookie {
37 pub domain: String,
39 pub include_subdomains: bool,
41 pub path: String,
43 pub secure: bool,
44 pub http_only: bool,
46 pub expires: Option<i64>,
48 pub name: String,
49 value: SecretValue,
50}
51
52#[derive(Clone, Debug, PartialEq, Eq, Error)]
55#[error("the {field} field is empty or malformed")]
56#[non_exhaustive]
57pub struct CookieFieldError {
58 pub field: &'static str,
59}
60
61fn field_error(field: &'static str) -> CookieFieldError {
62 CookieFieldError { field }
63}
64
65pub(crate) fn domain_ok(domain: &str) -> bool {
68 !domain.is_empty()
69 && !domain.starts_with('#')
70 && !domain
71 .chars()
72 .any(|c| c.is_whitespace() || c.is_control() || matches!(c, '/' | '\\' | ';' | ','))
73}
74
75fn path_ok(path: &str) -> bool {
76 path.starts_with('/') && !path.chars().any(|c| c.is_control() || c == ';')
77}
78
79fn name_ok(name: &str) -> bool {
80 !name.is_empty() && !name.chars().any(|c| c.is_control() || c == ';' || c == '=')
81}
82
83fn value_ok(value: &str) -> bool {
84 !value.chars().any(|c| c.is_control())
85}
86
87impl NetscapeCookie {
88 pub fn value(&self) -> &str {
90 &self.value.0
91 }
92
93 pub fn new(domain: &str, name: &str, value: &str) -> Result<Self, CookieFieldError> {
103 let host = domain.trim();
104 let had_dot = host.starts_with('.');
105 let domain = host.trim_start_matches('.').to_ascii_lowercase();
106 if !domain_ok(&domain) {
107 return Err(field_error("domain"));
108 }
109 if !name_ok(name) {
110 return Err(field_error("name"));
111 }
112 if !value_ok(value) {
113 return Err(field_error("value"));
114 }
115 Ok(Self {
116 domain,
117 include_subdomains: had_dot,
118 path: "/".to_string(),
119 secure: false,
120 http_only: false,
121 expires: None,
122 name: name.to_string(),
123 value: SecretValue(value.to_string()),
124 })
125 }
126
127 #[must_use]
129 pub fn with_include_subdomains(mut self, include_subdomains: bool) -> Self {
130 self.include_subdomains = include_subdomains;
131 self
132 }
133
134 pub fn with_path(mut self, path: &str) -> Result<Self, CookieFieldError> {
136 if !path_ok(path) {
137 return Err(field_error("path"));
138 }
139 self.path = path.to_string();
140 Ok(self)
141 }
142
143 #[must_use]
144 pub fn with_secure(mut self, secure: bool) -> Self {
145 self.secure = secure;
146 self
147 }
148
149 #[must_use]
150 pub fn with_http_only(mut self, http_only: bool) -> Self {
151 self.http_only = http_only;
152 self
153 }
154
155 pub fn with_expires(mut self, expires: Option<i64>) -> Result<Self, CookieFieldError> {
158 if matches!(expires, Some(e) if e <= 0) {
159 return Err(field_error("expires"));
160 }
161 self.expires = expires;
162 Ok(self)
163 }
164
165 #[cfg_attr(not(feature = "cookie-export"), allow(dead_code))]
168 pub(crate) fn invalid_field(&self) -> Option<&'static str> {
169 if !domain_ok(&self.domain) {
170 Some("domain")
171 } else if !path_ok(&self.path) {
172 Some("path")
173 } else if !name_ok(&self.name) {
174 Some("name")
175 } else if !value_ok(&self.value.0) {
176 Some("value")
177 } else if matches!(self.expires, Some(e) if e <= 0) {
178 Some("expires")
179 } else {
180 None
181 }
182 }
183}
184
185impl fmt::Debug for NetscapeCookie {
186 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187 f.debug_struct("NetscapeCookie")
188 .field("domain", &self.domain)
189 .field("include_subdomains", &self.include_subdomains)
190 .field("path", &self.path)
191 .field("secure", &self.secure)
192 .field("http_only", &self.http_only)
193 .field("expires", &self.expires)
194 .field("name", &self.name)
195 .field("value", &self.value)
196 .finish()
197 }
198}
199
200#[derive(Clone, Debug, PartialEq, Eq, Error)]
203#[non_exhaustive]
204pub enum CookieParseError {
205 #[error("cookies file is {bytes} bytes; the limit is {limit}")]
206 InputTooLarge { bytes: usize, limit: usize },
207 #[error("cookies file holds more than {limit} cookies")]
208 TooManyCookies { limit: usize },
209 #[error("line {line}: expected 7 tab-separated fields, found {found}")]
210 BadFieldCount { line: usize, found: usize },
211 #[error("line {line}: the {field} field must be TRUE or FALSE")]
212 BadFlag { line: usize, field: &'static str },
213 #[error("line {line}: the expiry field must be a non-negative integer")]
214 BadExpires { line: usize },
215 #[error("line {line}: the {field} field is empty or malformed")]
216 BadField { line: usize, field: &'static str },
217}
218
219const HTTP_ONLY_PREFIX: &str = "#HttpOnly_";
220
221fn parse_flag(raw: &str, line: usize, field: &'static str) -> Result<bool, CookieParseError> {
222 if raw.eq_ignore_ascii_case("TRUE") {
223 Ok(true)
224 } else if raw.eq_ignore_ascii_case("FALSE") {
225 Ok(false)
226 } else {
227 Err(CookieParseError::BadFlag { line, field })
228 }
229}
230
231fn bad_field(line: usize, field: &'static str) -> CookieParseError {
232 CookieParseError::BadField { line, field }
233}
234
235pub fn parse_netscape(text: &str) -> Result<Vec<NetscapeCookie>, CookieParseError> {
243 if text.len() > MAX_COOKIES_FILE_BYTES {
244 return Err(CookieParseError::InputTooLarge {
245 bytes: text.len(),
246 limit: MAX_COOKIES_FILE_BYTES,
247 });
248 }
249 let text = text.strip_prefix('\u{feff}').unwrap_or(text);
250 let mut out = Vec::new();
251 for (idx, raw_line) in text.split('\n').enumerate() {
252 let line_no = idx + 1;
253 let line = raw_line.strip_suffix('\r').unwrap_or(raw_line);
254 if line.trim().is_empty() {
255 continue;
256 }
257 let (line, http_only) = match line.strip_prefix(HTTP_ONLY_PREFIX) {
258 Some(rest) => (rest, true),
259 None if line.starts_with('#') => continue,
260 None => (line, false),
261 };
262 let fields: Vec<&str> = line.split('\t').collect();
263 if fields.len() != 7 {
264 return Err(CookieParseError::BadFieldCount {
265 line: line_no,
266 found: fields.len(),
267 });
268 }
269 if out.len() >= MAX_COOKIES {
270 return Err(CookieParseError::TooManyCookies { limit: MAX_COOKIES });
271 }
272 let host = fields[0].trim();
273 let had_dot = host.starts_with('.');
274 let domain = host.trim_start_matches('.').to_ascii_lowercase();
275 if !domain_ok(&domain) {
276 return Err(bad_field(line_no, "domain"));
277 }
278 let flag = parse_flag(fields[1].trim(), line_no, "include-subdomains")?;
279 let path = match fields[2] {
280 "" => "/".to_string(),
281 p if path_ok(p) => p.to_string(),
282 _ => return Err(bad_field(line_no, "path")),
283 };
284 let secure = parse_flag(fields[3].trim(), line_no, "secure")?;
285 let expires = match fields[4].trim().parse::<i64>() {
286 Ok(0) => None,
287 Ok(n) if n > 0 => Some(n),
288 _ => return Err(CookieParseError::BadExpires { line: line_no }),
289 };
290 let name = fields[5];
291 if !name_ok(name) {
292 return Err(bad_field(line_no, "name"));
293 }
294 let value = fields[6];
295 if !value_ok(value) {
296 return Err(bad_field(line_no, "value"));
297 }
298 out.push(NetscapeCookie {
299 domain,
300 include_subdomains: flag || had_dot,
301 path,
302 secure,
303 http_only,
304 expires,
305 name: name.to_string(),
306 value: SecretValue(value.to_string()),
307 });
308 }
309 Ok(out)
310}
311
312pub(crate) fn to_cdp_params(cookies: &[NetscapeCookie]) -> Vec<CookieParam> {
316 cookies
317 .iter()
318 .map(|c| {
319 let mut p = CookieParam::new(c.name.clone(), c.value().to_string());
320 p.domain = Some(if c.include_subdomains {
321 format!(".{}", c.domain)
322 } else {
323 c.domain.clone()
324 });
325 p.path = Some(c.path.clone());
326 p.secure = Some(c.secure);
327 p.http_only = Some(c.http_only);
328 p.expires = c.expires.map(|e| TimeSinceEpoch::new(e as f64));
329 p
330 })
331 .collect()
332}
333
334pub(crate) fn admission_detail(cookies: &[NetscapeCookie]) -> String {
337 let mut domains: Vec<&str> = cookies.iter().map(|c| c.domain.as_str()).collect();
338 domains.sort_unstable();
339 domains.dedup();
340 format!(
341 "import_cookies count={} domains={}",
342 cookies.len(),
343 domains.join(",")
344 )
345}
346
347pub(crate) fn scrub(message: &str, cookies: &[NetscapeCookie]) -> String {
350 let mut out = message.to_string();
351 for c in cookies {
352 let v = c.value();
353 if v.chars().count() >= 4 {
354 out = out.replace(v, "[redacted]");
355 }
356 }
357 out
358}