GeezerVison is showing github.com — feat(browser): import a cookie file from Settings > Browser (#415) · anomalyco/opencode-rune@3f474f9
File treeExpand file treeCollapse file tree Open diff view settings crates/browser-pane/src/cookies
Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: apps/browser-engine/src/cookies.rs +32-2Lines changed: 32 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -102,7 +102,7 @@ fn to_cef_cookie(cookie: &WireCookie, now_secs: f64) -> Option<(String, Cookie)> | 102 | 102 | { | 103 | 103 | return None; | 104 | 104 | } | 105 | | - if bare.chars().any(|c| matches!(c, '\0' | '\r' | '\n' | '/' | '\\') || c.is_whitespace()) | | 105 | + if !valid_cookie_host(&cookie.host) | 106 | 106 | || cookie.name.chars().any(|c| matches!(c, '\0' | '\r' | '\n')) | 107 | 107 | || cookie.path.chars().any(|c| matches!(c, '\0' | '\r' | '\n')) | 108 | 108 | { | @@ -153,7 +153,37 @@ fn to_cef_cookie(cookie: &WireCookie, now_secs: f64) -> Option<(String, Cookie)> | 153 | 153 | same_site, | 154 | 154 | priority: CookiePriority::MEDIUM, | 155 | 155 | }; | 156 | | - Some((cookie_url(cookie), cef_cookie)) | | 156 | + let url = cookie_url(cookie); | | 157 | + // The URL Chromium binds the cookie to must name exactly this host: no user info, no port. | | 158 | + let parsed = url::Url::parse(&url).ok()?; | | 159 | + let same_host = match parsed.host()? { | | 160 | + url::Host::Domain(d) => d.eq_ignore_ascii_case(bare), | | 161 | + url::Host::Ipv4(ip) => bare.parse::<std::net::Ipv4Addr>().is_ok_and(|b| b == ip), | | 162 | + url::Host::Ipv6(ip) => bare.trim_start_matches('[').trim_end_matches(']').parse::<std::net::Ipv6Addr>().is_ok_and(|b| b == ip), | | 163 | + }; | | 164 | + if !parsed.username().is_empty() || parsed.password().is_some() || parsed.port().is_some() || !same_host { | | 165 | + return None; | | 166 | + } | | 167 | + Some((url, cef_cookie)) | | 168 | +} | | 169 | + | | 170 | +/// A cookie host a browser would store (`browser_pane::cookies::format::valid_cookie_host`, kept in | | 171 | +/// step): a plain hostname or an IP literal, at most one leading dot; never `user@host`, `?`, `#`, | | 172 | +/// `%`, a port, a stray `:`, controls or spaces. | | 173 | +fn valid_cookie_host(host: &str) -> bool { | | 174 | + let bare = host.strip_prefix('.').unwrap_or(host); | | 175 | + if bare.is_empty() || bare.len() > 253 { | | 176 | + return false; | | 177 | + } | | 178 | + if let Some(inner) = bare.strip_prefix('[').and_then(|r| r.strip_suffix(']')) { | | 179 | + return inner.parse::<std::net::Ipv6Addr>().is_ok(); | | 180 | + } | | 181 | + if bare.contains(':') { | | 182 | + return bare.parse::<std::net::Ipv6Addr>().is_ok(); | | 183 | + } | | 184 | + bare.split('.').all(|label| { | | 185 | + !label.is_empty() && label.len() <= 63 && label.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') | | 186 | + }) | 157 | 187 | } | 158 | 188 |
| 159 | 189 | fn from_cef_cookie(c: &Cookie) -> WireCookie { | |
Collapse file Copy file name to clipboardExpand all lines: apps/desktop/src/plugin_host/native/browser.rs +2-1Lines changed: 2 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -216,7 +216,7 @@ pub fn build(lua: &Lua, vmx: &std::rc::Rc<Vmx>, t: &Table) -> mlua::Result<()> { | 216 | 216 | })?; | 217 | 217 | chrome::service_methods(lua, t)?; | 218 | 218 | history::service_methods(lua, vmx, t)?; | 219 | | - cookies::service_methods(lua, t)?; | | 219 | + cookies::service_methods(lua, vmx, t)?; | 220 | 220 | extensions::service_methods(lua, vmx, t)?; | 221 | 221 | let raw: Function = vmx.asyncs.raw_get("Browser.OpenAsync")?; | 222 | 222 | let open: Function = lua.load("local raw = ... return function(self, spec) local id = raw(spec) return if id then self:Get(id) else nil end").set_name("=Browser:OpenAsync").call(raw)?; | @@ -232,6 +232,7 @@ pub fn asyncs(host: &Host<'_>, t: &Table) -> mlua::Result<()> { | 232 | 232 | t.raw_set("BrowserTab.SiteCookiesAsync", host.async_function("BrowserTab:SiteCookiesAsync", devtools::site_cookies)?)?; | 233 | 233 | t.raw_set("BrowserTab.ClearSiteAsync", host.async_function("BrowserTab:ClearSiteAsync", devtools::clear_site)?)?; | 234 | 234 | extensions::asyncs(host, t)?; | | 235 | + cookies::asyncs(host, t)?; | 235 | 236 | history::asyncs(host, t)?; | 236 | 237 | chrome::asyncs(host, t) | 237 | 238 | } | |
Collapse file Copy file name to clipboardExpand all lines: apps/desktop/src/plugin_host/native/browser/cookies.rs +24-3Lines changed: 24 additions & 3 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 2 | 2 | //! store (`browser_pane::cookies::host`). Only the bundled browser plugin's own settings page may | 3 | 3 | //! call them: never a third-party plugin, and never from an MCP tool's coroutine. | 4 | 4 |
| 5 | | -use mlua::{Lua, Table}; | | 5 | +use mlua::{Function, Lua, MultiValue, Table}; | 6 | 6 | use rune::Tx; | | 7 | +use rune_luau::{Completer, Host}; | 7 | 8 |
| 8 | | -use super::{App, Dep, cx, method, scope::TabScope, with_app}; | | 9 | +use super::{App, Dep, Vmx, cx, method, scope::TabScope, with_app}; | 9 | 10 |
| 10 | 11 | fn require_settings_caller(lua: &Lua, what: &str) -> mlua::Result<()> { | 11 | 12 | let scope = TabScope::capture(lua); | @@ -15,7 +16,7 @@ fn require_settings_caller(lua: &Lua, what: &str) -> mlua::Result<()> { | 15 | 16 | Err(mlua::Error::runtime(format!("{what}: browser.cookies.denied"))) | 16 | 17 | } | 17 | 18 |
| 18 | | -pub(super) fn service_methods(lua: &Lua, t: &Table) -> mlua::Result<()> { | | 19 | +pub(super) fn service_methods(lua: &Lua, vmx: &std::rc::Rc<Vmx>, t: &Table) -> mlua::Result<()> { | 19 | 20 | // `settings.tsx:208-209`: the switch shows the profile's state, and is disabled while it is | 20 | 21 | // unknown (an engine without the `#286` cookie store). While the engine is idle, the persisted | 21 | 22 | // preference stays live and `BrowserHost` sends `SetShareSignIns` on `Ready { cookies: true }`. | @@ -36,5 +37,25 @@ pub(super) fn service_methods(lua: &Lua, t: &Table) -> mlua::Result<()> { | 36 | 37 | Ok(()) | 37 | 38 | }) | 38 | 39 | })?; | | 40 | + // `Browser:ImportCookieFileAsync(title)`: the app shows the picker itself (`cookie_import`). | | 41 | + let raw: Function = vmx.asyncs.raw_get("Browser.ImportCookieFileAsync")?; | | 42 | + let call: Function = lua | | 43 | + .load("local raw = ... return function(self, title) return raw(title) end") | | 44 | + .set_name("=Browser:ImportCookieFileAsync") | | 45 | + .call(raw)?; | | 46 | + t.raw_set("ImportCookieFileAsync", call)?; | 39 | 47 | Ok(()) | 40 | 48 | } | | 49 | + | | 50 | +pub(super) fn asyncs(host: &Host<'_>, t: &Table) -> mlua::Result<()> { | | 51 | + t.raw_set("Browser.ImportCookieFileAsync", host.async_function("Browser:ImportCookieFileAsync", import_cookie_file)?) | | 52 | +} | | 53 | + | | 54 | +fn import_cookie_file(lua: &Lua, a: MultiValue, done: Completer) -> mlua::Result<()> { | | 55 | + let (title,): (String,) = mlua::FromLuaMulti::from_lua_multi(a, lua)?; | | 56 | + require_settings_caller(lua, "Browser:ImportCookieFileAsync")?; | | 57 | + with_app("Browser:ImportCookieFileAsync", |app| { | | 58 | + app.later(Box::new(move |s: &mut App, tx: &mut Tx| s.start_cookie_file_import(title, done, tx))); | | 59 | + Ok(()) | | 60 | + }) | | 61 | +} |
Collapse file Copy file name to clipboard +211Lines changed: 211 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +//! Settings > Browser's "Import cookie file" (official `settings.tsx:56-61,230-255`, | | 2 | +//! `profile/index.ts:503-516`): the app opens the OS file picker itself, so a plugin never names a | | 3 | +//! path. `#286`'s `read_cookie_file` reads and parses it (regular files only, at most 32 MiB, | | 4 | +//! Netscape `cookies.txt`, Chrome JSON or Playwright storage state) on a worker thread, and | | 5 | +//! `prepare_for_import` drops what no browser would send (expired, nameless, or a host that is not a | | 6 | +//! plain hostname or IP literal: `valid_cookie_host`). The cookies go to the profile's store through | | 7 | +//! `BrowserHost::import_profile_cookies` in batches of at most 1,000 cookies / 2 MiB (one wire line | | 8 | +//! each, far under the engine's line cap), starting the engine if it is idle. Like official's | | 9 | +//! `writeCookies` (`profile/import.ts:10-38`) it writes every cookie with no per-site cap; Chromium | | 10 | +//! evicts past its own limits. One import runs at a time; it fails after 60 s without an answer | | 11 | +//! (`jobs-machine.ts:87`; counted from the last batch answered), or at once when the engine goes away. | | 12 | +
| | 13 | +use std::collections::HashSet; | | 14 | +use std::sync::{Arc, Mutex}; | | 15 | +use std::time::Duration; | | 16 | + | | 17 | +use browser_pane::cookies::format::prepare_for_import; | | 18 | +use browser_pane::cookies::{CookieRead, ImportFailure, ProfileEvent, read_cookie_file}; | | 19 | +use browser_pane::protocol::WireCookie; | | 20 | +use rune::time::Instant; | | 21 | +use rune::{FileDialogOptions, Tx}; | | 22 | +use rune_luau::{Completer, Data}; | | 23 | + | | 24 | +use crate::App; | | 25 | +use crate::plugin_host::services::map; | | 26 | + | | 27 | +const ANSWER_TIMEOUT: Duration = Duration::from_secs(60); | | 28 | +/// One `ProfileCookiesSet` line: at most this many cookies ... | | 29 | +const BATCH_COOKIES: usize = 1_000; | | 30 | +/// ... and about this many bytes of cookie text. | | 31 | +const BATCH_BYTES: usize = 2 * 1024 * 1024; | | 32 | +/// A picker title longer than this is cut. | | 33 | +const MAX_TITLE: usize = 200; | | 34 | + | | 35 | +type Read = Result<CookieRead, ImportFailure>; | | 36 | + | | 37 | +/// What the import brings: still being read on the worker, or read and waiting to be sent. | | 38 | +enum Reading { | | 39 | + Pending(Arc<Mutex<Option<Read>>>), | | 40 | + Ready(CookieRead), | | 41 | +} | | 42 | + | | 43 | +/// The import the engine has yet to answer. | | 44 | +pub struct CookieImport { | | 45 | + done: Completer, | | 46 | + read: Reading, | | 47 | + /// Batches still to send, the requests the engine has yet to answer, and its answers so far. | | 48 | + batches: Vec<Vec<WireCookie>>, | | 49 | + waiting: HashSet<u64>, | | 50 | + sent: bool, | | 51 | + imported: u32, | | 52 | + failed: u32, | | 53 | + deadline: Instant, | | 54 | +} | | 55 | + | | 56 | +fn failure(reason: &str) -> Data { | | 57 | + map([("error", Data::String(reason.into()))]) | | 58 | +} | | 59 | + | | 60 | +fn reason(f: ImportFailure) -> &'static str { | | 61 | + match f { | | 62 | + ImportFailure::Read | ImportFailure::Key | ImportFailure::Access | ImportFailure::Locked => "read", | | 63 | + ImportFailure::Format => "format", | | 64 | + ImportFailure::Storage => "storage", | | 65 | + } | | 66 | +} | | 67 | + | | 68 | +/// Splits `cookies` into batches of at most `BATCH_COOKIES` cookies and about `BATCH_BYTES` bytes. | | 69 | +fn batches(cookies: Vec<WireCookie>) -> Vec<Vec<WireCookie>> { | | 70 | + let mut out: Vec<Vec<WireCookie>> = Vec::new(); | | 71 | + let mut current: Vec<WireCookie> = Vec::new(); | | 72 | + let mut bytes = 0usize; | | 73 | + for c in cookies { | | 74 | + let size = c.host.len() + c.name.len() + c.value.len() + c.path.len() + 128; | | 75 | + if !current.is_empty() && (current.len() >= BATCH_COOKIES || bytes + size > BATCH_BYTES) { | | 76 | + out.push(std::mem::take(&mut current)); | | 77 | + bytes = 0; | | 78 | + } | | 79 | + bytes += size; | | 80 | + current.push(c); | | 81 | + } | | 82 | + if !current.is_empty() { | | 83 | + out.push(current); | | 84 | + } | | 85 | + out | | 86 | +} | | 87 | + | | 88 | +impl App { | | 89 | + /// Opens the picker titled `title` and imports the chosen file; `done` gets | | 90 | + /// `{ imported, failed, protected, skipped }`, `{ error }` or `{ cancelled = true }`. | | 91 | + pub(crate) fn start_cookie_file_import(&mut self, title: String, done: Completer, tx: &mut Tx) { | | 92 | + if self.workspace_panes.browser.cookie_import.is_some() { | | 93 | + return done.complete(failure("busy")); | | 94 | + } | | 95 | + let title: String = title.chars().filter(|c| !c.is_control()).take(MAX_TITLE).collect(); | | 96 | + let options = FileDialogOptions { title, ..Default::default() }.filter("Cookies", &["txt", "json"]); | | 97 | + tx.open_file(options, move |s: &mut App, picked, _tx| { | | 98 | + let path = match picked { | | 99 | + Ok(Some(path)) => path, | | 100 | + Ok(None) => return done.complete(map([("cancelled", Data::Bool(true))])), | | 101 | + Err(_) => return done.complete(failure("read")), | | 102 | + }; | | 103 | + if s.workspace_panes.browser.cookie_import.is_some() { | | 104 | + return done.complete(failure("busy")); | | 105 | + } | | 106 | + // Reading and parsing up to 32 MiB happens off the UI thread. | | 107 | + let slot: Arc<Mutex<Option<Read>>> = Arc::new(Mutex::new(None)); | | 108 | + let filled = slot.clone(); | | 109 | + let waker = (*s.waker).clone(); | | 110 | + let spawned = std::thread::Builder::new().name("browser-cookie-file".into()).spawn(move || { | | 111 | + let read = read_cookie_file(&path); | | 112 | + if let Ok(mut s) = filled.lock() { | | 113 | + *s = Some(read); | | 114 | + } | | 115 | + if let Some(w) = &waker { | | 116 | + w(); | | 117 | + } | | 118 | + }); | | 119 | + if spawned.is_err() { | | 120 | + return done.complete(failure("read")); | | 121 | + } | | 122 | + let start = !s.use_mock_browser() && !s.browser_unsupported(); | | 123 | + let pane = &mut s.workspace_panes.browser; | | 124 | + if !pane.host.engine_cookies() && start { | | 125 | + pane.host.prepare(ANSWER_TIMEOUT); | | 126 | + } | | 127 | + pane.cookie_import = Some(CookieImport { | | 128 | + done, | | 129 | + read: Reading::Pending(slot), | | 130 | + batches: Vec::new(), | | 131 | + waiting: HashSet::new(), | | 132 | + sent: false, | | 133 | + imported: 0, | | 134 | + failed: 0, | | 135 | + deadline: Instant::now() + ANSWER_TIMEOUT, | | 136 | + }); | | 137 | + }); | | 138 | + } | | 139 | + | | 140 | + /// Moves the waiting import on: takes the worker's read, sends its batches once the engine's | | 141 | + /// cookie store is up, and answers once every batch is answered. Takes only its own profile | | 142 | + /// events; others stay for whoever asked. True when an import ended. | | 143 | + pub(crate) fn pump_cookie_import(&mut self) -> bool { | | 144 | + let pane = &mut self.workspace_panes.browser; | | 145 | + let Some(mut job) = pane.cookie_import.take() else { return false }; | | 146 | + let host = &mut pane.host; | | 147 | + if let Reading::Pending(slot) = &job.read { | | 148 | + match slot.lock().ok().and_then(|mut s| s.take()) { | | 149 | + Some(Ok(read)) => { | | 150 | + let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0.0, |d| d.as_secs_f64()); | | 151 | + let (valid, skipped) = prepare_for_import(&read.cookies, now); | | 152 | + job.batches = batches(valid); | | 153 | + job.batches.reverse(); | | 154 | + job.read = Reading::Ready(CookieRead { cookies: Vec::new(), skipped: read.skipped + skipped, ..read }); | | 155 | + } | | 156 | + Some(Err(f)) => { | | 157 | + job.done.complete(failure(reason(f))); | | 158 | + return true; | | 159 | + } | | 160 | + None if Instant::now() >= job.deadline => { | | 161 | + job.done.complete(failure("failed")); | | 162 | + return true; | | 163 | + } | | 164 | + None => { | | 165 | + pane.cookie_import = Some(job); | | 166 | + return false; | | 167 | + } | | 168 | + } | | 169 | + } | | 170 | + let Reading::Ready(read) = &job.read else { return false }; | | 171 | + if !job.sent && host.engine_cookies() { | | 172 | + while let Some(batch) = job.batches.pop() { | | 173 | + match host.import_profile_cookies(None, batch) { | | 174 | + Some(id) => { | | 175 | + job.waiting.insert(id); | | 176 | + } | | 177 | + None => break, | | 178 | + } | | 179 | + } | | 180 | + job.sent = job.batches.is_empty(); | | 181 | + } | | 182 | + let waiting = &job.waiting; | | 183 | + for ev in host.take_profile_events_matching(|ev| matches!(ev, ProfileEvent::CookiesImported { request_id, .. } if waiting.contains(request_id))) { | | 184 | + if let ProfileEvent::CookiesImported { request_id, imported, failed } = ev { | | 185 | + job.waiting.remove(&request_id); | | 186 | + job.imported += imported; | | 187 | + job.failed += failed; | | 188 | + // A large file answers batch by batch: the 60 s run from the last answer. | | 189 | + job.deadline = Instant::now() + ANSWER_TIMEOUT; | | 190 | + } | | 191 | + } | | 192 | + let result = if job.sent && job.waiting.is_empty() { | | 193 | + map([ | | 194 | + ("imported", Data::Number(f64::from(job.imported))), | | 195 | + ("failed", Data::Number(f64::from(job.failed + read.failed))), | | 196 | + ("protected", Data::Number(f64::from(read.protected))), | | 197 | + ("skipped", Data::Number(f64::from(read.skipped))), | | 198 | + ]) | | 199 | + } else if !job.sent && host.engine_caps_known() && !host.engine_cookies() { | | 200 | + failure("failed") | | 201 | + } else if (job.sent && !host.has_live_sidecar()) || Instant::now() >= job.deadline { | | 202 | + // The engine went away with batches unanswered, or it never answered. | | 203 | + failure("failed") | | 204 | + } else { | | 205 | + pane.cookie_import = Some(job); | | 206 | + return false; | | 207 | + }; | | 208 | + job.done.complete(result); | | 209 | + true | | 210 | + } | | 211 | +} |
Collapse file Copy file name to clipboardExpand all lines: apps/desktop/src/surfaces/browser/mod.rs +5Lines changed: 5 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -18,6 +18,8 @@ mod comment_describe; | 18 | 18 | #[cfg(not(target_arch = "wasm32"))] | 19 | 19 | pub mod context_menu; | 20 | 20 | #[cfg(not(target_arch = "wasm32"))] | | 21 | +pub mod cookie_import; | | 22 | +#[cfg(not(target_arch = "wasm32"))] | 21 | 23 | mod keys; | 22 | 24 | #[cfg(not(target_arch = "wasm32"))] | 23 | 25 | pub mod extensions; | @@ -132,6 +134,8 @@ mod native { | 132 | 134 | pub session_tabs: HashMap<String, Vec<u64>>, | 133 | 135 | /// DevTools calls a plugin waits on, by the engine's request id. | 134 | 136 | pub devtools: HashMap<u64, PendingDevtools>, | | 137 | + /// Settings > Browser's cookie-file import waiting on the engine (`cookie_import`). | | 138 | + pub cookie_import: Option<super::cookie_import::CookieImport>, | 135 | 139 | /// Each other browser's icon for Settings > Browser, read off the UI thread (`app_icons`). | 136 | 140 | pub app_icons: super::app_icons::AppIcons, | 137 | 141 | /// Last observed Luau store version for `plugin.browser/rune.sitePermissions`. | @@ -702,6 +706,7 @@ mod native { | 702 | 706 | // Every poll comes here: the pane is written only when the engine has something. | 703 | 707 | let mut changed = !self.workspace_panes.browser.host.quiet() && self.workspace_panes.browser.host.poll(); | 704 | 708 | changed |= self.pump_preview_fetches(); | | 709 | + changed |= self.pump_cookie_import(); | 705 | 710 | let fallback_sources = self.workspace_panes.browser.host.drain_unsupported_local_previews(); | 706 | 711 | for (tab_id, doc) in fallback_sources { | 707 | 712 | // Non-agent local HTML clicks on an older engine (`!Ready.preview`) open in the | |
|