misterdownloadmanager: The ultimate open-source, clean-room download manager written from scratch in pure Rust for Windows, Mac, and Linux
Rust bittorrent-clientdebriddownload-acceleratordownload-managerdownloadmanagereguifile-downloadergallery-dlidmidm-alternativeinternet-download-managerm3u8-downloadermagnetplaylist-downloaderreal-debridrusttorrent-clientvideo-downloaderyoutube-downloaderyt-dlp
Video cookies: each one for its own domain, so YouTube Music's sign-in reaches www.youtube.com (#272)
Ahmed Nefzaoui134e590be8e6
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5be43d85..d17d10f4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -587,6 +587,14 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see### Fixed+- **Signed-in videos from YouTube Music and YouTube's mobile site**+ ([#229](https://github.com/anefzaoui/misterdownloadmanager/issues/229)): the button over a+ video on music.youtube.com or m.youtube.com passed the page's cookies for that host only, while+ yt-dlp asks www.youtube.com, so the sign-in didn't reach it. The extension now sends each+ cookie with the domain the browser keeps it for, and MDM gives yt-dlp each one for that domain:+ youtube.com's sign-in reaches every YouTube host, and a host's own cookie stays with that host.+ With an older extension, a YouTube page's cookies (or a site's mobile page's, m. and mobile.)+ go to the whole site.- **Update now finds the Linux and macOS files by either name**: a release's AppImage, .deb,.rpm, .tar.gz and .dmg were named `…-experimental`; MDM now looks for the name without itfirst and still takes the older one, so Update now keeps working whichever a release uses.diff --git a/ROADMAP.md b/ROADMAP.mdindex facca37f..c2866029 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -61,6 +61,9 @@ Everything below ships together, in one release, as version 0.3.0.([#192](https://github.com/anefzaoui/misterdownloadmanager/issues/192))- ✅ A menu of the menu bar shut with Escape opens again at the first click on its title (onLinux it took two; on Windows, Escape with the pointer on the title left the menu open)+- ✅ Signed-in videos from YouTube Music and YouTube's mobile site: the browser's cookies reach+ the YouTube host yt-dlp asks, each for the domain the browser keeps it for+ ([#229](https://github.com/anefzaoui/misterdownloadmanager/issues/229))- ✅ Cookies for video sites: yt-dlp can read a browser's cookies on this computer (Firefox,Chrome, Edge, Brave, Opera, Vivaldi, Chromium, Whale; Safari on macOS), so a pasted YouTubelink that asks to "confirm you're not a bot" works when you're signed in there; and the buttondiff --git a/crates/app/src/videodlg.rs b/crates/app/src/videodlg.rsindex c816d590..7d334003 100644--- a/crates/app/src/videodlg.rs+++ b/crates/app/src/videodlg.rs@@ -1021,6 +1021,7 @@ pub fn from_browser(c: &mdm_ipc::Command) -> mdm_tools::proc::FromBrowser {referer: c.referer.clone(),user_agent: c.user_agent.clone(),cookies: c.cookies.clone(),+ jar: c.cookie_jar.clone(),}}diff --git a/crates/ipc/src/lib.rs b/crates/ipc/src/lib.rsindex 65ffc9f8..56f0a135 100644--- a/crates/ipc/src/lib.rs+++ b/crates/ipc/src/lib.rs@@ -35,6 +35,12 @@ pub struct Command {/// From the browser: request context to reuse.pub referer: Option<String>,pub cookies: Option<String>,+ /// From the browser: the same cookies, each with the domain, path and flags the browser+ /// keeps for it, for yt-dlp's cookie file. yt-dlp may ask another host than the page's (a+ /// YouTube Music page is looked up on www.youtube.com), and a cookie of `.youtube.com` goes+ /// there too. An older extension sends `cookies` only.+ #[serde(skip_serializing_if = "Vec::is_empty")]+ pub cookie_jar: Vec<BrowserCookie>,pub user_agent: Option<String>,/// From the browser: where its redirects from `url` ended (`url` stays the address asked/// for, so an expired signed link can be renewed from it).@@ -107,6 +113,26 @@ pub struct Command {pub exclude_site: Option<String>,}+/// One cookie as the browser keeps it (`cookies.getAll`'s fields, under the extension's names+/// too: `hostOnly`, `expirationDate`).+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]+#[serde(default)]+pub struct BrowserCookie {+ pub name: String,+ pub value: String,+ /// `.youtube.com` (sent to its subdomains too) or a host name.+ pub domain: String,+ /// Sent to `domain` itself only, never its subdomains.+ #[serde(alias = "hostOnly")]+ pub host_only: bool,+ pub path: String,+ /// Sent over HTTPS only.+ pub secure: bool,+ /// When it expires, in seconds since 1970; none: when the browser closes.+ #[serde(alias = "expirationDate")]+ pub expires: Option<f64>,+}+impl Command {/// Asks for an answer (a JSON line) rather than "ok".pub fn wants_reply(&self) -> bool {diff --git a/crates/labserver/src/server.rs b/crates/labserver/src/server.rsindex 130a8a86..59483621 100644--- a/crates/labserver/src/server.rs+++ b/crates/labserver/src/server.rs@@ -70,6 +70,10 @@ pub struct LogEntry {/// The `Cookie` header, to check credentials don't follow cross-host redirects.#[serde(default)]pub cookie: Option<String>,+ /// The `Host` header: which host a request through the lab as an HTTP proxy was for (its+ /// absolute address, `GET http://www.youtube.com/…`, routed by its path like any other).+ #[serde(default)]+ pub host: Option<String>,/// The `Authorization` header, never in full: its scheme and first 4 characters ("Bearer/// good…"), to check a service token reaches its API only (#44).#[serde(default)]@@ -263,6 +267,7 @@ impl Shared {if_range: header_str(headers, header::IF_RANGE),user_agent: header_str(headers, header::USER_AGENT),cookie: header_str(headers, header::COOKIE),+ host: header_str(headers, header::HOST),authorization: header_str(headers, header::AUTHORIZATION).map(|a| a.chars().take(11).collect::<String>() + "…"),referer: header_str(headers, header::REFERER),diff --git a/crates/nmhost/src/main.rs b/crates/nmhost/src/main.rsindex b796c741..ed61617a 100644--- a/crates/nmhost/src/main.rs+++ b/crates/nmhost/src/main.rs@@ -63,6 +63,9 @@ struct Message {url: String,referrer: Option<String>,cookies: Option<String>,+ /// The same cookies with their domains and flags (`mdm_ipc::Command::cookie_jar`); an older+ /// extension sends none.+ cookie_jar: Vec<mdm_ipc::BrowserCookie>,user_agent: Option<String>,/// `navigator.userAgentData` brands: Brave and Opera name themselves there, not in the/// User-Agent; Firefox's forks add the name `runtime.getBrowserInfo` gives ("Zen").@@ -416,6 +419,7 @@ fn video_command(video_page: Some(src.unwrap_or_else(|| m.url.clone())),referer,cookies: m.cookies.clone().filter(|c| !c.is_empty()),+ cookie_jar: m.cookie_jar.clone(),user_agent: m.user_agent.clone(),private: m.private,..Default::default()@@ -496,6 +500,7 @@ fn to_command(m: Message) -> mdm_ipc::Command {name,referer: some(m.referrer),cookies: some(m.cookies),+ cookie_jar: m.cookie_jar,user_agent: m.user_agent,size: m.size.filter(|s| *s > 0),mime: some(m.mime),@@ -1079,6 +1084,13 @@ mod tests {url: "https://www.quiet.test/watch".into(),src: Some("https://cdn.test/v/master.m3u8?t=1".into()),cookies: Some("cdn=1".into()),+ cookie_jar: vec![mdm_ipc::BrowserCookie {+ name: "cdn".into(),+ value: "1".into(),+ domain: ".cdn.test".into(),+ path: "/".into(),+ ..Default::default()+ }],user_agent: Some(ua.into()),..Default::default()};@@ -1089,6 +1101,10 @@ mod tests {);assert_eq!(cmd.referer.as_deref(), Some("https://www.quiet.test/watch"));assert_eq!(cmd.cookies.as_deref(), Some("cdn=1"));+ assert_eq!(+ cmd.cookie_jar, listed.cookie_jar,+ "each cookie with its domain"+ );assert_eq!(cmd.user_agent.as_deref(), Some(ua));// Never a page that isn't on the web.let local = Message {@@ -1316,6 +1332,52 @@ mod tests {);}+ /// The extension's cookies with their domains, as `cookies.getAll` names them (its other+ /// fields ignored), reach the app; an older extension's message has none.+ #[test]+ fn cookies_keep_their_domains() {+ let m: Message = serde_json::from_str(+ r#"{"url":"https://music.youtube.com/watch?v=x","cookies":"SID=1; pref=2","userAgent":"UA",+ "cookieJar":[{"name":"SID","value":"1","domain":".youtube.com","hostOnly":false,"path":"/","secure":true,"httpOnly":true,"sameSite":"lax","session":false,"expirationDate":1893456000.5,"storeId":"0"},+ {"name":"pref","value":"2","domain":"music.youtube.com","hostOnly":true,"path":"/","secure":false,"session":true}]}"#,+ )+ .unwrap();+ let c = to_command(m);+ assert_eq!(c.cookies.as_deref(), Some("SID=1; pref=2"));+ assert_eq!(+ c.cookie_jar,+ [+ mdm_ipc::BrowserCookie {+ name: "SID".into(),+ value: "1".into(),+ domain: ".youtube.com".into(),+ host_only: false,+ path: "/".into(),+ secure: true,+ expires: Some(1893456000.5),+ },+ mdm_ipc::BrowserCookie {+ name: "pref".into(),+ value: "2".into(),+ domain: "music.youtube.com".into(),+ host_only: true,+ path: "/".into(),+ secure: false,+ expires: None,+ },+ ]+ );+ // To the app and back (its command line): the same.+ let line = serde_json::to_string(&c).unwrap();+ let back: mdm_ipc::Command = serde_json::from_str(&line).unwrap();+ assert_eq!(back.cookie_jar, c.cookie_jar);+ let old: Message =+ serde_json::from_str(r#"{"url":"https://x/a.zip","cookies":"a=1"}"#).unwrap();+ let c = to_command(old);+ assert!(c.cookie_jar.is_empty());+ assert!(!serde_json::to_string(&c).unwrap().contains("cookie_jar"));+ }+#[test]fn message_to_command() {let m: Message = serde_json::from_str(diff --git a/crates/tools/src/proc.rs b/crates/tools/src/proc.rsindex eae5cca9..edc2537f 100644--- a/crates/tools/src/proc.rs+++ b/crates/tools/src/proc.rs@@ -280,13 +280,15 @@ pub fn safe(s: &str) -> Result<&str, ProcError> {}/// What the browser's request for a page carried, so yt-dlp asks as the browser did: the page-/// that embeds a player (Referer), the browser's User-Agent, and the page's cookies (a Cookie-/// header's `name=value; …`), which sign a member's or a site's own videos in.+/// that embeds a player (Referer), the browser's User-Agent, and the page's cookies, which sign a+/// member's or a site's own videos in: each with its domain and flags (`jar`), or, from an older+/// extension, a Cookie header's `name=value; …` (`cookies`).#[derive(Clone, Debug, Default)]pub struct FromBrowser {pub referer: Option<String>,pub user_agent: Option<String>,pub cookies: Option<String>,+ pub jar: Vec<mdm_ipc::BrowserCookie>,}/// A private cookie file in the Netscape format yt-dlp's `--cookies` reads, removed when@@ -316,10 +318,14 @@ impl FromBrowser {let host = url::Url::parse(url).ok().and_then(|u| u.host_str().map(str::to_owned));- let file = match (given(&self.cookies), host) {- (Some(cookies), Some(host)) => {- let file = cookie_file(&host, cookies)- .map_err(|e| ProcError::Start("yt-dlp".into(), e))?;+ let text = match (given(&self.cookies), host) {+ _ if !self.jar.is_empty() => Some(jar_cookies(&self.jar)),+ (Some(cookies), Some(host)) => Some(header_cookies(&host, cookies)),+ _ => None,+ };+ let file = match text {+ Some(text) => {+ let file = cookie_file(&text).map_err(|e| ProcError::Start("yt-dlp".into(), e))?;args.extend(["--cookies".to_owned(),file.0.to_string_lossy().into_owned(),@@ -332,9 +338,99 @@ impl FromBrowser {}}-/// `cookies` (`a=1; b=2`) for `host` and its subdomains, as session cookies, in a file only this-/// user can read.-fn cookie_file(host: &str, cookies: &str) -> std::io::Result<CookieFile> {+/// The first line of a cookie file in the Netscape format (yt-dlp's `--cookies`). Each cookie is+/// a line: domain, sent to its subdomains too (TRUE, FALSE), path, HTTPS only (TRUE, FALSE),+/// expiry (seconds since 1970; 0: a session cookie), name, value, separated by tabs.+const NETSCAPE: &str = "# Netscape HTTP Cookie File\n";++/// Can `s` go in a cookie file's field (no tab or line break to shift the others)?+fn field(s: &str) -> bool {+ !s.contains(['\t', '\r', '\n', '\0'])+}++/// The browser's cookies (`cookies.getAll`'s), each for its own domain, path and flags: yt-dlp+/// sends a cookie of `.youtube.com` to www.youtube.com when the page was music.youtube.com, and+/// one of the page's host alone to that host only.+fn jar_cookies(jar: &[mdm_ipc::BrowserCookie]) -> String {+ let flag = |b: bool| if b { "TRUE" } else { "FALSE" };+ let mut text = String::from(NETSCAPE);+ for c in jar {+ let host = c.domain.trim_start_matches('.');+ let usable = !c.name.is_empty()+ && !host.is_empty()+ && !host.contains([' ', '/'])+ && [&c.name, &c.value, &c.domain, &c.path]+ .iter()+ .all(|s| field(s));+ if !usable {+ continue;+ }+ let domain = if c.host_only {+ host.to_owned()+ } else {+ format!(".{host}")+ };+ let path = if c.path.starts_with('/') {+ c.path.as_str()+ } else {+ "/"+ };+ let expires = c+ .expires+ .filter(|e| e.is_finite() && *e >= 1.0)+ .map_or(0, |e| e as u64);+ text.push_str(&format!(+ "{domain}\t{}\t{path}\t{}\t{expires}\t{}\t{}\n",+ flag(!c.host_only),+ flag(c.secure),+ c.name,+ c.value+ ));+ }+ text+}++/// An older extension's Cookie header (`a=1; b=2`, the page's cookies without their domains),+/// for the site's domain and its subdomains ([`header_domain`]), as session cookies.+fn header_cookies(host: &str, cookies: &str) -> String {+ let domain = header_domain(host);+ let mut text = String::from(NETSCAPE);+ for pair in cookies.split(';') {+ let Some((name, value)) = pair.trim().split_once('=') else {+ continue;+ };+ if ![domain, name, value].iter().all(|s| field(s)) {+ continue;+ }+ text.push_str(&format!(".{domain}\tTRUE\t/\tFALSE\t0\t{name}\t{value}\n"));+ }+ text+}++/// Where a page's cookies without their domains go: its host, or the site's own domain where+/// yt-dlp asks another of its hosts. Every YouTube host (music., m., www.: yt-dlp looks videos+/// up on www.youtube.com, and the sign-in cookies are `.youtube.com`'s), and a site's mobile+/// pages (m., mobile.), whose sign-in is the site's.+fn header_domain(host: &str) -> &str {+ let host = host.trim_end_matches('.');+ let youtube = "youtube.com";+ let lower = host.to_ascii_lowercase();+ if lower == youtube || lower.ends_with(".youtube.com") {+ return &host[host.len() - youtube.len()..];+ }+ for mobile in ["m.", "mobile."] {+ if let Some(site) = host.strip_prefix(mobile)+ && site.contains('.')+ {+ return site;+ }+ }+ host+}++/// A cookie file's `text` ([`jar_cookies`], [`header_cookies`]) in a file only this user can+/// read.+fn cookie_file(text: &str) -> std::io::Result<CookieFile> {use std::io::Write;use std::sync::atomic::{AtomicU64, Ordering};static N: AtomicU64 = AtomicU64::new(0);@@ -343,19 +439,6 @@ fn cookie_file(host: &str, cookies: &str) -> std::io::Result<CookieFile> {std::process::id(),N.fetch_add(1, Ordering::Relaxed)));- let mut text = String::from("# Netscape HTTP Cookie File\n");- for pair in cookies.split(';') {- let Some((name, value)) = pair.trim().split_once('=') else {- continue;- };- if [host, name, value]- .iter()- .any(|s| s.contains(['\t', '\r', '\n', '\0']))- {- continue;- }- text.push_str(&format!(".{host}\tTRUE\t/\tFALSE\t0\t{name}\t{value}\n"));- }let mut open = std::fs::OpenOptions::new();open.write(true).create_new(true);// The temporary folder is the user's own on Windows; elsewhere it may be shared.@@ -637,6 +720,7 @@ mod tests {referer: Some("https://course.test/lesson".into()),user_agent: Some("UA/1".into()),cookies: Some("sid=abc; theme=dark".into()),+ ..Default::default()};let (args, file) = b.args("https://player.test/video/1").unwrap();assert_eq!(@@ -666,9 +750,11 @@ mod tests {/// #229: the button over a YouTube video sends the watch page (its player plays a blob:, and/// a video's own requests aren't a manifest) with the cookies the browser has for that page:- /// youtube.com's sign-in, `__Secure-` ones included. They are filed for www.youtube.com and- /// its subdomains, the host yt-dlp's YouTube extractor asks (and checks the sign-in on), as- /// session cookies (expiry 0, which yt-dlp's loader keeps) sent over HTTP and HTTPS.+ /// youtube.com's sign-in, `__Secure-` ones included. An older extension sends them as a+ /// header, without their domains: they are filed for youtube.com and its subdomains, so they+ /// reach www.youtube.com, the host yt-dlp's YouTube extractor asks (and checks the sign-in+ /// on), from a YouTube Music or mobile page too; as session cookies (expiry 0, which+ /// yt-dlp's loader keeps) sent over HTTP and HTTPS.#[test]fn a_youtube_pages_cookies_reach_the_host_ytdlp_asks() {let b = FromBrowser {@@ -693,10 +779,110 @@ mod tests {("LOGIN_INFO", "AFmmF2s:QUQ3"),("__Host-GAPS", "1:g"),] {- let line = format!(".www.youtube.com\tTRUE\t/\tFALSE\t0\t{name}\t{value}\n");+ let line = format!(".youtube.com\tTRUE\t/\tFALSE\t0\t{name}\t{value}\n");assert!(text.contains(&line), "{line:?} in {text}");}assert_eq!(text.lines().count(), 7, "the header and six cookies");+ for page in [+ "https://music.youtube.com/watch?v=A1WG3x-Ebpk",+ "https://m.youtube.com/watch?v=A1WG3x-Ebpk",+ "https://youtube.com/shorts/A1WG3x-Ebpk",+ ] {+ let (_, file) = b.args(page).unwrap();+ let text = std::fs::read_to_string(&file.unwrap().0).unwrap();+ assert!(+ text.contains(".youtube.com\tTRUE\t/\tFALSE\t0\tSAPISID\ts/1\n"),+ "{page}: {text}"+ );+ }+ }++ /// The domain an older extension's header is filed under: the page's host, or its site's+ /// where yt-dlp asks another of the site's hosts.+ #[test]+ fn a_header_goes_to_the_sites_own_domain() {+ for (host, domain) in [+ ("www.youtube.com", "youtube.com"),+ ("music.youtube.com", "youtube.com"),+ ("m.youtube.com", "youtube.com"),+ ("youtube.com", "youtube.com"),+ ("Music.YouTube.com.", "YouTube.com"),+ ("m.facebook.com", "facebook.com"),+ ("mobile.twitter.com", "twitter.com"),+ ("m.vk.com", "vk.com"),+ ("player.test", "player.test"),+ ("www.example.org", "www.example.org"),+ ("notyoutube.com", "notyoutube.com"),+ ("youtube.com.evil.test", "youtube.com.evil.test"),+ ("m.org", "m.org"),+ ("127.0.0.1", "127.0.0.1"),+ ] {+ assert_eq!(header_domain(host), domain, "{host}");+ }+ }++ fn cookie(name: &str, domain: &str, host_only: bool) -> mdm_ipc::BrowserCookie {+ mdm_ipc::BrowserCookie {+ name: name.into(),+ value: format!("{name}-v"),+ domain: domain.into(),+ host_only,+ path: "/".into(),+ ..Default::default()+ }+ }++ /// A newer extension sends each cookie with the domain, path and flags the browser keeps: the+ /// file has each as it is (a host's own cookie for that host alone, a site's for its+ /// subdomains too), and the header, sent for older apps, is left out.+ #[test]+ fn each_cookie_keeps_its_domain_and_flags() {+ let b = FromBrowser {+ cookies: Some("SID=SID-v; pref=pref-v".into()),+ jar: vec![+ mdm_ipc::BrowserCookie {+ secure: true,+ expires: Some(1893456000.75),+ path: "/".into(),+ ..cookie("SID", ".youtube.com", false)+ },+ cookie("pref", "music.youtube.com", true),+ // Without a leading dot, as Firefox may name a domain cookie.+ mdm_ipc::BrowserCookie {+ path: "/account".into(),+ ..cookie("acct", "youtube.com", false)+ },+ // A path that isn't one: the whole site.+ mdm_ipc::BrowserCookie {+ path: "account".into(),+ ..cookie("odd", "youtube.com", true)+ },+ // Never a field that would shift the others, an empty name or domain.+ cookie("tab\tname", ".youtube.com", false),+ mdm_ipc::BrowserCookie {+ value: "a\nb".into(),+ ..cookie("line", ".youtube.com", false)+ },+ cookie("", ".youtube.com", false),+ cookie("nodomain", "", false),+ cookie("dots", "...", false),+ cookie("slash", "youtube.com/x", false),+ ],+ ..Default::default()+ };+ let (args, file) = b.args("https://music.youtube.com/watch?v=x").unwrap();+ assert_eq!(args[0], "--cookies");+ let text = std::fs::read_to_string(&file.unwrap().0).unwrap();+ assert_eq!(+ text,+ "# Netscape HTTP Cookie File\n\+ .youtube.com\tTRUE\t/\tTRUE\t1893456000\tSID\tSID-v\n\+ music.youtube.com\tFALSE\t/\tFALSE\t0\tpref\tpref-v\n\+ .youtube.com\tTRUE\t/account\tFALSE\t0\tacct\tacct-v\n\+ youtube.com\tFALSE\t/\tFALSE\t0\todd\todd-v\n"+ );+ // A page with no address of its own (none parsed) still gets the jar's.+ assert!(b.args("not a url").unwrap().1.is_some());}fn yt(chosen: Option<&BrowserCookies>, ours: &[&str]) -> Vec<String> {diff --git a/crates/tools/tests/cookies.rs b/crates/tools/tests/cookies.rsindex d4bae97e..ce6b891b 100644--- a/crates/tools/tests/cookies.rs+++ b/crates/tools/tests/cookies.rs@@ -3,6 +3,10 @@//! computer, and no real browser profile is read: Firefox's cookies come from a throwaway//! profile folder made for the test.//!+//! The cookies of a page on one host of a site reach yt-dlp's request to another host of it+//! (music.youtube.com's page, www.youtube.com's request): yt-dlp then goes through the lab as its+//! HTTP proxy, which answers for every host name, so those names never reach the network.+//!//! Ignored: it needs yt-dlp's program, and for the browser part a Firefox profile folder whose//! `cookies.sqlite` has the cookie `ff=from-firefox` for 127.0.0.1://!@@ -10,6 +14,7 @@use std::time::{Duration, Instant};+use mdm_ipc::BrowserCookie;use mdm_labserver::{Config, LabServer};use mdm_tools::proc::{BrowserCookies, FromBrowser, set_browser_cookies};use mdm_tools::video::{State, Subs, VideoJob};@@ -24,6 +29,39 @@ fn cookies_seen(lab: &LabServer, path: &str, from: usize) -> Vec<String> {.collect()}+/// yt-dlp's look-up (`-J`) of `url` with `browser`'s cookies as the app gives them, through the+/// lab as its HTTP proxy (any host name is the lab's: nothing leaves this computer), its generic+/// extractor forced (YouTube's would take a youtube.com address as a channel's); then the host+/// and cookies of each request for the lab's clip.+fn hosts_and_cookies(+ exe: &std::path::Path,+ lab: &LabServer,+ url: &str,+ browser: &FromBrowser,+) -> Vec<(String, String)> {+ let proxy = lab.url("");+ let extras = ["--proxy".to_owned(), proxy.trim_end_matches('/').to_owned()];+ let mut ours: Vec<String> = ["-J", "--no-playlist", "--force-generic-extractor"]+ .map(String::from)+ .to_vec();+ let (theirs, _file) = browser.args(url).unwrap();+ ours.extend(theirs);+ let at = lab.log().len();+ let cmd = mdm_tools::proc::ytdlp(exe, &extras, &ours, url).unwrap();+ let out = mdm_tools::proc::output(cmd, "yt-dlp", Duration::from_secs(90));+ assert!(out.is_ok(), "{url}: {:?}", out.err());+ lab.log()+ .into_iter()+ .skip(at)+ .filter(|e| e.path == "/gen/1M/clip.mp4")+ .map(|e| {+ let host = e.host.unwrap_or_default();+ let host = host.split(':').next().unwrap_or_default().to_owned();+ (host, e.cookie.unwrap_or_default())+ })+ .collect()+}+fn download(exe: &std::path::Path, url: &str, browser: &FromBrowser) -> (State, Vec<String>) {let dir = tempfile::tempdir().unwrap();let job = VideoJob::start(@@ -89,22 +127,87 @@ fn whose_cookies_ytdlp_sends() {println!("2. look-up, nothing: {seen:?}");assert!(seen.iter().all(String::is_empty));+ // 3. A YouTube Music page's cookies, the look-up asking www.youtube.com (the lab's redirect+ // stands in for yt-dlp going there): a newer extension's, each with its domain: the+ // site's sign-in (`.youtube.com`) goes there, the page host's own cookie doesn't.+ let port = lab+ .url("")+ .trim_end_matches('/')+ .rsplit(':')+ .next()+ .unwrap()+ .to_owned();+ let via = |from: &str, to: &str| {+ format!("http://{from}:{port}/redirect?to=http://{to}:{port}/gen/1M/clip.mp4")+ };+ let music = via("music.youtube.com", "www.youtube.com");+ let jar = FromBrowser {+ cookies: Some("SID=signed-in; pref=music-only".into()),+ jar: vec![+ BrowserCookie {+ name: "SID".into(),+ value: "signed-in".into(),+ domain: ".youtube.com".into(),+ path: "/".into(),+ ..Default::default()+ },+ BrowserCookie {+ name: "pref".into(),+ value: "music-only".into(),+ domain: "music.youtube.com".into(),+ host_only: true,+ path: "/".into(),+ ..Default::default()+ },+ ],+ ..Default::default()+ };+ let seen = hosts_and_cookies(&exe, &lab, &music, &jar);+ println!("3. music.youtube.com's page, each cookie's domain: {seen:?}");+ assert!(!seen.is_empty(), "the clip asked for");+ for (host, cookie) in &seen {+ assert_eq!(host, "www.youtube.com");+ assert!(cookie.contains("SID=signed-in"), "{cookie:?}");+ assert!(!cookie.contains("pref="), "{cookie:?}");+ }+ // An older extension's header (no domains): filed for youtube.com, it goes there too.+ let header = FromBrowser {+ cookies: Some("SID=signed-in".into()),+ ..Default::default()+ };+ let seen = hosts_and_cookies(&exe, &lab, &music, &header);+ println!("3. music.youtube.com's page, a header: {seen:?}");+ assert!(!seen.is_empty());+ for (host, cookie) in &seen {+ assert_eq!(host, "www.youtube.com");+ assert!(cookie.contains("SID=signed-in"), "{cookie:?}");+ }+ // Another site's header stays with the page's host: none for its other host.+ let other = via("music.lab.test", "www.lab.test");+ let seen = hosts_and_cookies(&exe, &lab, &other, &header);+ println!("3. music.lab.test's page, a header: {seen:?}");+ assert!(!seen.is_empty());+ for (host, cookie) in &seen {+ assert_eq!(host, "www.lab.test");+ assert!(!cookie.contains("SID="), "{cookie:?}");+ }+let Ok(profile) = std::env::var("MDM_TEST_FIREFOX_PROFILE") else {println!("MDM_TEST_FIREFOX_PROFILE not set: the browser's part not run");return;};- // 3. Options → Cookies for video sites: Firefox's (the throwaway profile) when the extension+ // 4. Options → Cookies for video sites: Firefox's (the throwaway profile) when the extension// sent none: a pasted address, the look-up and the download.set_browser_cookies(BrowserCookies::new("firefox", &profile));let at = lab.log().len();mdm_tools::resolve::look_up(&exe, &url, &FromBrowser::default()).unwrap();let seen = cookies_seen(&lab, path, at);- println!("3. look-up, Firefox's: {seen:?}");+ println!("4. look-up, Firefox's: {seen:?}");assert!(!seen.is_empty() && seen.iter().all(|c| c.contains("ff=from-firefox")));let at = lab.log().len();let (state, events) = download(&exe, &url, &FromBrowser::default());let seen = cookies_seen(&lab, path, at);- println!("3. download, Firefox's: {state:?} {seen:?} {events:?}");+ println!("4. download, Firefox's: {state:?} {seen:?} {events:?}");assert!(matches!(state, State::Done(_)), "{state:?}");assert!(seen.iter().all(|c| c.contains("ff=from-firefox")),@@ -123,11 +226,11 @@ fn whose_cookies_ytdlp_sends() {"the log names the browser only");- // 4. Both: the extension's alone (that page's, that session's).+ // 5. Both: the extension's alone (that page's, that session's).let at = lab.log().len();let (state, events) = download(&exe, &url, &ext);let seen = cookies_seen(&lab, path, at);- println!("4. download, both: {state:?} {seen:?} {events:?}");+ println!("5. download, both: {state:?} {seen:?} {events:?}");assert!(matches!(state, State::Done(_)), "{state:?}");assert!(seen.iter()@@ -135,14 +238,14 @@ fn whose_cookies_ytdlp_sends() {"{seen:?}");- // 5. A profile folder with no cookies: yt-dlp's refusal, kept on the error.+ // 6. A profile folder with no cookies: yt-dlp's refusal, kept on the error.let empty = tempfile::tempdir().unwrap();set_browser_cookies(BrowserCookies::new("firefox",&empty.path().display().to_string(),));let err = mdm_tools::resolve::look_up(&exe, &url, &FromBrowser::default()).unwrap_err();- println!("5. look-up, empty profile: {err}");+ println!("6. look-up, empty profile: {err}");assert!(err.to_string().contains("could not find firefox cookies database"),diff --git a/docs/automation-api.schema.json b/docs/automation-api.schema.jsonindex d3a2bec4..5ee544f6 100644--- a/docs/automation-api.schema.json+++ b/docs/automation-api.schema.json@@ -54,6 +54,48 @@],"type": "object"},+ "BrowserCookie": {+ "description": "One cookie as the browser keeps it (`cookies.getAll`'s fields, under the extension's names\ntoo: `hostOnly`, `expirationDate`).",+ "properties": {+ "domain": {+ "default": "",+ "description": "`.youtube.com` (sent to its subdomains too) or a host name.",+ "type": "string"+ },+ "expires": {+ "default": null,+ "description": "When it expires, in seconds since 1970; none: when the browser closes.",+ "format": "double",+ "type": [+ "number",+ "null"+ ]+ },+ "host_only": {+ "default": false,+ "description": "Sent to `domain` itself only, never its subdomains.",+ "type": "boolean"+ },+ "name": {+ "default": "",+ "type": "string"+ },+ "path": {+ "default": "",+ "type": "string"+ },+ "secure": {+ "default": false,+ "description": "Sent over HTTPS only.",+ "type": "boolean"+ },+ "value": {+ "default": "",+ "type": "string"+ }+ },+ "type": "object"+ },"CategoryInfo": {"description": "One category of the list.","properties": {@@ -304,6 +346,13 @@"null"]},+ "cookie_jar": {+ "description": "From the browser: the same cookies, each with the domain, path and flags the browser\nkeeps for it, for yt-dlp's cookie file. yt-dlp may ask another host than the page's (a\nYouTube Music page is looked up on www.youtube.com), and a cookie of `.youtube.com` goes\nthere too. An older extension sends `cookies` only.",+ "items": {+ "$ref": "#/$defs/BrowserCookie"+ },+ "type": "array"+ },"cookies": {"default": null,"type": [diff --git a/extension/background.js b/extension/background.jsindex be0ff4c7..a290fee3 100644--- a/extension/background.js+++ b/extension/background.js@@ -891,7 +891,7 @@ async function mediaDownload(tabId, url) {src: it.url,title: String(tab.title || "").slice(0, 300),referrer: tab.url && tab.url !== page ? tab.url : "",- cookies: await cookieHeader(it.url, ctx),+ ...(await videoCookies(it.url, ctx)),...(ctx.incognito ? { private: true } : {}),});}@@ -902,16 +902,41 @@ async function mediaDownload(tabId, url) {// Cookies from the store the download belongs to, never another: Firefox names it on the// download (private windows and containers each have their own); Chrome's incognito store is "1".-async function cookieHeader(url, { incognito, storeId }) {+async function cookiesFor(url, { incognito, storeId }) {try {const query = storeId ? { url, storeId } : incognito ? { url, storeId: "1" } : { url };- const list = await ext.cookies.getAll(query);- return list.map((c) => `${c.name}=${c.value}`).join("; ");+ return (await ext.cookies.getAll(query)) || [];} catch {- return "";+ return [];}}+function header(list) {+ return list.map((c) => `${c.name}=${c.value}`).join("; ");+}++async function cookieHeader(url, ctx) {+ return header(await cookiesFor(url, ctx));+}++// For yt-dlp, which may ask another host of the site than the page's (a YouTube Music page is+// looked up on www.youtube.com): each cookie with the domain, path and flags the browser keeps,+// so the app files `.youtube.com`'s sign-in for every host of it and a host's own cookie for+// that host alone. The header goes too, for an older app.+async function videoCookies(url, ctx) {+ const list = await cookiesFor(url, ctx);+ const cookieJar = list.map((c) => ({+ name: c.name,+ value: c.value,+ domain: c.domain,+ hostOnly: Boolean(c.hostOnly),+ path: c.path || "/",+ secure: Boolean(c.secure),+ ...(typeof c.expirationDate === "number" ? { expirationDate: c.expirationDate } : {}),+ }));+ return { cookies: header(list), cookieJar };+}+// Has the user left this extension the site? With access limited ("On click", some sites), its// cookies can't be read, and a download handed over without them would fail.async function siteAccess(url) {@@ -1433,7 +1458,7 @@ ext.contextMenus.onClicked.addListener(async (info, tab) => {// window, which reads streams (a manifest downloaded as a file is only a short list).// The manifest's own cookies (its server may not be the page's), as the media list sends.if (url && MANIFEST.test(url)) {- const reply = await native({ video: true, explicit: true, url: info.pageUrl, src: url, cookies: await cookieHeader(url, { incognito, storeId }), private: incognito });+ const reply = await native({ video: true, explicit: true, url: info.pageUrl, src: url, ...(await videoCookies(url, { incognito, storeId })), private: incognito });if (!reply.ok && reply.why !== "options") explain(reply.why);return;}@@ -1452,7 +1477,7 @@ ext.contextMenus.onClicked.addListener(async (info, tab) => {url: page,...(src ? { src } : {}),referrer: info.pageUrl && info.pageUrl !== page ? info.pageUrl : "",- cookies: await cookieHeader(src || page, { incognito, storeId }),+ ...(await videoCookies(src || page, { incognito, storeId })),private: incognito,});if (!reply.ok && reply.why !== "options") explain(reply.why);@@ -1572,7 +1597,7 @@ async function pageMessage(m, sender) {referrer: tab.url && tab.url !== page ? tab.url : "",// The cookies of what yt-dlp is given (the app files them under its host): the stream's// own server may not be the page's, and the page's cookies are not for it.- cookies: await cookieHeader(src || page, { incognito: tab.incognito, storeId: tab.cookieStoreId }),+ ...(await videoCookies(src || page, { incognito: tab.incognito, storeId: tab.cookieStoreId })),...(tab.incognito ? { private: true } : {}),});return { ok: Boolean(reply.ok), why: reply.why };diff --git a/tools/extension/test.mjs b/tools/extension/test.mjsindex 6fd55669..3222e30d 100644--- a/tools/extension/test.mjs+++ b/tools/extension/test.mjs@@ -84,7 +84,8 @@ function fakeApi({cookies: {getAll: async (q) => {calls.push(["cookies", q]);- return [{ name: "sid", value: "1" }];+ // As Chrome gives one: its other fields aren't sent.+ return [{ name: "sid", value: "1", domain: ".tube.test", hostOnly: false, path: "/", secure: true, httpOnly: true, sameSite: "lax", session: false, expirationDate: 1893456000.5, storeId: "0" }];},},permissions: {@@ -265,6 +266,7 @@ const ok = (what) => {["https://x/a.zip", "https://page/", "sid=1", "a.zip", 2048, "application/zip", "UA", "0.2.5"],);assert.deepEqual(m.brands, ["Chromium", "Brave"]);+ assert.equal(m.cookieJar, undefined, "a file's download: the header the app sends");assert.deepEqual(steps(calls), ["pause", "cancel", "erase"]);ok("Firefox: taken with its container's cookies, size and type");}@@ -550,6 +552,8 @@ const ok = (what) => {assert.equal(video.url, "https://tube.test/embed/1", "the page the browser names, not the message's");assert.equal(video.referrer, "https://blog.test/post");assert.equal(video.cookies, "sid=1");+ // Each cookie with its domain and flags, for yt-dlp asking another host of the site.+ assert.deepEqual(video.cookieJar, [{ name: "sid", value: "1", domain: ".tube.test", hostOnly: false, path: "/", secure: true, expirationDate: 1893456000.5 }]);assert.deepEqual(await ask({ type: "hide-site", host: "elsewhere.test" }), { ok: true });assert.ok(natives(calls).some((m) => m.hideSite === "tube.test"));assert.deepEqual(await ask({ type: "panel" }, "https://tube.test/embed/3"), { on: false }, "off at once");@@ -740,6 +744,7 @@ const MPD = (protect) => `<?xml version="1.0"?>const v = natives(calls).find((m) => m.video);assert.deepEqual([v.explicit, v.src, v.url, v.title, v.cookies, v.referrer], [true, "https://cdn.test/v/master.m3u8", "https://watch.test/v/1", "A film", "sid=1", ""]);assert.deepEqual(calls.filter((c) => c[0] === "cookies").pop()[1], { url: "https://cdn.test/v/master.m3u8" });+ assert.deepEqual(v.cookieJar.map((c) => c.domain), [".tube.test"], "each cookie with its domain");await popupAsk(listeners, { type: "media-download", tab: 9, url: "https://files.test/movie.mp4" });const f = natives(calls).find((m) => m.url === "https://files.test/movie.mp4");assert.deepEqual([f.explicit, f.referrer, f.size, f.mime, f.video], [true, "https://watch.test/v/1", 52428800, "video/mp4", undefined]);