From 19718cee2247b6ed77321a3a2ae269abd3e72db0 Mon Sep 17 00:00:00 2001 From: TheGeneralist <180094941+thegeneralist01@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:51:15 +0200 Subject: [PATCH] feat: capture browser cookies and localStorage from extension (#44) Add an optional browser session to captures and the shared in-page dialog. Validate localStorage against the exact page origin, preserve cookie and storage keys, and clean up temporary secret files on failure. Companion extension PR: thegeneralist01/archivr-extension#1. --- crates/archivr-core/src/browser_session.rs | 356 ++++++++++++++++++ crates/archivr-core/src/capture.rs | 39 +- .../archivr-core/src/downloader/singlefile.rs | 180 +++++++-- crates/archivr-core/src/lib.rs | 1 + crates/archivr-server/src/routes.rs | 220 ++++++++++- frontend/src/browserData.js | 159 ++++++++ frontend/src/browserData.test.js | 181 +++++++++ .../src/components/CaptureBrowserData.jsx | 292 ++++++++++++++ frontend/src/components/CaptureDialog.jsx | 113 +++++- .../src/components/CaptureDialog.test.jsx | 62 +++ frontend/src/styles.css | 149 ++++++++ 11 files changed, 1712 insertions(+), 40 deletions(-) create mode 100644 crates/archivr-core/src/browser_session.rs create mode 100644 frontend/src/browserData.js create mode 100644 frontend/src/browserData.test.js create mode 100644 frontend/src/components/CaptureBrowserData.jsx diff --git a/crates/archivr-core/src/browser_session.rs b/crates/archivr-core/src/browser_session.rs new file mode 100644 index 0000000..069886d --- /dev/null +++ b/crates/archivr-core/src/browser_session.rs @@ -0,0 +1,356 @@ +//! Browser session data forwarded from the extension's in-page capture dialog. +//! +//! `BrowserSession` carries cookies and localStorage from the user's real browser +//! tab so Archivr can archive the page as the authenticated user sees it. +//! +//! Security invariants: +//! - Names and values are never printed in error messages or logs. +//! - The struct's `Debug` impl redacts all names and values, showing only counts. +//! - The session is validated before use and is never persisted. + +use std::{collections::HashMap, fmt}; + +/// Browser session forwarded from the extension's in-page capture dialog. +#[derive(Clone, serde::Deserialize)] +pub struct BrowserSession { + /// The exact URL the session data was read from. + pub url: String, + /// Browser cookies for the page, name → value. + #[serde(default)] + pub cookies: HashMap, + /// Page localStorage entries, key → value. + #[serde(default)] + pub local_storage: HashMap, +} + +/// Redacting Debug: never prints names or values, only counts. +impl fmt::Debug for BrowserSession { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("BrowserSession") + .field("url", &self.url) + .field("cookies_count", &self.cookies.len()) + .field("local_storage_count", &self.local_storage.len()) + .finish() + } +} + +// ── Limits (mirrored in extension core.ts and frontend browserData.js) ─────── + +const MAX_COOKIES: usize = 300; +const MAX_COOKIE_NAME_BYTES: usize = 256; +const MAX_COOKIE_VALUE_BYTES: usize = 8192; +const MAX_COOKIES_TOTAL_BYTES: usize = 65536; +const MAX_STORAGE_ITEMS: usize = 2000; +const MAX_STORAGE_KEY_BYTES: usize = 1024; +const MAX_STORAGE_TOTAL_BYTES: usize = 1_048_576; +const MAX_URL_BYTES: usize = 10_000; + +impl BrowserSession { + /// Validates all limits and character rules for the session data. + /// Returns an `Err(String)` containing the exact 400-error string on failure. + pub fn validate(&self) -> Result<(), String> { + // ── URL ────────────────────────────────────────────────────────────── + if self.url.len() > MAX_URL_BYTES { + return Err("browser_session.url must be an http(s) URL".to_string()); + } + let parsed_url = reqwest::Url::parse(&self.url) + .map_err(|_| "browser_session.url must be an http(s) URL".to_string())?; + if !matches!(parsed_url.scheme(), "http" | "https") { + return Err("browser_session.url must be an http(s) URL".to_string()); + } + if parsed_url.host_str().is_none() { + return Err("browser_session.url must be an http(s) URL".to_string()); + } + + // ── Cookies ────────────────────────────────────────────────────────── + if self.cookies.len() > MAX_COOKIES { + return Err(format!( + "browser_session has too many cookies (max {MAX_COOKIES})" + )); + } + let mut cookie_total_bytes: usize = 0; + for (name, value) in &self.cookies { + if name.is_empty() + || name.len() > MAX_COOKIE_NAME_BYTES + || name.bytes().any(|b| b < 0x20 || b == 0x7f || b == b' ' || b == b';' || b == b'=') + { + let display = truncate_debug(name, 64); + return Err(format!( + "browser_session cookie {display} has an invalid name" + )); + } + if value.len() > MAX_COOKIE_VALUE_BYTES + || value.bytes().any(|b| b < 0x20 || b == 0x7f || b == b';') + { + let display = truncate_debug(name, 64); + return Err(format!( + "browser_session cookie {display} has an invalid value" + )); + } + cookie_total_bytes += name.len() + value.len(); + } + if cookie_total_bytes > MAX_COOKIES_TOTAL_BYTES { + return Err("browser_session cookies exceed 64 KiB".to_string()); + } + + // ── localStorage ───────────────────────────────────────────────────── + if self.local_storage.len() > MAX_STORAGE_ITEMS { + return Err(format!( + "browser_session has too many localStorage items (max {MAX_STORAGE_ITEMS})" + )); + } + let mut storage_total_bytes: usize = 0; + for (key, value) in &self.local_storage { + if key.is_empty() || key.len() > MAX_STORAGE_KEY_BYTES { + let display = truncate_debug(key, 64); + return Err(format!( + "browser_session localStorage key {display} is empty or longer than 1024 bytes" + )); + } + storage_total_bytes += key.len() + value.len(); + } + if storage_total_bytes > MAX_STORAGE_TOTAL_BYTES { + return Err("browser_session localStorage exceeds 1 MiB".to_string()); + } + + Ok(()) + } + + /// Returns `true` when the session URL matches the target described by `locator`. + /// + /// - Tweet/TweetThread sources: session host must be X-family (`x.com`, `twitter.com`, + /// or a subdomain of either). + /// - Everything else: the expanded locator URL must have the same exact hostname as + /// the session URL. + pub fn applies_to(&self, locator: &str) -> bool { + use crate::{ + capture::{determine_source, expand_shorthand_to_url, Source}, + downloader::cookies::domain_from_url, + }; + + let source = determine_source(locator); + match source { + Source::Tweet | Source::TweetThread => { + let host = domain_from_url(&self.url).to_lowercase(); + is_x_family_host(&host) + } + _ => { + let locator_url = expand_shorthand_to_url(locator, &source); + let locator_host = domain_from_url(&locator_url).to_lowercase(); + let session_host = domain_from_url(&self.url).to_lowercase(); + !locator_host.is_empty() && locator_host == session_host + } + } + } + + /// localStorage belongs to an exact origin, including scheme and port. + /// Media shorthands have no page origin to seed. + pub fn storage_applies_to(&self, locator: &str) -> bool { + let Ok(session_url) = reqwest::Url::parse(&self.url) else { + return false; + }; + let Ok(target_url) = reqwest::Url::parse(locator) else { + return false; + }; + matches!(target_url.scheme(), "http" | "https") + && session_url.origin() == target_url.origin() + } + + /// Returns the ASCII-serialized origin of `url`, e.g. `"https://www.example.com"`. + pub fn storage_origin(&self) -> Option { + reqwest::Url::parse(&self.url) + .ok() + .map(|u| u.origin().ascii_serialization()) + } +} + +/// True when `host` is exactly `x.com` or `twitter.com`, or a subdomain of either. +fn is_x_family_host(host: &str) -> bool { + host == "x.com" + || host == "twitter.com" + || host.ends_with(".x.com") + || host.ends_with(".twitter.com") +} + +/// Extends `base` cookies with the browser session's cookies. +/// Session values win on name collision (browser cookie overrides rule cookie). +pub(crate) fn merge_cookies( + mut base: HashMap, + session: Option<&BrowserSession>, +) -> HashMap { + if let Some(s) = session { + for (k, v) in &s.cookies { + base.insert(k.clone(), v.clone()); + } + } + base +} + +/// Returns `format!("{:?}", s)` truncated to `max_chars` chars (with `…` appended if cut). +fn truncate_debug(s: &str, max_chars: usize) -> String { + let repr = format!("{s:?}"); + let chars: Vec = repr.chars().collect(); + if chars.len() > max_chars { + let truncated: String = chars[..max_chars].iter().collect(); + format!("{truncated}…") + } else { + repr + } +} + +// ── Tests ───────────────────────────────────────────────────────────────────── + +#[cfg(test)] +mod tests { + use super::*; + + fn make_session(url: &str) -> BrowserSession { + BrowserSession { + url: url.to_string(), + cookies: HashMap::new(), + local_storage: HashMap::new(), + } + } + + // ── applies_to ──────────────────────────────────────────────────────────── + + #[test] + fn applies_to_same_host() { + let s = make_session("https://www.example.com/a"); + assert!(s.applies_to("https://www.example.com/b")); + } + + #[test] + fn storage_requires_the_same_origin_not_just_host() { + let s = make_session("https://example.com:8443/a"); + assert!(s.storage_applies_to("https://example.com:8443/b")); + assert!(!s.storage_applies_to("https://example.com/b")); + assert!(!s.storage_applies_to("http://example.com:8443/b")); + assert!(!s.storage_applies_to("tweet:123456789012345678")); + } + + #[test] + fn applies_to_different_subdomain_is_false() { + let s = make_session("https://www.example.com/a"); + assert!(!s.applies_to("https://example.com/b")); + } + + #[test] + fn applies_to_twitter_session_with_tweet_locator() { + let s = make_session("https://twitter.com/home"); + // tweet:tweet:123 → Source::Tweet + assert!(s.applies_to("tweet:tweet:123456789012345678")); + } + + #[test] + fn applies_to_x_session_with_tweet_locator() { + let s = make_session("https://x.com/home"); + assert!(s.applies_to("x:123456789012345678")); + } + + #[test] + fn applies_to_non_x_session_with_tweet_locator_is_false() { + let s = make_session("https://example.com/"); + assert!(!s.applies_to("tweet:123456789012345678")); + } + + #[test] + fn applies_to_youtube_session_with_yt_shorthand() { + let s = make_session("https://www.youtube.com/feed"); + assert!(s.applies_to("yt:dQw4w9WgXcQ")); + } + + #[test] + fn applies_to_youtube_session_with_wrong_shorthand_is_false() { + let s = make_session("https://www.youtube.com/feed"); + // ytm: expands to music.youtube.com, not www.youtube.com + assert!(!s.applies_to("ytm:dQw4w9WgXcQ")); + } + + // ── validate ────────────────────────────────────────────────────────────── + + #[test] + fn validate_rejects_name_with_space() { + let mut s = make_session("https://example.com/"); + s.cookies.insert("a b".to_string(), "value".to_string()); + let err = s.validate().unwrap_err(); + assert!(err.contains("invalid name"), "got: {err}"); + assert!(!err.contains("value"), "must not leak value: {err}"); + } + + #[test] + fn validate_rejects_value_with_newline() { + let mut s = make_session("https://example.com/"); + s.cookies.insert("name".to_string(), "val\nue".to_string()); + let err = s.validate().unwrap_err(); + assert!(err.contains("invalid value"), "got: {err}"); + assert!(!err.contains("val\nue"), "must not leak value: {err}"); + } + + #[test] + fn validate_rejects_too_many_cookies() { + let mut s = make_session("https://example.com/"); + for i in 0..=300 { + s.cookies.insert(format!("k{i}"), "v".to_string()); + } + let err = s.validate().unwrap_err(); + assert!(err.contains("too many cookies"), "got: {err}"); + } + + #[test] + fn validate_rejects_oversized_storage() { + let mut s = make_session("https://example.com/"); + // 1 MiB + 1 byte total + let large_val = "x".repeat(MAX_STORAGE_TOTAL_BYTES + 1); + s.local_storage.insert("k".to_string(), large_val); + let err = s.validate().unwrap_err(); + assert!(err.contains("localStorage exceeds 1 MiB"), "got: {err}"); + } + + #[test] + fn validate_accepts_realistic_map() { + let mut s = make_session("https://example.com/"); + s.cookies.insert("session_id".to_string(), "abc123xyz".to_string()); + s.cookies.insert("theme".to_string(), "dark".to_string()); + s.local_storage.insert("pref".to_string(), "1".to_string()); + assert!(s.validate().is_ok()); + } + + // ── merge_cookies ───────────────────────────────────────────────────────── + + #[test] + fn merge_cookies_session_wins_on_collision() { + let mut base = HashMap::new(); + base.insert("session".to_string(), "old_value".to_string()); + base.insert("other".to_string(), "kept".to_string()); + + let mut s = make_session("https://example.com/"); + s.cookies.insert("session".to_string(), "new_value".to_string()); + + let merged = merge_cookies(base, Some(&s)); + assert_eq!(merged["session"], "new_value"); + assert_eq!(merged["other"], "kept"); + } + + #[test] + fn merge_cookies_with_no_session_returns_base() { + let mut base = HashMap::new(); + base.insert("k".to_string(), "v".to_string()); + let merged = merge_cookies(base.clone(), None); + assert_eq!(merged, base); + } + + // ── debug redaction ─────────────────────────────────────────────────────── + + #[test] + fn debug_does_not_leak_cookie_values() { + let mut s = make_session("https://example.com/"); + s.cookies + .insert("session".to_string(), "super_secret_token".to_string()); + s.local_storage + .insert("key".to_string(), "stored_secret".to_string()); + let repr = format!("{s:?}"); + assert!(!repr.contains("super_secret_token"), "value leaked in Debug: {repr}"); + assert!(!repr.contains("stored_secret"), "value leaked in Debug: {repr}"); + } +} diff --git a/crates/archivr-core/src/capture.rs b/crates/archivr-core/src/capture.rs index 58a4091..2430a60 100644 --- a/crates/archivr-core/src/capture.rs +++ b/crates/archivr-core/src/capture.rs @@ -113,6 +113,10 @@ pub struct CaptureConfig { /// `capture_jobs` row to link to the run as soon as the run exists, so the job's creator /// can see the in-progress run (the job otherwise learns its `run_uid` only when it ends). pub job_uid: Option, + /// Browser session forwarded from the extension's in-page capture dialog. + /// Contains the user's cookies and localStorage for the captured page. + /// Never persisted or logged. + pub browser_session: Option, } impl Default for CaptureConfig { @@ -128,6 +132,7 @@ impl Default for CaptureConfig { sync: false, download_subtitles: true, job_uid: None, + browser_session: None, } } } @@ -324,7 +329,7 @@ fn is_youtube_video_id(s: &str) -> bool { .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-') } -fn expand_shorthand_to_url(path: &str, source: &Source) -> String { +pub(crate) fn expand_shorthand_to_url(path: &str, source: &Source) -> String { // YouTube shorthands: yt:video/ID, yt:playlist/ID, yt:@handle, yt:channel/ID, etc. if matches!( source, @@ -432,7 +437,7 @@ pub fn locator_is_local_path(locator: &str) -> bool { // INFO: yt-dlp supports a lot of sites; so, when archiving (for example) a website, the user // -> should be asked whether they want to archive the whole website or just the video(s) on it. -fn determine_source(path: &str) -> Source { +pub(crate) fn determine_source(path: &str) -> Source { // INFO: Extractor URLs can be found here: // -> https://github.com/yt-dlp/yt-dlp/tree/dfc0a84c192a7357dd1768cc345d590253a14fe5/yt_dlp/extractor // TEST: X posts can have multiple videos. @@ -1254,7 +1259,16 @@ pub fn perform_capture( // Expand shorthands to the canonical URL for cookie matching. let canonical_url = expand_shorthand_to_url(locator, &source); - let cookies = resolve_cookies_for_url(&config.cookie_rules, &canonical_url); + // Filter the browser session to this locator (defensive re-check even though + // the server validates applicability before creating the job). + let session = config + .browser_session + .as_ref() + .filter(|s| s.applies_to(locator)); + let cookies = crate::browser_session::merge_cookies( + resolve_cookies_for_url(&config.cookie_rules, &canonical_url), + session, + ); // Create the run record before probing so every attempt — including // probe failures — is visible in /runs with a proper status and error. @@ -1720,6 +1734,19 @@ pub fn perform_capture( // Key cleanup/title-stripping off the actual fetch host so that // user-supplied freedium-mirror.cfd URLs are also handled correctly. let is_freedium_fetch = fetch_url.starts_with("https://freedium-mirror.cfd/"); + // Build localStorage seed when we have a session with storage items and + // this is NOT a Freedium fetch (Freedium gets an empty cookie jar and no seed). + let storage_seed_origin = if !is_freedium_fetch { + session.and_then(|s| s.storage_origin()) + } else { + None + }; + let storage_seed = storage_seed_origin.as_deref().and_then(|origin| { + session.map(|s| downloader::singlefile::LocalStorageSeed { + origin, + items: &s.local_storage, + }) + }); match downloader::singlefile::save( &fetch_url, store_path, @@ -1730,6 +1757,7 @@ pub fn perform_capture( config.reader_mode, config.modal_closer_enabled, is_freedium_fetch, + storage_seed, ) { Ok(result) => { let file_extension = ".html".to_string(); @@ -1910,7 +1938,10 @@ pub fn perform_capture( // Tweet shorthands (tweet:ID) don't expand to a URL, so `canonical_url` // won't match x.com patterns. Always resolve cookies against x.com so // that wildcard/global rules containing `ct0`+`auth_token` are picked up. - let tweet_cookies = resolve_cookies_for_url(&config.cookie_rules, "https://x.com/"); + let tweet_cookies = crate::browser_session::merge_cookies( + resolve_cookies_for_url(&config.cookie_rules, "https://x.com/"), + session, + ); match downloader::tweets::archive( locator, source == Source::TweetThread, diff --git a/crates/archivr-core/src/downloader/singlefile.rs b/crates/archivr-core/src/downloader/singlefile.rs index a346d86..c388679 100644 --- a/crates/archivr-core/src/downloader/singlefile.rs +++ b/crates/archivr-core/src/downloader/singlefile.rs @@ -273,6 +273,32 @@ pub struct SaveResult { pub cookie_ext_skipped: bool, } +/// Carries localStorage seed data for a SingleFile page capture. +/// The items are written to a `--browser-script` that runs before page scripts. +pub struct LocalStorageSeed<'a> { + /// ASCII origin of the page (e.g. `"https://www.example.com"`). + pub origin: &'a str, + /// key → value pairs to seed into `localStorage` on page load. + pub items: &'a HashMap, +} + +/// Generates a self-contained IIFE script that seeds localStorage with the given +/// items, gated on the page's origin matching `seed.origin`. +/// +/// Both the origin and the data are JSON-encoded (valid JS literals), so no +/// manual quoting or escaping is needed. The IIFE catches any errors silently so +/// the page always loads, even if storage is blocked. +fn local_storage_seed_script(seed: &LocalStorageSeed) -> String { + let origin_json = serde_json::to_string(seed.origin).unwrap_or_else(|_| "\"\"".to_string()); + let data_json = serde_json::to_string(seed.items).unwrap_or_else(|_| "{}".to_string()); + format!( + ";(function(){{try{{if(location.origin!=={origin_json})return;\ + var d={data_json};\ + for(var k in d){{if(Object.prototype.hasOwnProperty.call(d,k))localStorage.setItem(k,d[k]);}}\ + }}catch(e){{}}}})()" + ) +} + /// Archives `url` as a self-contained HTML snapshot. /// /// Env vars: @@ -291,6 +317,7 @@ pub fn save( reader_mode: bool, modal_closer_enabled: Option, freedium_cleanup: bool, + local_storage: Option>, ) -> Result { let single_file = env::var("ARCHIVR_SINGLE_FILE").unwrap_or_else(|_| "single-file".to_string()); @@ -310,6 +337,7 @@ pub fn save( reader_mode, modal_closer, freedium_cleanup, + local_storage, )?; result.ublock_skipped = ublock_skipped; result.cookie_ext_skipped = cookie_ext_skipped; @@ -435,6 +463,7 @@ fn save_with( reader_mode: bool, modal_closer: bool, freedium_cleanup: bool, + local_storage: Option>, ) -> Result { let temp_dir = store_path.join("temp").join(timestamp); std::fs::create_dir_all(&temp_dir).context("failed to create temp dir")?; @@ -609,36 +638,66 @@ fn save_with( .collect(); let browser_args = format!("[{}]", quoted.join(",")); - // Write cookie file (secrets must never appear in process args). - let cookie_file: Option = if !cookies.is_empty() { - let cf = temp_dir.join("cookies.json"); - let domain = domain_from_url(url); - write_json_cookie_file(cookies, &domain, url, &cf) - .context("failed to write single-file cookie file")?; - Some(cf) - } else { - None - }; + // Construct both secret paths before writing either one. Every fallible + // write and the subprocess run stay inside this scope so cleanup also runs + // when the second write fails after the first file has been created. + let cookie_file = (!cookies.is_empty()).then(|| temp_dir.join("cookies.json")); + let storage_script_file = local_storage + .as_ref() + .filter(|seed| !seed.items.is_empty()) + .map(|_| temp_dir.join("sf-local-storage.js")); + let sf_result = (|| -> Result { + if let Some(cf) = &cookie_file { + let domain = domain_from_url(url); + write_json_cookie_file(cookies, &domain, url, cf) + .context("failed to write single-file cookie file")?; + } + if let (Some(sf), Some(seed)) = (&storage_script_file, &local_storage) { + let script = local_storage_seed_script(seed); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + std::fs::OpenOptions::new() + .write(true) + .create(true) + .truncate(true) + .mode(0o600) + .open(sf) + .and_then(|mut f| { + use std::io::Write; + f.write_all(script.as_bytes()) + }) + .context("failed to write localStorage seed script")?; + } + #[cfg(not(unix))] + std::fs::write(sf, &script).context("failed to write localStorage seed script")?; + } - let mut scripts: Vec<&Path> = vec![strip_scripts_path.as_path()]; - scripts.extend(extra_browser_scripts.iter().map(|p| p.as_path())); - - let sf_output = run_single_file_standalone( - url, - &out_file, - single_file, - chrome, - &browser_args, - &scripts, - cookie_file.as_deref(), - ) - .with_context(|| format!("failed to spawn single-file ({single_file})"))?; - - // Delete cookie file unconditionally — including on failure — so secrets - // are never left in store/temp when the capture fails. - if let Some(cf) = &cookie_file { - let _ = std::fs::remove_file(cf); + // localStorage seed runs FIRST so it executes before any page scripts. + let mut scripts: Vec<&Path> = Vec::new(); + if let Some(sf) = &storage_script_file { + scripts.push(sf.as_path()); + } + scripts.push(strip_scripts_path.as_path()); + scripts.extend(extra_browser_scripts.iter().map(|p| p.as_path())); + run_single_file_standalone( + url, + &out_file, + single_file, + chrome, + &browser_args, + &scripts, + cookie_file.as_deref(), + ) + .with_context(|| format!("failed to spawn single-file ({single_file})")) + })(); + for path in [cookie_file.as_ref(), storage_script_file.as_ref()] + .into_iter() + .flatten() + { + let _ = std::fs::remove_file(path); } + let sf_output = sf_result?; if !sf_output.status.success() { let stderr = String::from_utf8_lossy(&sf_output.stderr); @@ -1080,6 +1139,7 @@ mod tests { false, // reader mode off false, // modal closer off false, // freedium cleanup off + None, // no localStorage seed ); let err = result.unwrap_err(); let msg = format!("{err:#}"); @@ -1089,6 +1149,70 @@ mod tests { ); } + #[test] + fn save_with_spawn_failure_removes_secret_files() { + // Verifies that cookies.json and sf-local-storage.js are deleted even + // when spawning the single-file binary fails. + let tmp = tempfile::tempdir().unwrap(); + let mut cookies = HashMap::new(); + cookies.insert("session".to_string(), "secret".to_string()); + let mut items = HashMap::new(); + items.insert("pref".to_string(), "dark".to_string()); + let seed = LocalStorageSeed { + origin: "https://example.com", + items: &items, + }; + let result = save_with( + "https://example.com", + tmp.path(), + "test-ts", + "/nonexistent/single-file", + "chromium", + &cookies, + None, // no ublock ext + None, // no cookie ext + false, // reader mode off + false, // modal closer off + false, // freedium cleanup off + Some(seed), + ); + assert!(result.is_err(), "expected error from missing binary"); + let cookie_path = tmp.path().join("temp/test-ts/cookies.json"); + let storage_path = tmp.path().join("temp/test-ts/sf-local-storage.js"); + assert!(!cookie_path.exists(), "cookies.json was not deleted: {}", cookie_path.display()); + assert!(!storage_path.exists(), "sf-local-storage.js was not deleted: {}", storage_path.display()); + } + + #[test] + fn save_with_storage_write_failure_removes_cookie_file() { + let tmp = tempfile::tempdir().unwrap(); + let temp_dir = tmp.path().join("temp/test-ts"); + std::fs::create_dir_all(temp_dir.join("sf-local-storage.js")).unwrap(); + let mut cookies = HashMap::new(); + cookies.insert("session".to_string(), "secret".to_string()); + let mut items = HashMap::new(); + items.insert("pref".to_string(), "dark".to_string()); + let result = save_with( + "https://example.com", + tmp.path(), + "test-ts", + "/nonexistent/single-file", + "chromium", + &cookies, + None, + None, + false, + false, + false, + Some(LocalStorageSeed { + origin: "https://example.com", + items: &items, + }), + ); + assert!(result.unwrap_err().to_string().contains("localStorage seed script")); + assert!(!temp_dir.join("cookies.json").exists()); + } + #[test] fn save_with_both_extensions_uses_comma_joined_flags() { use std::path::Path; diff --git a/crates/archivr-core/src/lib.rs b/crates/archivr-core/src/lib.rs index 340b87c..41d3782 100644 --- a/crates/archivr-core/src/lib.rs +++ b/crates/archivr-core/src/lib.rs @@ -1,4 +1,5 @@ pub mod capture; +pub mod browser_session; pub mod archive; pub mod auth_credentials; pub mod auth_users; diff --git a/crates/archivr-server/src/routes.rs b/crates/archivr-server/src/routes.rs index 728cede..d58832f 100644 --- a/crates/archivr-server/src/routes.rs +++ b/crates/archivr-server/src/routes.rs @@ -59,6 +59,8 @@ const MAX_TEXT_CAPTURE_BODY_BYTES: usize = 2 * 1024 * 1024; // JSON can expand each body byte into a six-byte `\\u00XX` escape sequence, // plus a small request envelope. const MAX_TEXT_CAPTURE_REQUEST_BYTES: usize = MAX_TEXT_CAPTURE_BODY_BYTES * 6 + 64 * 1024; +// 1 MiB localStorage + 64 KiB cookies, with up to 6× JSON escape expansion. +const MAX_CAPTURE_REQUEST_BYTES: usize = (1_048_576 + 65_536) * 6 + 64 * 1024; // Short-lived token granting unauthenticated access to one specific artifact. // Used so Cast / AirPlay devices (which carry no session cookie) can fetch media. @@ -304,7 +306,7 @@ pub fn app_with_state(state: AppState) -> Router { .route("/api/archives/:archive_id/blobs/:sha256", get(serve_blob)) .route("/api/archives/:archive_id/runs", get(list_runs)) .route("/api/captures/options", get(capture_options_handler)) - .route("/api/archives/:archive_id/captures", post(capture_handler)) + .route("/api/archives/:archive_id/captures", post(capture_handler).layer(DefaultBodyLimit::max(MAX_CAPTURE_REQUEST_BYTES))) .route( "/api/archives/:archive_id/captures/text/title", post(generate_text_title_handler) @@ -1610,6 +1612,10 @@ struct CaptureBody { /// When true, skip playlist items already archived under an existing container. #[serde(default)] sync: bool, + /// Browser session forwarded from the extension's in-page capture dialog. + /// Contains the user's cookies and localStorage for the captured page. + /// Never persisted, logged, or echoed in error messages. + browser_session: Option, } #[derive(Debug, serde::Deserialize)] @@ -1733,6 +1739,20 @@ async fn capture_handler( ))); } } + // Validate browser_session if provided. + if let Some(session) = &body.browser_session { + session.validate().map_err(|e| ApiError::bad_request(&e))?; + if !session.applies_to(body.locator.trim()) { + return Err(ApiError::bad_request( + "browser_session.url must be on the same site as the locator", + )); + } + if !session.local_storage.is_empty() && !session.storage_applies_to(body.locator.trim()) { + return Err(ApiError::bad_request( + "browser_session.local_storage requires the same origin as the locator", + )); + } + } // per_item_quality semantics (enforced in capture.rs): // - Absent or empty map: all playlist items are downloaded; quality is the // global `quality` field applied as a yt-dlp cap with graceful fallback. @@ -1819,6 +1839,7 @@ async fn capture_handler( per_item_quality: body.per_item_quality.clone(), sync: body.sync, job_uid: Some(job_uid.clone()), + browser_session: body.browser_session.clone(), }; // Spawn background capture. @@ -2224,6 +2245,8 @@ async fn rearchive_handler( sync: false, // Rearchive replaces an entry's artifacts in place and creates no run to link. job_uid: None, + // Rearchive has no browser session; browser data is only supplied for new captures. + browser_session: None, }; let job_uid_bg = job_uid.clone(); @@ -6441,6 +6464,201 @@ mod tests { ); } + #[tokio::test] + async fn capture_browser_session_wrong_site_is_rejected() { + let dir = tempfile::tempdir().unwrap(); + let (registry, _, auth_path) = make_test_registry(&dir); + let session_cookie = make_test_session(&auth_path); + let body = serde_json::json!({ + "locator": "https://example.com/a", + "browser_session": { + "url": "https://other.example.com/", + "cookies": {}, + "local_storage": {} + } + }); + let response = app(registry, auth_path) + .oneshot( + Request::builder() + .method("POST") + .uri("/api/archives/test/captures") + .header("content-type", "application/json") + .header("cookie", &session_cookie) + .body(Body::from(body.to_string())) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + let resp_bytes = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + let json: serde_json::Value = serde_json::from_slice(&resp_bytes).unwrap(); + assert!( + json["error"] + .as_str() + .is_some_and(|e| e.contains("same site")), + "expected same-site error, got: {json}" + ); + } + + #[tokio::test] + async fn capture_browser_session_storage_requires_same_origin() { + let dir = tempfile::tempdir().unwrap(); + let (registry, _, auth_path) = make_test_registry(&dir); + let session_cookie = make_test_session(&auth_path); + let body = serde_json::json!({ + "locator": "https://example.com:8443/a", + "browser_session": { + "url": "https://example.com/a", + "cookies": { "session": "abc" }, + "local_storage": { "pref": "dark" } + } + }); + let response = app(registry, auth_path) + .oneshot( + Request::builder() + .method("POST") + .uri("/api/archives/test/captures") + .header("content-type", "application/json") + .header("cookie", &session_cookie) + .body(Body::from(body.to_string())) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + let resp_bytes = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + let json: serde_json::Value = serde_json::from_slice(&resp_bytes).unwrap(); + assert!(json["error"] + .as_str() + .is_some_and(|e| e.contains("same origin"))); + } + + #[tokio::test] + async fn capture_browser_session_invalid_cookie_name_is_rejected() { + let dir = tempfile::tempdir().unwrap(); + let (registry, _, auth_path) = make_test_registry(&dir); + let session_cookie = make_test_session(&auth_path); + let body = serde_json::json!({ + "locator": "https://example.com/a", + "browser_session": { + "url": "https://example.com/", + "cookies": { "a b": "secret_value_must_not_appear" }, + "local_storage": {} + } + }); + let response = app(registry, auth_path) + .oneshot( + Request::builder() + .method("POST") + .uri("/api/archives/test/captures") + .header("content-type", "application/json") + .header("cookie", &session_cookie) + .body(Body::from(body.to_string())) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + let resp_bytes = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + let text = String::from_utf8_lossy(&resp_bytes); + assert!( + text.contains("invalid name"), + "expected invalid-name error, got: {text}" + ); + assert!( + !text.contains("secret_value_must_not_appear"), + "cookie value must not appear in error: {text}" + ); + } + + #[tokio::test] + async fn capture_browser_session_valid_returns_accepted() { + let dir = tempfile::tempdir().unwrap(); + let (registry, _, auth_path) = make_test_registry(&dir); + let session_cookie = make_test_session(&auth_path); + let body = serde_json::json!({ + "locator": "https://example.com/a", + "browser_session": { + "url": "https://example.com/page", + "cookies": { "session": "abc123" }, + "local_storage": { "pref": "dark" } + } + }); + let response = app(registry, auth_path) + .oneshot( + Request::builder() + .method("POST") + .uri("/api/archives/test/captures") + .header("content-type", "application/json") + .header("cookie", &session_cookie) + .body(Body::from(body.to_string())) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::ACCEPTED); + let resp_bytes = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + let json: serde_json::Value = serde_json::from_slice(&resp_bytes).unwrap(); + assert!( + json["job_uid"].as_str().is_some(), + "expected job_uid, got: {json}" + ); + } + + #[tokio::test] + async fn capture_browser_session_oversized_storage_returns_400_not_413() { + // Body ≈ 3 MiB (1.5 MiB of '"' chars, each escaped to '\\"' → 6 bytes); + // exceeds axum's 2 MB default. Proves the route's raised body limit. + // The value also exceeds our 1 MiB storage limit, so validation gives 400. + let dir = tempfile::tempdir().unwrap(); + let (registry, _, auth_path) = make_test_registry(&dir); + let session_cookie = make_test_session(&auth_path); + let large_value = "\"".repeat(1_572_864); // 1.5 MiB of '"' + let body = serde_json::json!({ + "locator": "https://example.com/a", + "browser_session": { + "url": "https://example.com/page", + "cookies": {}, + "local_storage": { "k": large_value } + } + }); + let response = app(registry, auth_path) + .oneshot( + Request::builder() + .method("POST") + .uri("/api/archives/test/captures") + .header("content-type", "application/json") + .header("cookie", &session_cookie) + .body(Body::from(body.to_string())) + .unwrap(), + ) + .await + .unwrap(); + // Must be 400 (validation error) not 413 (body too large). + assert_eq!( + response.status(), + StatusCode::BAD_REQUEST, + "expected 400, got {}", + response.status() + ); + let resp_bytes = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + let text = String::from_utf8_lossy(&resp_bytes); + assert!( + text.contains("localStorage exceeds 1 MiB"), + "expected storage limit error, got: {text}" + ); + } + #[tokio::test] async fn text_capture_post_returns_accepted_with_job_uid() { let dir = tempfile::tempdir().unwrap(); diff --git a/frontend/src/browserData.js b/frontend/src/browserData.js new file mode 100644 index 0000000..346c911 --- /dev/null +++ b/frontend/src/browserData.js @@ -0,0 +1,159 @@ +/** + * Pure helpers for browser session data (cookies + localStorage) forwarded + * from the extension's in-page capture dialog. + * + * Limits mirror the Rust server (browser_session.rs) and the extension (core.ts). + */ + +// ── Limits (mirrored in browser_session.rs and extension core.ts) ───────────── + +const MAX_COOKIES = 300 +const MAX_COOKIE_NAME_BYTES = 256 +const MAX_COOKIE_VALUE_BYTES = 8192 +const MAX_COOKIES_TOTAL_BYTES = 65536 +const MAX_STORAGE_ITEMS = 2000 +const MAX_STORAGE_KEY_BYTES = 1024 +const MAX_STORAGE_TOTAL_BYTES = 1_048_576 + +let _rowCounter = 0 + +/** @returns {number} */ +function nextRowId() { + return ++_rowCounter +} + +/** + * Maps a flat list of objects to table rows. + * @param {Array} list Items with a name/key field and a value field. + * @param {'name'|'key'} keyField Name of the property holding the key. + * @returns {Array<{id:number, name:string, value:string, included:boolean, httpOnly?:boolean}>} + */ +export function toRows(list, keyField) { + return (list || []).map(item => ({ + id: nextRowId(), + name: item[keyField] ?? '', + value: item.value ?? '', + included: true, + ...(keyField === 'name' && item.httpOnly !== undefined ? { httpOnly: !!item.httpOnly } : {}), + })) +} + +/** + * Converts rows to a plain object of included rows only. + * @param {Array<{name:string, value:string, included:boolean}>} rows + * @returns {Object} + */ +export function rowsToMap(rows) { + // Object.fromEntries creates an own property for names such as "__proto__". + // Assignment into {} silently drops that valid cookie/localStorage key. + return Object.fromEntries(rows + .filter(row => row.included && row.name !== '') + .map(row => [row.name, row.value])) +} + +/** @param {string} s */ +function byteLength(s) { + return new TextEncoder().encode(s).length +} + +/** + * Validates browser data. + * Returns the first error string, or `null` if everything is valid. + * Only included rows count, and only for enabled kinds. + * + * @param {{ + * useCookies: boolean, + * includeStorage: boolean, + * cookieRows: Array<{name:string, value:string, included:boolean}>, + * storageRows: Array<{name:string, value:string, included:boolean}> + * }} opts + * @returns {string|null} + */ +export function validateBrowserData({ useCookies, includeStorage, cookieRows, storageRows }) { + if (useCookies) { + const included = (cookieRows || []).filter(r => r.included) + if (included.length > MAX_COOKIES) { + return `Too many cookies (max ${MAX_COOKIES}).` + } + // Duplicate name check + const seen = new Set() + for (const row of included) { + if (seen.has(row.name)) { + return `Duplicate cookie name: ${row.name}` + } + seen.add(row.name) + } + // Per-row validation + for (const row of included) { + const name = row.name + const value = row.value + if (!name || byteLength(name) > MAX_COOKIE_NAME_BYTES || /[\x00-\x1f\x7f ;=]/.test(name)) { + return `Cookie names cannot be empty or contain spaces, ';' or '='.` + } + if (byteLength(value) > MAX_COOKIE_VALUE_BYTES || /[\x00-\x1f\x7f;]/.test(value)) { + return `Cookie values cannot contain ';' or control characters.` + } + } + // Total byte check + let total = 0 + for (const row of included) { + total += byteLength(row.name) + byteLength(row.value) + } + if (total > MAX_COOKIES_TOTAL_BYTES) { + return `Cookies exceed 64 KiB — exclude some.` + } + } + + if (includeStorage) { + const included = (storageRows || []).filter(r => r.included) + if (included.length > MAX_STORAGE_ITEMS) { + return `Too many localStorage items (max ${MAX_STORAGE_ITEMS}).` + } + // Duplicate key check + const seen = new Set() + for (const row of included) { + if (seen.has(row.name)) { + return `Duplicate localStorage key: ${row.name}` + } + seen.add(row.name) + } + // Per-row key validation + for (const row of included) { + if (!row.name || byteLength(row.name) > MAX_STORAGE_KEY_BYTES) { + return `localStorage keys cannot be empty or longer than 1024 bytes.` + } + } + // Total byte check + let total = 0 + for (const row of included) { + total += byteLength(row.name) + byteLength(row.value) + } + if (total > MAX_STORAGE_TOTAL_BYTES) { + return `localStorage exceeds 1 MiB — exclude some.` + } + } + + return null +} + +/** + * Builds the `browser_session` payload for the capture API. + * Returns `null` when both resulting maps are empty (nothing to send). + * + * @param {{ + * pageUrl: string, + * useCookies: boolean, + * includeStorage: boolean, + * cookieRows: Array<{name:string, value:string, included:boolean}>, + * storageRows: Array<{name:string, value:string, included:boolean}> + * }} opts + * @returns {{ url: string, cookies: object, local_storage: object }|null} + */ +export function buildBrowserSessionPayload({ pageUrl, useCookies, includeStorage, cookieRows, storageRows }) { + const cookies = useCookies ? rowsToMap(cookieRows || []) : {} + const local_storage = includeStorage ? rowsToMap(storageRows || []) : {} + if (Object.keys(cookies).length === 0 && Object.keys(local_storage).length === 0) { + return null + } + return { url: pageUrl, cookies, local_storage } +} diff --git a/frontend/src/browserData.test.js b/frontend/src/browserData.test.js new file mode 100644 index 0000000..34a31e3 --- /dev/null +++ b/frontend/src/browserData.test.js @@ -0,0 +1,181 @@ +import { describe, test, expect } from 'bun:test' +import { toRows, rowsToMap, validateBrowserData, buildBrowserSessionPayload } from './browserData.js' + +describe('toRows', () => { + test('maps name field for cookies', () => { + const rows = toRows([{ name: 'session', value: 'abc', httpOnly: true }], 'name') + expect(rows).toHaveLength(1) + expect(rows[0].name).toBe('session') + expect(rows[0].value).toBe('abc') + expect(rows[0].httpOnly).toBe(true) + expect(rows[0].included).toBe(true) + expect(typeof rows[0].id).toBe('number') + }) + + test('maps key field for localStorage', () => { + const rows = toRows([{ key: 'pref', value: '1' }], 'key') + expect(rows[0].name).toBe('pref') + expect(rows[0].value).toBe('1') + expect(rows[0].httpOnly).toBeUndefined() + }) +}) + +describe('rowsToMap', () => { + test('includes only included rows with non-empty names', () => { + const rows = [ + { id: 1, name: 'a', value: 'x', included: true }, + { id: 2, name: 'b', value: 'y', included: false }, + { id: 3, name: '', value: 'z', included: true }, + ] + const map = rowsToMap(rows) + expect(Object.keys(map)).toEqual(['a']) + expect(map.a).toBe('x') + }) + + test('preserves a localStorage key named __proto__', () => { + const map = rowsToMap([{ id: 1, name: '__proto__', value: 'saved', included: true }]) + expect(Object.keys(map)).toEqual(['__proto__']) + expect(map.__proto__).toBe('saved') + }) +}) + +describe('validateBrowserData', () => { + function make(overrides = {}) { + return { + useCookies: true, + includeStorage: true, + cookieRows: [], + storageRows: [], + ...overrides, + } + } + + test('returns null for valid empty data', () => { + expect(validateBrowserData(make())).toBeNull() + }) + + test('rejects a duplicate included cookie name', () => { + const cookieRows = [ + { id: 1, name: 'dup', value: 'a', included: true }, + { id: 2, name: 'dup', value: 'b', included: true }, + ] + const err = validateBrowserData(make({ cookieRows })) + expect(err).toMatch(/Duplicate cookie name/) + }) + + test('ignores duplicate excluded cookie names', () => { + const cookieRows = [ + { id: 1, name: 'dup', value: 'a', included: false }, + { id: 2, name: 'dup', value: 'b', included: false }, + ] + expect(validateBrowserData(make({ cookieRows }))).toBeNull() + }) + + test('rejects semicolon in cookie value', () => { + const cookieRows = [{ id: 1, name: 'k', value: 'a;b', included: true }] + const err = validateBrowserData(make({ cookieRows })) + expect(err).toBeTruthy() + expect(err).toMatch(/values cannot contain/i) + }) + + test('rejects duplicate included localStorage key', () => { + const storageRows = [ + { id: 1, name: 'k', value: 'a', included: true }, + { id: 2, name: 'k', value: 'b', included: true }, + ] + const err = validateBrowserData(make({ storageRows })) + expect(err).toMatch(/Duplicate localStorage key/) + }) + + test('passes at exactly 65536 cookie bytes', () => { + // 8 cookies: name 1 byte ('k') + value 8191 bytes = 8192 per cookie; + // 8 × 8192 = 65536 total (exact limit, each value ≤ MAX_COOKIE_VALUE_BYTES). + const val = 'x'.repeat(8191) + const cookieRows = Array.from({ length: 8 }, (_, i) => ({ + id: i + 1, name: `k${i}`, value: val.slice(0, 8191 - String(i).length), included: true, + })) + // Simplest: just 8 single-char-name cookies to hit exactly 65536 + const rows = Array.from({ length: 8 }, (_, i) => ({ + id: i, name: String.fromCharCode(97 + i), value: 'x'.repeat(8191), included: true, + })) + // 8 × (1 + 8191) = 8 × 8192 = 65536 + expect(validateBrowserData(make({ cookieRows: rows }))).toBeNull() + }) + + test('fails above 65536 cookie bytes', () => { + // 9 × 8192 = 73728 > 65536 + const rows = Array.from({ length: 9 }, (_, i) => ({ + id: i, name: String.fromCharCode(97 + i), value: 'x'.repeat(8191), included: true, + })) + const err = validateBrowserData(make({ cookieRows: rows })) + expect(err).toMatch(/64 KiB/) + }) + + test('skips cookie validation when useCookies is false', () => { + const cookieRows = [{ id: 1, name: 'a b', value: 'x', included: true }] + expect(validateBrowserData(make({ useCookies: false, cookieRows }))).toBeNull() + }) + + test('skips storage validation when includeStorage is false', () => { + const storageRows = [ + { id: 1, name: 'k', value: 'a', included: true }, + { id: 2, name: 'k', value: 'b', included: true }, + ] + expect(validateBrowserData(make({ includeStorage: false, storageRows }))).toBeNull() + }) +}) + +describe('buildBrowserSessionPayload', () => { + test('omits excluded rows', () => { + const cookieRows = [ + { id: 1, name: 'a', value: 'x', included: true }, + { id: 2, name: 'b', value: 'y', included: false }, + ] + const payload = buildBrowserSessionPayload({ + pageUrl: 'https://example.com/', + useCookies: true, + includeStorage: false, + cookieRows, + storageRows: [], + }) + expect(payload).not.toBeNull() + expect(Object.keys(payload.cookies)).toEqual(['a']) + expect(payload.local_storage).toEqual({}) + }) + + test('returns null when both maps are empty', () => { + const payload = buildBrowserSessionPayload({ + pageUrl: 'https://example.com/', + useCookies: true, + includeStorage: true, + cookieRows: [], + storageRows: [], + }) + expect(payload).toBeNull() + }) + + test('returns null when both toggles are off', () => { + const cookieRows = [{ id: 1, name: 'a', value: 'x', included: true }] + const storageRows = [{ id: 2, name: 'k', value: 'v', included: true }] + const payload = buildBrowserSessionPayload({ + pageUrl: 'https://example.com/', + useCookies: false, + includeStorage: false, + cookieRows, + storageRows, + }) + expect(payload).toBeNull() + }) + + test('includes url in payload', () => { + const cookieRows = [{ id: 1, name: 'a', value: 'x', included: true }] + const payload = buildBrowserSessionPayload({ + pageUrl: 'https://example.com/page', + useCookies: true, + includeStorage: false, + cookieRows, + storageRows: [], + }) + expect(payload.url).toBe('https://example.com/page') + }) +}) diff --git a/frontend/src/components/CaptureBrowserData.jsx b/frontend/src/components/CaptureBrowserData.jsx new file mode 100644 index 0000000..260fafe --- /dev/null +++ b/frontend/src/components/CaptureBrowserData.jsx @@ -0,0 +1,292 @@ +import { toRows } from '../browserData.js' + +/** + * The "Use my cookies" toggle row rendered below the Add URL / Add text buttons. + * Only shown when `browserSession.appliesTo` is true for at least one URL item. + * + * Props: + * browserSession – the browserSession prop from CaptureDialog + * browserData – { status, cookieAccess, cookieRows, storageRows } + * useCookies – boolean + * setUseCookies – setter + */ +export function BrowserSessionToggle({ browserSession, browserData, useCookies, setUseCookies }) { + const { status, cookieAccess, cookieRows } = browserData + const host = browserSession?.host ?? '' + const includedCount = (cookieRows || []).filter(r => r.included).length + + const loading = status === 'loading' || status === 'idle' + const accessMissing = cookieAccess === 'missing' + const hasError = status === 'error' + const disabled = loading || accessMissing || hasError + + let metaContent + if (loading) { + metaContent = Reading cookies… + } else if (hasError) { + metaContent = Couldn't read cookies + } else if (accessMissing) { + metaContent = ( + <> + + + ) + } else { + const cookieText = includedCount === 0 ? 'no cookies' : `${includedCount} ${includedCount === 1 ? 'cookie' : 'cookies'}` + metaContent = {host} · {cookieText} + } + + return ( + + ) +} + +/** + * The browser data section rendered at the bottom of Advanced options. + * Shows Include localStorage toggle, Cookies table, localStorage table. + * + * Props: + * browserSession – the browserSession prop from CaptureDialog + * browserData – { status, cookieAccess, cookieRows, storageRows } + * setBrowserData – setter + * useCookies – boolean + * effectiveUseCookies – boolean (useCookies && access granted) + * includeStorage – boolean + * setIncludeStorage – setter + * browserDataError – string|null + */ +export function BrowserDataSection({ + browserSession, + browserData, + setBrowserData, + effectiveUseCookies, + includeStorage, + storageApplicable, + setIncludeStorage, + browserDataError, +}) { + const host = browserSession?.host ?? '' + const { cookieRows = [], storageRows = [] } = browserData + + function updateCookieRow(id, field, value) { + setBrowserData(prev => ({ + ...prev, + cookieRows: prev.cookieRows.map(r => r.id === id ? { ...r, [field]: value } : r), + })) + } + + function removeCookieRow(id) { + setBrowserData(prev => ({ + ...prev, + cookieRows: prev.cookieRows.filter(r => r.id !== id), + })) + } + + function addCookieRow() { + const newRow = { id: Date.now() + Math.random(), name: '', value: '', included: true } + setBrowserData(prev => ({ ...prev, cookieRows: [...prev.cookieRows, newRow] })) + } + + function updateStorageRow(id, field, value) { + setBrowserData(prev => ({ + ...prev, + storageRows: prev.storageRows.map(r => r.id === id ? { ...r, [field]: value } : r), + })) + } + + function removeStorageRow(id) { + setBrowserData(prev => ({ + ...prev, + storageRows: prev.storageRows.filter(r => r.id !== id), + })) + } + + function addStorageRow() { + const newRow = { id: Date.now() + Math.random(), name: '', value: '', included: true } + setBrowserData(prev => ({ ...prev, storageRows: [...prev.storageRows, newRow] })) + } + + const cookieIncluded = cookieRows.filter(r => r.included).length + const storageIncluded = storageRows.filter(r => r.included).length + + return ( +
+
Browser data · {host}
+ + {/* Include localStorage toggle */} + + + {/* Cookies table */} + {effectiveUseCookies && ( +
+
+ Cookies + {cookieIncluded} of {cookieRows.length} included +
+
+ + + + + + + + + + + {cookieRows.map(row => ( + + + + + + + ))} + +
NameValue
+ updateCookieRow(row.id, 'included', e.target.checked)} + aria-label={`Include ${row.name}`} + /> + + updateCookieRow(row.id, 'name', e.target.value)} + placeholder="name" + aria-label="Cookie name" + /> + {row.httpOnly && HttpOnly} + + updateCookieRow(row.id, 'value', e.target.value)} + placeholder="value" + aria-label="Cookie value" + /> + + +
+
+ +
+ )} + + {/* localStorage table */} + {includeStorage && ( +
+
+ localStorage + {storageIncluded} of {storageRows.length} included +
+
+ + + + + + + + + + + {storageRows.map(row => ( + + + + + + + ))} + +
KeyValue
+ updateStorageRow(row.id, 'included', e.target.checked)} + aria-label={`Include ${row.name}`} + /> + + updateStorageRow(row.id, 'name', e.target.value)} + placeholder="key" + aria-label="localStorage key" + /> + + updateStorageRow(row.id, 'value', e.target.value)} + placeholder="value" + aria-label="localStorage value" + /> + + +
+
+ +
+ )} + + {browserDataError && ( +

+ {browserDataError} +

+ )} +
+ ) +} diff --git a/frontend/src/components/CaptureDialog.jsx b/frontend/src/components/CaptureDialog.jsx index cd1f5ee..b5312bf 100644 --- a/frontend/src/components/CaptureDialog.jsx +++ b/frontend/src/components/CaptureDialog.jsx @@ -1,6 +1,8 @@ import { useRef, useEffect, useState } from 'react' import * as defaultApi from '../api' import { capturePersistenceKey, captureDraftItems, applyGeneratedTitle, applyTitleGenerationError } from '../captureRequests' +import { toRows, validateBrowserData, buildBrowserSessionPayload } from '../browserData.js' +import { BrowserSessionToggle, BrowserDataSection } from './CaptureBrowserData.jsx' let nextItemId = 1 @@ -234,8 +236,7 @@ function applyPlaylistQuality(newQ, currentItems) { function hasConflict(item) { return Array.isArray(item.playlistItems) && item.playlistItems.some(pi => pi.quality === null) } - -export default function CaptureDialog({ open, archiveId, onClose, onCaptured, onToast, onJobStarted, onJobSettled, activeJobs = [], api = defaultApi, initialItems, persistenceKey = 'captureItems', requestKey, allowFileUpload = true }) { +export default function CaptureDialog({ open, archiveId, onClose, onCaptured, onToast, onJobStarted, onJobSettled, activeJobs = [], api = defaultApi, initialItems, persistenceKey = 'captureItems', requestKey, allowFileUpload = true, browserSession = null }) { const draftKey = capturePersistenceKey(persistenceKey, initialItems, requestKey) const apiRef = useRef(api) apiRef.current = api @@ -356,6 +357,52 @@ export default function CaptureDialog({ open, archiveId, onClose, onCaptured, on // Reader mode: off by default, per-session only const [readerMode, setReaderMode] = useState(false) + // ── Browser session (extension-only; null in dashboard) ───────────────────── + // NEVER write cookie or localStorage data to sessionStorage — in the extension + // content script, that is the *page's* sessionStorage. + const [browserData, setBrowserData] = useState({ + status: 'idle', cookieAccess: null, cookieRows: [], storageRows: [], + }) + const cookieAccessRef = useRef(browserData.cookieAccess) + cookieAccessRef.current = browserData.cookieAccess + const [useCookies, setUseCookies] = useState(browserSession?.defaults?.cookies ?? false) + const [includeStorage, setIncludeStorage] = useState(browserSession?.defaults?.localStorage ?? false) + + useEffect(() => { + if (!browserSession) return + let cancelled = false + async function load() { + setBrowserData(prev => ({ ...prev, status: 'loading' })) + try { + const result = await browserSession.load() + if (cancelled) return + setBrowserData({ + status: 'ready', + cookieAccess: result.cookieAccess, + cookieRows: toRows(result.cookies || [], 'name'), + storageRows: toRows(result.localStorage || [], 'key'), + }) + if (result.cookieAccess === 'granted') { + setUseCookies(browserSession.defaults.cookies) + } + } catch { + if (!cancelled) setBrowserData({ status: 'error', cookieAccess: null, cookieRows: [], storageRows: [] }) + } + } + load() + // Re-check when tab regains focus (user may have granted access in the settings tab) + function onVisibility() { + if (document.visibilityState === 'visible' && cookieAccessRef.current === 'missing') { + load() + } + } + document.addEventListener('visibilitychange', onVisibility) + return () => { + cancelled = true + document.removeEventListener('visibilitychange', onVisibility) + } + }, [browserSession]) // eslint-disable-line react-hooks/exhaustive-deps + // On mount: clean up old single-locator sessionStorage keys; reconnect running bg jobs useEffect(() => { ;['captureDialogLocator','captureDialogError','captureDialogBusy', @@ -574,6 +621,7 @@ export default function CaptureDialog({ open, archiveId, onClose, onCaptured, on function handleArchive() { if (!archiveIdRef.current) return + if (browserDataError || browserDataLoading) return // Guard against the Enter-key shortcut in CaptureRow bypassing the // disabled button — uploads must be complete before archiving starts. if (items.some(it => it.kind === 'file' && it.uploadStatus === 'uploading')) return @@ -603,13 +651,28 @@ export default function CaptureDialog({ open, archiveId, onClose, onCaptured, on if (it.kind === 'text') { return { type: 'text', title: it.title.trim(), body: it.body, mime: it.mime } } + const locator = it.locator.trim() + // Cookies are host-scoped; localStorage is scoped to the exact origin. + const sessionPayload = browserSession?.appliesTo(locator) + ? buildBrowserSessionPayload({ + pageUrl: browserSession.pageUrl, + useCookies: effectiveUseCookies, + includeStorage: effectiveIncludeStorage && !!browserSession.storageAppliesTo?.(locator), + cookieRows: browserData.cookieRows, + storageRows: browserData.storageRows, + }) + : null + const browserSessionExt = sessionPayload ? { browser_session: sessionPayload } : {} return { type: 'url', - locator: it.locator.trim(), + locator, quality: it.playlistItems !== null ? null : (it.quality || 'best'), - extraExtensions: it.playlistItems !== null - ? { per_item_quality: Object.fromEntries(it.playlistItems.map(pi => [pi.id, pi.quality])), sync: it.syncEnabled } - : {}, + extraExtensions: { + ...(it.playlistItems !== null + ? { per_item_quality: Object.fromEntries(it.playlistItems.map(pi => [pi.id, pi.quality])), sync: it.syncEnabled } + : {}), + ...browserSessionExt, + }, } }) // Reset form and close dialog immediately. @@ -861,6 +924,20 @@ export default function CaptureDialog({ open, archiveId, onClose, onCaptured, on ) ) + // ── Browser session computed values ───────────────────────────────────────── + const browserApplicable = !!browserSession && items.some( + it => it.kind !== 'text' && it.kind !== 'file' && it.locator.trim() && browserSession.appliesTo(it.locator.trim()) + ) + const storageApplicable = !!browserSession && items.some( + it => it.kind !== 'text' && it.kind !== 'file' && it.locator.trim() && browserSession.storageAppliesTo?.(it.locator.trim()) + ) + const effectiveIncludeStorage = includeStorage && storageApplicable + const effectiveUseCookies = useCookies && browserData.cookieAccess === 'granted' + const browserDataError = browserApplicable + ? validateBrowserData({ useCookies: effectiveUseCookies, includeStorage: effectiveIncludeStorage, cookieRows: browserData.cookieRows, storageRows: browserData.storageRows }) + : null + const browserDataLoading = browserApplicable && (browserData.status === 'idle' || browserData.status === 'loading') + return ( + {/* ── Use my cookies toggle ────────────────────────── */} + {browserApplicable && ( + + )} + {/* ── Advanced options ────────────────────────────── */}
+ {browserApplicable && ( + + )}
)} @@ -1089,7 +1188,7 @@ export default function CaptureDialog({ open, archiveId, onClose, onCaptured, on type="button" className="capture-submit" onClick={handleArchive} - disabled={!archiveId || pendingCount === 0 || anyConflict || anyProbing || anyEmptyPlaylist || anyUploading} + disabled={!archiveId || pendingCount === 0 || anyConflict || anyProbing || anyEmptyPlaylist || anyUploading || browserDataLoading || !!browserDataError} > {pendingCount > 1 ? `Archive ${pendingCount}` : 'Archive'} diff --git a/frontend/src/components/CaptureDialog.test.jsx b/frontend/src/components/CaptureDialog.test.jsx index fc85a9e..7379afe 100644 --- a/frontend/src/components/CaptureDialog.test.jsx +++ b/frontend/src/components/CaptureDialog.test.jsx @@ -195,3 +195,65 @@ describe('manual title controls', () => { expect(markup).toContain('New body') }) }) + +describe('browser session', () => { + // (a) Without browserSession prop, dashboard-invariant: no browser data controls + test('without browserSession the markup contains no browser data controls', () => { + const markup = renderToStaticMarkup( + + ) + expect(markup).not.toContain('Use my cookies') + expect(markup).not.toContain('Include localStorage') + }) + + // (b) With browserSession whose appliesTo returns true: toggle visible, unchecked + test('with matching browserSession the checkbox appears unchecked when defaults.cookies=false', () => { + const browserSession = { + pageUrl: 'https://www.example.com/a', + host: 'www.example.com', + defaults: { cookies: false, localStorage: false }, + appliesTo: () => true, + load: () => new Promise(() => {}), + requestAccess: () => {}, + } + const markup = renderToStaticMarkup( + + ) + expect(markup).toContain('Use my cookies') + // checkbox should not be checked (defaults.cookies = false) + expect(markup).not.toContain('checked="" class="capture-browser-session-row"') + // the checkbox input itself should not have checked + const checkboxMatch = markup.match(/type="checkbox"[^>]*/) + expect(checkboxMatch?.[0] ?? '').not.toContain('checked') + }) + + // (c) With browserSession whose appliesTo returns false: no toggle + test('with non-matching browserSession (appliesTo false) the toggle is not shown', () => { + const browserSession = { + pageUrl: 'https://other.example.com/', + host: 'other.example.com', + defaults: { cookies: true, localStorage: true }, + appliesTo: () => false, + load: () => new Promise(() => {}), + requestAccess: () => {}, + } + const markup = renderToStaticMarkup( + + ) + expect(markup).not.toContain('Use my cookies') + }) +}) diff --git a/frontend/src/styles.css b/frontend/src/styles.css index 0275236..73cb8f6 100644 --- a/frontend/src/styles.css +++ b/frontend/src/styles.css @@ -822,6 +822,155 @@ select { margin-top: 1px; } +/* ── Capture dialog: browser session toggle ─────────────────────────────── */ +.capture-browser-session-row { + display: flex; + align-items: center; + gap: 8px; + margin: -8px 0 0; + font-size: 13px; + color: var(--ink); + cursor: pointer; +} +.capture-browser-session-row input[type="checkbox"] { + width: 14px; + height: 14px; + margin: 0; + accent-color: var(--ink); + cursor: pointer; + flex-shrink: 0; +} +.capture-browser-session-label { + font-weight: 600; + white-space: nowrap; +} +.capture-browser-session-meta { + font-size: 12px; + color: var(--muted); + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.capture-browser-session-grant { + background: none; + border: 0; + padding: 0; + color: var(--link, var(--accent-2)); + font-size: 12px; + cursor: pointer; + text-decoration: underline; +} + +/* ── Capture dialog: browser data section (Advanced options) ─────────────── */ +.capture-browser-data { + margin-top: 12px; + padding-top: 10px; + border-top: 1px solid var(--line); +} +.capture-browser-data-title { + font-size: 11px; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.04em; + color: var(--muted); + margin-bottom: 8px; +} +.capture-kv { + margin-top: 10px; +} +.capture-kv-head { + display: flex; + justify-content: space-between; + font-size: 12.5px; + font-weight: 600; + margin-bottom: 4px; +} +.capture-kv-head span:last-child { + font-weight: 400; + color: var(--muted); +} +.capture-kv-scroll { + max-height: 220px; + overflow: auto; + border: 1px solid var(--line); + border-radius: var(--r); + background: var(--field); +} +.capture-kv-table { + width: 100%; + border-collapse: collapse; + table-layout: fixed; + font-size: 12px; +} +.capture-kv-table th { + position: sticky; + top: 0; + background: var(--paper-2); + font-size: 11px; + color: var(--muted); + font-weight: 600; + padding: 5px 6px; + text-align: left; +} +.capture-kv-table td { + padding: 2px 4px; + border-bottom: 1px solid var(--line-soft); +} +.capture-kv-table tr:last-child td { + border-bottom: none; +} +.capture-kv-input { + width: 100%; + background: transparent; + border: 1px solid transparent; + padding: 4px 6px; + border-radius: var(--r); + font-family: ui-monospace, SFMono-Regular, Menlo, monospace; + font-size: 12px; + color: inherit; + box-sizing: border-box; +} +.capture-kv-input:focus { + border-color: var(--accent-2); + outline: none; +} +.capture-kv-row--excluded .capture-kv-input { + color: var(--muted); + text-decoration: line-through; +} +.capture-kv-badge { + font-size: 10px; + text-transform: uppercase; + border: 1px solid var(--line); + border-radius: var(--r); + padding: 0 4px; + color: var(--muted); + margin-left: 4px; + vertical-align: middle; + white-space: nowrap; +} +.capture-kv-remove { + background: none; + border: none; + padding: 2px 4px; + cursor: pointer; + color: var(--muted); + font-size: 14px; + line-height: 1; +} +.capture-kv-remove:hover { + color: var(--ink); +} +.capture-kv-add { + margin: 6px 0 0; + border-style: dashed; +} +.capture-browser-data-error { + padding-left: 0; + margin-top: 8px; +} + /* ── Capture dialog: header + multi-row ─────────────────────────────────── */ .capture-dialog-header { display: flex;