1
Fork 0
mirror of https://github.com/thegeneralist01/archivr synced 2026-12-04 18:56:44 +01:00

fix: handle __Host- cookies correctly for single-file captures

Chrome's CDP Network.setCookies rejects __Host- prefixed cookies that
carry a domain attribute — the prefix semantically forbids domain binding.
The previous Netscape cookie file always emitted a domain column, causing
setCookies to fail with "Invalid cookie fields" and the capture to
produce no output file.

Switch single-file's cookie file to JSON format (single-file tries
JSON.parse first, falls back to Netscape text parsing). JSON gives
per-cookie field control:

- __Host- cookies: {url, path: "/", secure: true}, no domain field.
  url is the https page URL (synthesised as https://hostname/ when the
  page URL is non-https, since __Host- requires https anyway).
- __Secure- cookies: {domain, path: "/", secure: true}.
- All other cookies: {domain, path: "/"} — unchanged behaviour.

yt-dlp still receives the existing Netscape file; only the single-file
path is affected.

Add four unit tests covering __Host-, __Secure-, regular cookies, and
the http→https url fallback.
This commit is contained in:
TheGeneralist 2026-10-12 20:00:06 +02:00
parent e40312734d
commit 2115a70343
Signed by: thegeneralist01
SSH key fingerprint: SHA256:pp9qddbCNmVNoSjevdvQvM5z0DHN7LTa8qBMbcMq/R4
2 changed files with 172 additions and 3 deletions

View file

@ -1,4 +1,5 @@
use std::{collections::HashMap, io::Write, path::Path}; use std::{collections::HashMap, io::Write, path::Path};
use serde_json::json;
/// Writes a Netscape-format HTTP cookie file suitable for yt-dlp `--cookies` and /// Writes a Netscape-format HTTP cookie file suitable for yt-dlp `--cookies` and
/// single-file `--browser-cookies-file`. The file is created with mode 0o600 /// single-file `--browser-cookies-file`. The file is created with mode 0o600
@ -38,6 +39,84 @@ pub fn write_netscape_cookie_file(
Ok(()) Ok(())
} }
/// Writes a JSON-format cookie file for single-file `--browser-cookies-file`.
///
/// Single-file accepts both Netscape text and JSON; JSON gives us per-cookie
/// field control, which is required for `__Host-`/`__Secure-` cookies.
///
/// - `__Host-` cookies: Chrome CDP `Network.setCookies` rejects these when a
/// `domain` attribute is present. They must be set via `url` (no `domain`),
/// `path: "/"`, and `secure: true`.
/// - `__Secure-` cookies: require `secure: true`; `domain` is still fine.
/// - All other cookies: use `domain` as before; `secure` left false because
/// we have no per-cookie scheme information from the user's input map.
///
/// The file is created 0o600 (owner read/write only) to protect cookie secrets.
pub fn write_json_cookie_file(
cookies: &HashMap<String, String>,
domain: &str,
page_url: &str,
path: &Path,
) -> std::io::Result<()> {
#[cfg(unix)]
let mut f = {
use std::os::unix::fs::OpenOptionsExt;
std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.mode(0o600)
.open(path)?
};
#[cfg(not(unix))]
let mut f = std::fs::File::create(path)?;
// Build a canonical https root URL for __Host- cookies (must be https).
// If the page_url itself is https we use it directly; otherwise synthesise one.
let host_url = if page_url.starts_with("https://") {
page_url.to_string()
} else {
format!("https://{}/", domain)
};
let entries: Vec<serde_json::Value> = cookies
.iter()
.map(|(name, value)| {
if name.starts_with("__Host-") {
// No `domain` field — Chrome rejects __Host- cookies that carry one.
json!({
"name": name,
"value": value,
"url": host_url,
"path": "/",
"secure": true
})
} else if name.starts_with("__Secure-") {
json!({
"name": name,
"value": value,
"domain": domain,
"path": "/",
"secure": true
})
} else {
json!({
"name": name,
"value": value,
"domain": domain,
"path": "/"
})
}
})
.collect();
let json_str = serde_json::to_string(&entries)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
f.write_all(json_str.as_bytes())?;
Ok(())
}
/// Extracts the exact hostname from a URL, suitable for use as the Netscape /// Extracts the exact hostname from a URL, suitable for use as the Netscape
/// cookie domain. /// cookie domain.
/// ///
@ -64,3 +143,93 @@ pub fn cookies_to_header(cookies: &HashMap<String, String>) -> String {
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join("; ") .join("; ")
} }
#[cfg(test)]
mod tests {
use super::*;
use tempfile::NamedTempFile;
fn read_json(f: &NamedTempFile) -> Vec<serde_json::Value> {
let s = std::fs::read_to_string(f.path()).unwrap();
serde_json::from_str(&s).unwrap()
}
#[test]
fn host_prefix_cookie_has_no_domain_uses_url() {
let mut cookies = HashMap::new();
cookies.insert("__Host-session".to_string(), "abc123".to_string());
let f = NamedTempFile::new().unwrap();
write_json_cookie_file(
&cookies,
"example.com",
"https://example.com/page",
f.path(),
)
.unwrap();
let entries = read_json(&f);
assert_eq!(entries.len(), 1);
let c = &entries[0];
assert_eq!(c["name"], "__Host-session");
assert_eq!(c["value"], "abc123");
assert!(c.get("domain").is_none(), "__Host- must not have domain field");
assert_eq!(c["url"], "https://example.com/page");
assert_eq!(c["path"], "/");
assert_eq!(c["secure"], true);
}
#[test]
fn secure_prefix_cookie_has_domain_and_secure_true() {
let mut cookies = HashMap::new();
cookies.insert("__Secure-token".to_string(), "xyz".to_string());
let f = NamedTempFile::new().unwrap();
write_json_cookie_file(
&cookies,
"example.com",
"https://example.com/",
f.path(),
)
.unwrap();
let entries = read_json(&f);
let c = &entries[0];
assert_eq!(c["domain"], "example.com");
assert_eq!(c["secure"], true);
assert!(c.get("url").is_none(), "__Secure- should not carry url field");
}
#[test]
fn regular_cookie_uses_domain_no_secure() {
let mut cookies = HashMap::new();
cookies.insert("cf_bm".to_string(), "val".to_string());
let f = NamedTempFile::new().unwrap();
write_json_cookie_file(
&cookies,
"example.com",
"https://example.com/",
f.path(),
)
.unwrap();
let entries = read_json(&f);
let c = &entries[0];
assert_eq!(c["domain"], "example.com");
assert!(c.get("secure").map(|v| v != true).unwrap_or(true), "regular cookie should not be forced secure");
assert!(c.get("url").is_none());
}
#[test]
fn host_prefix_falls_back_to_https_url_when_page_url_is_http() {
let mut cookies = HashMap::new();
cookies.insert("__Host-x".to_string(), "1".to_string());
let f = NamedTempFile::new().unwrap();
write_json_cookie_file(
&cookies,
"marketing.creativedirector.net",
"http://marketing.creativedirector.net/course",
f.path(),
)
.unwrap();
let entries = read_json(&f);
let c = &entries[0];
assert!(c["url"].as_str().unwrap().starts_with("https://"), "must use https url for __Host- even when page is http");
assert!(c.get("domain").is_none());
}
}

View file

@ -10,7 +10,7 @@ use std::{
process::Command, process::Command,
}; };
use crate::downloader::cookies::{domain_from_url, write_netscape_cookie_file}; use crate::downloader::cookies::{domain_from_url, write_json_cookie_file};
use crate::hash::hash_file; use crate::hash::hash_file;
/// Combined reader-mode script: Readability.js (Apache 2.0) bundled with the /// Combined reader-mode script: Readability.js (Apache 2.0) bundled with the
@ -611,9 +611,9 @@ fn save_with(
// Write cookie file (secrets must never appear in process args). // Write cookie file (secrets must never appear in process args).
let cookie_file: Option<PathBuf> = if !cookies.is_empty() { let cookie_file: Option<PathBuf> = if !cookies.is_empty() {
let cf = temp_dir.join("cookies.txt"); let cf = temp_dir.join("cookies.json");
let domain = domain_from_url(url); let domain = domain_from_url(url);
write_netscape_cookie_file(cookies, &domain, &cf) write_json_cookie_file(cookies, &domain, url, &cf)
.context("failed to write single-file cookie file")?; .context("failed to write single-file cookie file")?;
Some(cf) Some(cf)
} else { } else {