Skip to content

Open-source download manager & offline media toolbox for YouTube, music, social media, learning platforms & 1,800+ sites. Built with Tauri 2.0, Rust & Svelte.

feat(cookies): implement cookie management commands and storage structure

Tonho292c1972544f
diff --git a/src-tauri/src/cookies/commands.rs b/src-tauri/src/cookies/commands.rs
new file mode 100644
index 00000000..609f5863
--- /dev/null
+++ b/src-tauri/src/cookies/commands.rs
@@ -0,0 +1,154 @@
+//! Tauri commands exposed to the Settings → Cookies UI.
+
+use serde::{Deserialize, Serialize};
+
+use super::parsers;
+use super::platform::PlatformKind;
+use super::storage::{
+ self, AccountEntry, CookieRegistry, IngestSource,
+};
+
+#[derive(Debug, Serialize)]
+pub struct CookieListResponse {
+ pub registry: CookieRegistry,
+ pub cookies_dir: String,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct ImportRequest {
+ pub content: String,
+ #[serde(default)]
+ pub source_url: Option<String>,
+ #[serde(default)]
+ pub source_label: Option<String>,
+ #[serde(default)]
+ pub alias: Option<String>,
+}
+
+#[derive(Debug, Serialize)]
+pub struct ImportResponse {
+ pub buckets_written: Vec<BucketWrite>,
+}
+
+#[derive(Debug, Serialize)]
+pub struct BucketWrite {
+ pub domain: String,
+ pub cookie_count: usize,
+ pub platform_kind: String,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct ReadRequest {
+ pub domain: String,
+ #[serde(default)]
+ pub slug: Option<String>,
+}
+
+#[derive(Debug, Serialize)]
+pub struct ReadResponse {
+ pub content: String,
+ pub path: String,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct ClearRequest {
+ pub domain: String,
+ #[serde(default)]
+ pub slug: Option<String>,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct RenameRequest {
+ pub domain: String,
+ #[serde(default)]
+ pub slug: Option<String>,
+ pub new_alias: String,
+}
+
+#[derive(Debug, Serialize)]
+pub struct OkResponse {
+ pub ok: bool,
+}
+
+const DEFAULT_SLUG: &str = "_default";
+
+#[tauri::command]
+pub async fn cookies_list() -> Result<CookieListResponse, String> {
+ let registry = storage::load_registry();
+ let cookies_dir = storage::cookies_root().to_string_lossy().into_owned();
+ Ok(CookieListResponse { registry, cookies_dir })
+}
+
+#[tauri::command]
+pub async fn cookies_read(request: ReadRequest) -> Result<ReadResponse, String> {
+ let slug = request.slug.as_deref().unwrap_or(DEFAULT_SLUG);
+ let content = storage::read_account_file(&request.domain, slug).map_err(|e| e.to_string())?;
+ let path = storage::account_file(&request.domain, slug).to_string_lossy().into_owned();
+ Ok(ReadResponse { content, path })
+}
+
+#[tauri::command]
+pub async fn cookies_import(request: ImportRequest) -> Result<ImportResponse, String> {
+ let cookies = parsers::parse(&request.content).map_err(|e| e.to_string())?;
+ if cookies.is_empty() {
+ return Err("No cookies found in payload".to_string());
+ }
+ let label = request.source_label.unwrap_or_else(|| "Manual import".to_string());
+ let written = storage::ingest_batch(
+ &cookies,
+ IngestSource {
+ source_url: request.source_url,
+ source_label: label,
+ alias_hint: request.alias,
+ },
+ )
+ .map_err(|e| e.to_string())?;
+
+ let buckets_written = written
+ .into_iter()
+ .map(|(domain, cookie_count)| {
+ let platform_kind = PlatformKind::from_domain(&domain).as_str().to_string();
+ BucketWrite { domain, cookie_count, platform_kind }
+ })
+ .collect();
+ Ok(ImportResponse { buckets_written })
+}
+
+#[tauri::command]
+pub async fn cookies_clear(request: ClearRequest) -> Result<OkResponse, String> {
+ let slug = request.slug.as_deref().unwrap_or(DEFAULT_SLUG);
+ storage::move_to_trash(&request.domain, slug).map_err(|e| e.to_string())?;
+ Ok(OkResponse { ok: true })
+}
+
+#[tauri::command]
+pub async fn cookies_rename(request: RenameRequest) -> Result<OkResponse, String> {
+ let slug = request.slug.as_deref().unwrap_or(DEFAULT_SLUG);
+ if request.new_alias.trim().is_empty() {
+ return Err("Alias cannot be empty".to_string());
+ }
+ storage::rename_account(&request.domain, slug, request.new_alias.trim())
+ .map_err(|e| e.to_string())?;
+ Ok(OkResponse { ok: true })
+}
+
+#[tauri::command]
+pub async fn cookies_migrate_legacy() -> Result<OkResponse, String> {
+ storage::migrate_legacy_if_needed().map_err(|e| e.to_string())?;
+ Ok(OkResponse { ok: true })
+}
+
+#[tauri::command]
+pub async fn cookies_detect_platform(domain: String) -> Result<String, String> {
+ Ok(PlatformKind::from_domain(&domain).as_str().to_string())
+}
+
+#[allow(dead_code)]
+pub fn list_accounts_for_domain(domain: &str) -> Vec<AccountEntry> {
+ let registry = storage::load_registry();
+ registry
+ .buckets
+ .get(domain)
+ .map(|b| b.accounts.clone())
+ .unwrap_or_default()
+}
diff --git a/src-tauri/src/cookies/mod.rs b/src-tauri/src/cookies/mod.rs
new file mode 100644
index 00000000..cae73dbd
--- /dev/null
+++ b/src-tauri/src/cookies/mod.rs
@@ -0,0 +1,24 @@
+//! Cookie Manager — multi-platform per-domain cookie storage.
+//!
+//! Lives on top of the legacy single-file `chrome-extension-cookies.txt` (see
+//! `extension_storage`). The bridge endpoints (`/v1/enqueue`, `/v1/cookies`)
+//! and the existing native message path continue to write the legacy file for
+//! backwards compatibility with plugins compiled against SDK v2; this module
+//! is invoked in parallel so plugins compiled against v3+ see the new layout.
+//!
+//! Module layout:
+//! * `platform` — domain → `PlatformKind` mapping (drives UI logo + copy)
+//! * `parsers` — Netscape and JSON cookie import
+//! * `storage` — on-disk layout, `_meta.json` registry, transactional writes
+//! * `commands` — Tauri commands consumed by Settings → Cookies UI
+
+pub mod commands;
+pub mod parsers;
+pub mod platform;
+pub mod storage;
+
+pub use platform::{root_domain_of, PlatformKind};
+pub use storage::{
+ account_path_for_consumer, ingest_batch, load_registry, migrate_legacy_if_needed,
+ AccountEntry, BucketEntry, CookieRegistry, IngestSource,
+};
diff --git a/src-tauri/src/cookies/parsers.rs b/src-tauri/src/cookies/parsers.rs
new file mode 100644
index 00000000..1e030377
--- /dev/null
+++ b/src-tauri/src/cookies/parsers.rs
@@ -0,0 +1,231 @@
+//! Parse cookie payloads from different formats into the canonical
+//! `ExtensionCookie` shape used by `extension_storage` and yt-dlp.
+//!
+//! Two formats are accepted on import:
+//! * Netscape (`# Netscape HTTP Cookie File`, tab-separated 7 fields) — the
+//! format yt-dlp itself uses; also produced by Loop and
+//! Get-cookies.txt-LOCALLY.
+//! * JSON array — produced by Edit-This-Cookie and recent
+//! Get-cookies.txt-LOCALLY versions.
+//!
+//! Detection is content-based, not extension-based: the first non-whitespace
+//! character drives the choice.
+
+use serde::Deserialize;
+
+use crate::extension_storage::ExtensionCookie;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum CookieFormat {
+ Netscape,
+ Json,
+ Unknown,
+}
+
+pub fn detect_format(content: &str) -> CookieFormat {
+ let trimmed = content.trim_start();
+ if trimmed.is_empty() {
+ return CookieFormat::Unknown;
+ }
+ let first = trimmed.chars().next().unwrap_or(' ');
+ if first == '[' || first == '{' {
+ return CookieFormat::Json;
+ }
+ if trimmed.starts_with("# Netscape") || trimmed.starts_with("#HttpOnly_") || trimmed.contains('\t') {
+ return CookieFormat::Netscape;
+ }
+ CookieFormat::Unknown
+}
+
+pub fn parse(content: &str) -> anyhow::Result<Vec<ExtensionCookie>> {
+ match detect_format(content) {
+ CookieFormat::Netscape => parse_netscape(content),
+ CookieFormat::Json => parse_json(content),
+ CookieFormat::Unknown => {
+ anyhow::bail!("Unrecognized cookie format. Accepted: Netscape (yt-dlp), JSON (Edit-This-Cookie, Get-cookies.txt-LOCALLY).")
+ }
+ }
+}
+
+pub fn parse_netscape(content: &str) -> anyhow::Result<Vec<ExtensionCookie>> {
+ let mut cookies = Vec::new();
+ for raw in content.lines() {
+ let trimmed = raw.trim_end();
+ if trimmed.is_empty() {
+ continue;
+ }
+ let (effective, http_only) = if let Some(rest) = trimmed.strip_prefix("#HttpOnly_") {
+ (rest, true)
+ } else if trimmed.starts_with('#') {
+ continue;
+ } else {
+ (trimmed, false)
+ };
+ let parts: Vec<&str> = effective.split('\t').collect();
+ if parts.len() < 7 {
+ continue;
+ }
+ let domain = parts[0].to_string();
+ let include_subdomains = parts[1].eq_ignore_ascii_case("TRUE");
+ let path = parts[2].to_string();
+ let secure = parts[3].eq_ignore_ascii_case("TRUE");
+ let expires = parts[4].parse::<i64>().unwrap_or(0);
+ let name = parts[5].to_string();
+ let value = parts[6..].join("\t");
+ cookies.push(ExtensionCookie {
+ domain,
+ http_only,
+ path,
+ secure,
+ expires,
+ name,
+ value,
+ host_only: Some(!include_subdomains),
+ same_site: None,
+ });
+ }
+ Ok(cookies)
+}
+
+#[derive(Debug, Deserialize)]
+struct JsonCookie {
+ domain: String,
+ #[serde(default)]
+ path: Option<String>,
+ #[serde(default, alias = "httpOnly")]
+ http_only: Option<bool>,
+ #[serde(default)]
+ secure: Option<bool>,
+ #[serde(default, alias = "expirationDate", alias = "expires")]
+ expiration: Option<f64>,
+ name: String,
+ value: String,
+ #[serde(default, alias = "hostOnly")]
+ host_only: Option<bool>,
+ #[serde(default, alias = "sameSite")]
+ same_site: Option<String>,
+ #[serde(default)]
+ session: Option<bool>,
+}
+
+pub fn parse_json(content: &str) -> anyhow::Result<Vec<ExtensionCookie>> {
+ let raw: serde_json::Value = serde_json::from_str(content)
+ .map_err(|e| anyhow::anyhow!("invalid JSON: {e}"))?;
+ let arr = match raw {
+ serde_json::Value::Array(a) => a,
+ serde_json::Value::Object(_) => vec![raw],
+ _ => anyhow::bail!("Expected a JSON array of cookie objects."),
+ };
+ let mut cookies = Vec::with_capacity(arr.len());
+ for item in arr {
+ let parsed: JsonCookie = match serde_json::from_value(item) {
+ Ok(c) => c,
+ Err(_) => continue,
+ };
+ let expires = match (parsed.session.unwrap_or(false), parsed.expiration) {
+ (true, _) => 0,
+ (false, Some(f)) => f as i64,
+ (false, None) => 0,
+ };
+ cookies.push(ExtensionCookie {
+ domain: parsed.domain,
+ http_only: parsed.http_only.unwrap_or(false),
+ path: parsed.path.unwrap_or_else(|| "/".to_string()),
+ secure: parsed.secure.unwrap_or(false),
+ expires,
+ name: parsed.name,
+ value: parsed.value,
+ host_only: parsed.host_only,
+ same_site: parsed.same_site,
+ });
+ }
+ Ok(cookies)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn detect_netscape_header() {
+ assert_eq!(detect_format("# Netscape HTTP Cookie File\n.foo\tTRUE\t/\tTRUE\t0\ta\tb"), CookieFormat::Netscape);
+ }
+
+ #[test]
+ fn detect_json_array() {
+ assert_eq!(detect_format("[{\"domain\":\"x.com\"}]"), CookieFormat::Json);
+ }
+
+ #[test]
+ fn detect_tab_separated_without_header() {
+ assert_eq!(detect_format(".x.com\tTRUE\t/\tTRUE\t0\tname\tvalue"), CookieFormat::Netscape);
+ }
+
+ #[test]
+ fn detect_unknown_returns_unknown() {
+ assert_eq!(detect_format("just some text"), CookieFormat::Unknown);
+ assert_eq!(detect_format(""), CookieFormat::Unknown);
+ }
+
+ #[test]
+ fn parse_netscape_basic() {
+ let raw = "# Netscape HTTP Cookie File\n.youtube.com\tTRUE\t/\tTRUE\t1830000000\tSID\tabc123\n";
+ let cookies = parse_netscape(raw).unwrap();
+ assert_eq!(cookies.len(), 1);
+ assert_eq!(cookies[0].domain, ".youtube.com");
+ assert_eq!(cookies[0].name, "SID");
+ assert_eq!(cookies[0].value, "abc123");
+ assert_eq!(cookies[0].expires, 1830000000);
+ assert!(cookies[0].secure);
+ }
+
+ #[test]
+ fn parse_netscape_httponly_prefix() {
+ let raw = "#HttpOnly_.youtube.com\tTRUE\t/\tTRUE\t1830000000\tHSID\txyz\n";
+ let cookies = parse_netscape(raw).unwrap();
+ assert_eq!(cookies.len(), 1);
+ assert!(cookies[0].http_only);
+ assert_eq!(cookies[0].domain, ".youtube.com");
+ }
+
+ #[test]
+ fn parse_netscape_skips_comments_and_short_lines() {
+ let raw = "# header\n.x.com\tTRUE\t/\tTRUE\t0\tk\tv\nbroken line\n";
+ let cookies = parse_netscape(raw).unwrap();
+ assert_eq!(cookies.len(), 1);
+ }
+
+ #[test]
+ fn parse_json_edit_this_cookie() {
+ let raw = r#"[{"domain":".youtube.com","expirationDate":1830000000.5,"hostOnly":false,"httpOnly":true,"name":"SID","path":"/","sameSite":"no_restriction","secure":true,"session":false,"value":"abc123"}]"#;
+ let cookies = parse_json(raw).unwrap();
+ assert_eq!(cookies.len(), 1);
+ assert_eq!(cookies[0].domain, ".youtube.com");
+ assert_eq!(cookies[0].name, "SID");
+ assert_eq!(cookies[0].expires, 1830000000);
+ assert!(cookies[0].http_only);
+ assert!(cookies[0].secure);
+ }
+
+ #[test]
+ fn parse_json_session_cookie_zeros_expiration() {
+ let raw = r#"[{"domain":"x.com","name":"sess","value":"v","session":true,"path":"/","secure":false}]"#;
+ let cookies = parse_json(raw).unwrap();
+ assert_eq!(cookies[0].expires, 0);
+ }
+
+ #[test]
+ fn parse_json_skips_malformed_entries_but_keeps_valid() {
+ let raw = r#"[{"name":"missing_domain","value":"v"},{"domain":".ok.com","name":"k","value":"v","path":"/"}]"#;
+ let cookies = parse_json(raw).unwrap();
+ assert_eq!(cookies.len(), 1);
+ assert_eq!(cookies[0].domain, ".ok.com");
+ }
+
+ #[test]
+ fn dispatch_via_parse() {
+ assert_eq!(parse("[]").unwrap().len(), 0);
+ assert_eq!(parse(".x.com\tTRUE\t/\tTRUE\t0\tk\tv").unwrap().len(), 1);
+ assert!(parse("just text").is_err());
+ }
+}
diff --git a/src-tauri/src/cookies/platform.rs b/src-tauri/src/cookies/platform.rs
new file mode 100644
index 00000000..fd4fa9cf
--- /dev/null
+++ b/src-tauri/src/cookies/platform.rs
@@ -0,0 +1,120 @@
+//! Map an HTTP domain to a `platform_kind` used by the UI and by plugin
+//! consumers. The mapping is deterministic and intentionally narrow — only
+//! platforms with first-class support get a dedicated kind; everything else
+//! falls back to `generic` and is identified by domain alone.
+//!
+//! Kept separate from `storage.rs` so the platform list can evolve without
+//! touching the on-disk format.
+
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum PlatformKind {
+ Youtube,
+ YoutubeMusic,
+ SoundCloud,
+ Spotify,
+ Twitch,
+ Instagram,
+ XTwitter,
+ Vimeo,
+ Tiktok,
+ Bilibili,
+ Reddit,
+ Pinterest,
+ Bluesky,
+ Generic,
+}
+
+impl PlatformKind {
+ pub fn as_str(&self) -> &'static str {
+ match self {
+ PlatformKind::Youtube => "youtube",
+ PlatformKind::YoutubeMusic => "youtube_music",
+ PlatformKind::SoundCloud => "soundcloud",
+ PlatformKind::Spotify => "spotify",
+ PlatformKind::Twitch => "twitch",
+ PlatformKind::Instagram => "instagram",
+ PlatformKind::XTwitter => "x_twitter",
+ PlatformKind::Vimeo => "vimeo",
+ PlatformKind::Tiktok => "tiktok",
+ PlatformKind::Bilibili => "bilibili",
+ PlatformKind::Reddit => "reddit",
+ PlatformKind::Pinterest => "pinterest",
+ PlatformKind::Bluesky => "bluesky",
+ PlatformKind::Generic => "generic",
+ }
+ }
+
+ pub fn from_domain(domain: &str) -> PlatformKind {
+ let host = domain.trim_start_matches('.').to_lowercase();
+ if host == "music.youtube.com" {
+ return PlatformKind::YoutubeMusic;
+ }
+ let root = root_domain_of(&host);
+ match root.as_str() {
+ "youtube.com" | "youtu.be" => PlatformKind::Youtube,
+ "soundcloud.com" => PlatformKind::SoundCloud,
+ "spotify.com" => PlatformKind::Spotify,
+ "twitch.tv" => PlatformKind::Twitch,
+ "instagram.com" => PlatformKind::Instagram,
+ "x.com" | "twitter.com" => PlatformKind::XTwitter,
+ "vimeo.com" => PlatformKind::Vimeo,
+ "tiktok.com" => PlatformKind::Tiktok,
+ "bilibili.com" => PlatformKind::Bilibili,
+ "reddit.com" => PlatformKind::Reddit,
+ "pinterest.com" => PlatformKind::Pinterest,
+ "bsky.app" | "bsky.social" => PlatformKind::Bluesky,
+ _ => PlatformKind::Generic,
+ }
+ }
+}
+
+pub fn root_domain_of(host: &str) -> String {
+ let h = host.trim_start_matches('.').to_lowercase();
+ let parts: Vec<&str> = h.split('.').collect();
+ if parts.len() >= 2 {
+ parts[parts.len() - 2..].join(".")
+ } else {
+ h
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn youtube_variants_map_correctly() {
+ assert_eq!(PlatformKind::from_domain("youtube.com"), PlatformKind::Youtube);
+ assert_eq!(PlatformKind::from_domain(".youtube.com"), PlatformKind::Youtube);
+ assert_eq!(PlatformKind::from_domain("www.youtube.com"), PlatformKind::Youtube);
+ assert_eq!(PlatformKind::from_domain("music.youtube.com"), PlatformKind::YoutubeMusic);
+ assert_eq!(PlatformKind::from_domain("youtu.be"), PlatformKind::Youtube);
+ }
+
+ #[test]
+ fn twitter_x_share_kind() {
+ assert_eq!(PlatformKind::from_domain("x.com"), PlatformKind::XTwitter);
+ assert_eq!(PlatformKind::from_domain("twitter.com"), PlatformKind::XTwitter);
+ }
+
+ #[test]
+ fn unknown_falls_to_generic() {
+ assert_eq!(PlatformKind::from_domain("example.com"), PlatformKind::Generic);
+ assert_eq!(PlatformKind::from_domain("bandcamp.com"), PlatformKind::Generic);
+ }
+
+ #[test]
+ fn root_strips_subdomain() {
+ assert_eq!(root_domain_of("music.youtube.com"), "youtube.com");
+ assert_eq!(root_domain_of("api.soundcloud.com"), "soundcloud.com");
+ assert_eq!(root_domain_of("localhost"), "localhost");
+ }
+
+ #[test]
+ fn root_handles_leading_dot() {
+ assert_eq!(root_domain_of(".youtube.com"), "youtube.com");
+ }
+}
diff --git a/src-tauri/src/cookies/storage.rs b/src-tauri/src/cookies/storage.rs
new file mode 100644
index 00000000..49f5c0f9
--- /dev/null
+++ b/src-tauri/src/cookies/storage.rs
@@ -0,0 +1,417 @@
+//! On-disk layout for the cookie manager.
+//!
+//! ```text
+//! <app_data>/
+//! cookies/
+//! <root_domain>/
+//! _default.txt # primary account (Netscape, yt-dlp consumable)
+//! <slug>.txt # additional accounts (multi-account UX, CK-5)
+//! _meta.json # registry: alias, source, captured_at, platform_kind
+//! _trash/ # 24h-retention bin for `cookies:clear`
+//! ```
+//!
+//! The format inside each file is Netscape — same as the legacy
+//! `chrome-extension-cookies.txt` so yt-dlp consumes it unchanged.
+
+use std::collections::BTreeMap;
+use std::fs;
+use std::path::{Path, PathBuf};
+
+use serde::{Deserialize, Serialize};
+
+use super::platform::{root_domain_of, PlatformKind};
+use crate::extension_storage::ExtensionCookie;
+
+const META_FILE: &str = "_meta.json";
+const DEFAULT_SLUG: &str = "_default";
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct AccountEntry {
+ pub slug: String,
+ pub alias: String,
+ #[serde(default)]
+ pub source_url: Option<String>,
+ #[serde(default)]
+ pub source_label: Option<String>,
+ pub captured_at_ms: i64,
+ pub cookie_count: usize,
+ #[serde(default)]
+ pub last_used_at_ms: Option<i64>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, Default)]
+pub struct BucketEntry {
+ pub platform_kind: String,
+ pub accounts: Vec<AccountEntry>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, Default)]
+pub struct CookieRegistry {
+ #[serde(default)]
+ pub buckets: BTreeMap<String, BucketEntry>,
+}
+
+pub fn cookies_root() -> PathBuf {
+ crate::core::paths::app_data_dir()
+ .unwrap_or_else(|| PathBuf::from("."))
+ .join("cookies")
+}
+
+pub fn bucket_dir(domain: &str) -> PathBuf {
+ cookies_root().join(safe_domain_segment(domain))
+}
+
+pub fn account_file(domain: &str, slug: &str) -> PathBuf {
+ bucket_dir(domain).join(format!("{}.txt", safe_slug_segment(slug)))
+}
+
+pub fn meta_path() -> PathBuf {
+ cookies_root().join(META_FILE)
+}
+
+pub fn trash_dir() -> PathBuf {
+ cookies_root().join("_trash")
+}
+
+fn safe_domain_segment(domain: &str) -> String {
+ let h = domain.trim_start_matches('.').to_lowercase();
+ h.chars()
+ .map(|c| if c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == '_' { c } else { '_' })
+ .collect()
+}
+
+fn safe_slug_segment(slug: &str) -> String {
+ let lowered = slug.to_lowercase();
+ let cleaned: String = lowered
+ .chars()
+ .map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '-' })
+ .collect();
+ if cleaned.is_empty() { DEFAULT_SLUG.to_string() } else { cleaned }
+}
+
+pub fn load_registry() -> CookieRegistry {
+ let path = meta_path();
+ let content = match fs::read_to_string(&path) {
+ Ok(c) => c,
+ Err(_) => return CookieRegistry::default(),
+ };
+ serde_json::from_str(&content).unwrap_or_default()
+}
+
+pub fn save_registry(registry: &CookieRegistry) -> anyhow::Result<()> {
+ let path = meta_path();
+ if let Some(parent) = path.parent() {
+ fs::create_dir_all(parent)?;
+ }
+ let serialized = serde_json::to_string_pretty(registry)?;
+ let tmp = path.with_extension("json.tmp");
+ fs::write(&tmp, serialized)?;
+ fs::rename(&tmp, &path)?;
+ Ok(())
+}
+
+pub fn current_unix_ms() -> i64 {
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_millis() as i64)
+ .unwrap_or(0)
+}
+
+fn format_cookie_line(c: &ExtensionCookie, session_ttl: u64) -> String {
+ let raw_domain = sanitize_field(&c.domain);
+ let path_field = sanitize_field(&c.path);
+ let name = sanitize_field(&c.name);
+ let value = sanitize_field(&c.value);
+ let http_only_prefix = if c.http_only { "#HttpOnly_" } else { "" };
+ let is_host_only = c.host_only.unwrap_or_else(|| !raw_domain.starts_with('.'));
+ let (domain, include_subdomains) = if is_host_only {
+ let stripped = raw_domain.strip_prefix('.').unwrap_or(&raw_domain).to_string();
+ (stripped, "FALSE")
+ } else if raw_domain.starts_with('.') {
+ (raw_domain.clone(), "TRUE")
+ } else {
+ (format!(".{}", raw_domain), "TRUE")
+ };
+ let secure = if c.secure { "TRUE" } else { "FALSE" };
+ let expires = if c.expires == 0 { session_ttl } else { c.expires as u64 };
+ format!(
+ "{}{}\t{}\t{}\t{}\t{}\t{}\t{}\n",
+ http_only_prefix, domain, include_subdomains, path_field, secure, expires, name, value,
+ )
+}
+
+fn sanitize_field(s: &str) -> String {
+ s.chars().filter(|c| *c != '\n' && *c != '\r' && *c != '\t').collect()
+}
+
+pub struct IngestSource {
+ pub source_url: Option<String>,
+ pub source_label: String,
+ pub alias_hint: Option<String>,
+}
+
+pub fn write_account_file(
+ domain: &str,
+ slug: &str,
+ cookies: &[ExtensionCookie],
+) -> anyhow::Result<usize> {
+ let path = account_file(domain, slug);
+ if let Some(parent) = path.parent() {
+ fs::create_dir_all(parent)?;
+ }
+ let now = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_secs())
+ .unwrap_or(0);
+ let session_ttl = now + 86400;
+ let mut content = String::from("# Netscape HTTP Cookie File\n");
+ for c in cookies {
+ content.push_str(&format_cookie_line(c, session_ttl));
+ }
+ fs::write(&path, content)?;
+
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ fs::set_permissions(&path, fs::Permissions::from_mode(0o600))?;
+ }
+
+ Ok(cookies.len())
+}
+
+pub fn ingest_batch(
+ cookies: &[ExtensionCookie],
+ source: IngestSource,
+) -> anyhow::Result<Vec<(String, usize)>> {
+ let mut by_root: BTreeMap<String, Vec<ExtensionCookie>> = BTreeMap::new();
+ for c in cookies {
+ let root = root_domain_of(&c.domain);
+ if root.is_empty() {
+ continue;
+ }
+ by_root.entry(root).or_default().push(c.clone());
+ }
+
+ let mut registry = load_registry();
+ let mut written: Vec<(String, usize)> = Vec::new();
+ let now = current_unix_ms();
+
+ for (root, group) in by_root.iter() {
+ let count = write_account_file(root, DEFAULT_SLUG, group)?;
+ let platform = PlatformKind::from_domain(root);
+ let bucket = registry.buckets.entry(root.clone()).or_insert_with(|| BucketEntry {
+ platform_kind: platform.as_str().to_string(),
+ accounts: Vec::new(),
+ });
+ bucket.platform_kind = platform.as_str().to_string();
+
+ let alias_default = format!(
+ "{} · {}",
+ platform_display(platform),
+ human_date(now),
+ );
+ let new_alias = source.alias_hint.clone().unwrap_or(alias_default);
+
+ if let Some(existing) = bucket.accounts.iter_mut().find(|a| a.slug == DEFAULT_SLUG) {
+ existing.captured_at_ms = now;
+ existing.cookie_count = count;
+ if let Some(ref u) = source.source_url {
+ existing.source_url = Some(u.clone());
+ }
+ existing.source_label = Some(source.source_label.clone());
+ if source.alias_hint.is_some() {
+ existing.alias = new_alias;
+ }
+ } else {
+ bucket.accounts.push(AccountEntry {
+ slug: DEFAULT_SLUG.to_string(),
+ alias: new_alias,
+ source_url: source.source_url.clone(),
+ source_label: Some(source.source_label.clone()),
+ captured_at_ms: now,
+ cookie_count: count,
+ last_used_at_ms: None,
+ });
+ }
+
+ written.push((root.clone(), count));
+ }
+
+ save_registry(&registry)?;
+ Ok(written)
+}
+
+fn platform_display(p: PlatformKind) -> &'static str {
+ match p {
+ PlatformKind::Youtube => "YouTube",
+ PlatformKind::YoutubeMusic => "YouTube Music",
+ PlatformKind::SoundCloud => "SoundCloud",
+ PlatformKind::Spotify => "Spotify",
+ PlatformKind::Twitch => "Twitch",
+ PlatformKind::Instagram => "Instagram",
+ PlatformKind::XTwitter => "X",
+ PlatformKind::Vimeo => "Vimeo",
+ PlatformKind::Tiktok => "TikTok",
+ PlatformKind::Bilibili => "Bilibili",
+ PlatformKind::Reddit => "Reddit",
+ PlatformKind::Pinterest => "Pinterest",
+ PlatformKind::Bluesky => "Bluesky",
+ PlatformKind::Generic => "Site",
+ }
+}
+
+fn human_date(ms: i64) -> String {
+ let secs = (ms / 1000) as u64;
+ let days = secs / 86400;
+ let years = 1970 + (days / 365);
+ let day_of_year = days % 365;
+ let month = (day_of_year / 30).min(11);
+ let day = (day_of_year % 30) + 1;
+ format!("{:04}-{:02}-{:02}", years, month + 1, day)
+}
+
+pub fn read_account_file(domain: &str, slug: &str) -> anyhow::Result<String> {
+ let path = account_file(domain, slug);
+ Ok(fs::read_to_string(path)?)
+}
+
+pub fn move_to_trash(domain: &str, slug: &str) -> anyhow::Result<()> {
+ let src = account_file(domain, slug);
+ if !src.exists() {
+ return Ok(());
+ }
+ let trash = trash_dir();
+ fs::create_dir_all(&trash)?;
+ let stamp = current_unix_ms();
+ let dst_name = format!("{}__{}__{}.txt", safe_domain_segment(domain), safe_slug_segment(slug), stamp);
+ let dst = trash.join(dst_name);
+ fs::rename(&src, &dst)?;
+
+ let mut registry = load_registry();
+ if let Some(bucket) = registry.buckets.get_mut(domain) {
+ bucket.accounts.retain(|a| a.slug != slug);
+ if bucket.accounts.is_empty() {
+ registry.buckets.remove(domain);
+ }
+ }
+ save_registry(&registry)?;
+
+ let dir = bucket_dir(domain);
+ if dir.exists() {
+ if let Ok(mut entries) = fs::read_dir(&dir) {
+ if entries.next().is_none() {
+ let _ = fs::remove_dir(&dir);
+ }
+ }
+ }
+ Ok(())
+}
+
+pub fn rename_account(domain: &str, slug: &str, new_alias: &str) -> anyhow::Result<()> {
+ let mut registry = load_registry();
+ let bucket = registry
+ .buckets
+ .get_mut(domain)
+ .ok_or_else(|| anyhow::anyhow!("bucket not found: {domain}"))?;
+ let account = bucket
+ .accounts
+ .iter_mut()
+ .find(|a| a.slug == slug)
+ .ok_or_else(|| anyhow::anyhow!("account not found: {slug}"))?;
+ account.alias = new_alias.to_string();
+ save_registry(&registry)?;
+ Ok(())
+}
+
+pub fn account_path_for_consumer(domain: &str, slug: Option<&str>) -> Option<PathBuf> {
+ let slug = slug.unwrap_or(DEFAULT_SLUG);
+ let path = account_file(domain, slug);
+ if path.exists() { Some(path) } else { None }
+}
+
+pub fn migrate_legacy_if_needed() -> anyhow::Result<usize> {
+ let legacy = crate::extension_storage::extension_cookie_file_path();
+ if !legacy.exists() {
+ return Ok(0);
+ }
+ let raw = fs::read_to_string(&legacy)?;
+ let cookies = super::parsers::parse_netscape(&raw)?;
+ if cookies.is_empty() {
+ return Ok(0);
+ }
+ let written = ingest_batch(
+ &cookies,
+ IngestSource {
+ source_url: None,
+ source_label: "Migrated from legacy single-file storage".to_string(),
+ alias_hint: None,
+ },
+ )?;
+ Ok(written.len())
+}
+
+pub fn has_been_migrated() -> bool {
+ let registry = load_registry();
+ !registry.buckets.is_empty()
+}
+
+pub fn migrate_path(path: &Path) -> PathBuf {
+ cookies_root().join(".migrated").join(
+ path.file_name()
+ .map(|s| s.to_string_lossy().to_string())
+ .unwrap_or_else(|| "legacy".to_string()),
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn fake_cookie(domain: &str, name: &str, value: &str) -> ExtensionCookie {
+ ExtensionCookie {
+ domain: domain.to_string(),
+ http_only: false,
+ path: "/".to_string(),
+ secure: true,
+ expires: 1830000000,
+ name: name.to_string(),
+ value: value.to_string(),
+ host_only: None,
+ same_site: None,
+ }
+ }
+
+ #[test]
+ fn safe_domain_strips_unsafe() {
+ assert_eq!(safe_domain_segment(".YouTube.Com"), "youtube.com");
+ assert_eq!(safe_domain_segment("foo/bar"), "foo_bar");
+ }
+
+ #[test]
+ fn safe_slug_handles_empty_and_unsafe() {
+ assert_eq!(safe_slug_segment(""), DEFAULT_SLUG);
+ assert_eq!(safe_slug_segment("My Account / WTF"), "my-account---wtf");
+ }
+
+ #[test]
+ fn format_cookie_line_matches_netscape() {
+ let c = fake_cookie(".youtube.com", "SID", "abc");
+ let line = format_cookie_line(&c, 0);
+ let parts: Vec<&str> = line.trim().split('\t').collect();
+ assert_eq!(parts.len(), 7);
+ assert_eq!(parts[0], ".youtube.com");
+ assert_eq!(parts[1], "TRUE");
+ assert_eq!(parts[5], "SID");
+ assert_eq!(parts[6], "abc");
+ }
+
+ #[test]
+ fn format_cookie_line_host_only_flag() {
+ let mut c = fake_cookie("youtube.com", "k", "v");
+ c.host_only = Some(true);
+ let line = format_cookie_line(&c, 0);
+ let parts: Vec<&str> = line.trim().split('\t').collect();
+ assert_eq!(parts[0], "youtube.com");
+ assert_eq!(parts[1], "FALSE");
+ }
+}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 762f9f07..6835f8de 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -12,6 +12,7 @@ pub struct P2pSendHandle {
pub type ActiveP2pSends = Arc<tokio::sync::Mutex<HashMap<String, P2pSendHandle>>>;
pub mod commands;
+pub mod cookies;
pub mod core;
pub mod extension_storage;
pub mod external_url;
@@ -357,6 +358,13 @@ pub fn run() {
commands::browser_extension::browser_extension_open_folder,
commands::extension_cookies::read_extension_cookies,
commands::extension_cookies::extension_cookies_status,
+ cookies::commands::cookies_list,
+ cookies::commands::cookies_read,
+ cookies::commands::cookies_import,
+ cookies::commands::cookies_clear,
+ cookies::commands::cookies_rename,
+ cookies::commands::cookies_migrate_legacy,
+ cookies::commands::cookies_detect_platform,
commands::clip::clip_video,
commands::reencode::reencode_video,
commands::diagnostics::get_rate_limit_stats,
diff --git a/src-tauri/src/local_bridge.rs b/src-tauri/src/local_bridge.rs
index f84827b8..c2da14df 100644
--- a/src-tauri/src/local_bridge.rs
+++ b/src-tauri/src/local_bridge.rs
@@ -84,6 +84,12 @@ struct CookiesRequest {
cookies: Vec<ExtensionCookie>,
#[serde(default)]
protocol_version: Option<u32>,
+ #[serde(default)]
+ source_url: Option<String>,
+ #[serde(default)]
+ page_title: Option<String>,
+ #[serde(default)]
+ alias: Option<String>,
}
const HOST_MAX_PROTOCOL_VERSION: u32 = 1;
@@ -297,6 +303,16 @@ async fn enqueue(
if let Err(error) = write_extension_cookies(cookies) {
tracing::warn!("failed to write extension cookies: {error}");
}
+ if let Err(error) = crate::cookies::ingest_batch(
+ cookies,
+ crate::cookies::IngestSource {
+ source_url: payload.page_url.clone().or_else(|| Some(payload.url.clone())),
+ source_label: "Browser extension".to_string(),
+ alias_hint: payload.title.clone(),
+ },
+ ) {
+ tracing::warn!("failed to ingest cookies into manager: {error}");
+ }
}
}
@@ -373,6 +389,22 @@ async fn cookies_export(
format!("write extension cookies: {error}"),
);
}
+ let label = if request.source_url.is_some() || request.alias.is_some() {
+ "Browser extension (manual capture)".to_string()
+ } else {
+ "Browser extension (auto-capture)".to_string()
+ };
+ let alias_hint = request.alias.clone().or_else(|| request.page_title.clone());
+ if let Err(error) = crate::cookies::ingest_batch(
+ &request.cookies,
+ crate::cookies::IngestSource {
+ source_url: request.source_url.clone(),
+ source_label: label,
+ alias_hint,
+ },
+ ) {
+ tracing::warn!("failed to ingest cookies into manager: {error}");
+ }
}
let body = Json(EnqueueResponse {