RuneStone 1.0.0

This commit is contained in:
Knotty Wyvern
2026-11-16 04:21:21 -07:00
commit b52eeb14a1
827 changed files with 241421 additions and 0 deletions
+908
View File
@@ -0,0 +1,908 @@
use serde_json::{json, Value};
use std::{
collections::{HashMap, HashSet},
fs,
io::{BufRead, BufReader, Read, Write},
net::TcpStream,
path::{Path, PathBuf},
process::{Child, Command, Stdio},
sync::{mpsc, Arc, Mutex},
time::{Duration, Instant},
};
use tauri::{AppHandle, Emitter, Manager, State};
use crate::error::{Error, Result};
const COMMANDS: &[&str] = &[
"state",
"newTab",
"closeTab",
"navigate",
"back",
"forward",
"reload",
"stop",
"find",
"stopFind",
"openExternal",
"moveToWindow",
"adoptTab",
"resize",
"visible",
"focus",
"input",
"insertText",
"edit",
"contextAction",
"copiedImage",
"linkAt",
"frameAck",
"createProfile",
"renameProfile",
"duplicateProfile",
"bookmark",
"removeBookmark",
"settings",
"clearData",
"webData",
"removeCookie",
"removeHistory",
"agentSnapshot",
];
#[derive(Default)]
pub struct BrowserState {
inner: Mutex<Option<Worker>>,
sessions: Mutex<HashMap<String, String>>,
/// Tab owners. Each engine uses this table, so a closing window can release its tabs
/// without waiting for the engine lock.
routing: Arc<Mutex<WindowTabs>>,
/// Held while a retired engine stops. A new engine starts after the old one has stopped.
stopping: Mutex<()>,
}
#[derive(Default)]
struct WindowTabs {
windows: HashSet<String>,
owners: HashMap<String, String>,
pending: HashMap<String, String>,
transfer_tokens: HashMap<String, String>,
}
impl WindowTabs {
fn snapshot(&self, mut value: Value, owner: &str) -> Value {
if let Some(tabs) = value.get_mut("tabs").and_then(Value::as_array_mut) {
tabs.retain(|tab| tab["id"].as_str().and_then(|id| self.owners.get(id)).is_some_and(|window| window == owner));
for tab in tabs {
if let Some(token) = tab["id"].as_str().and_then(|id| self.transfer_tokens.get(id)) {
tab["transferToken"] = json!(token);
}
}
}
value
}
fn close(&mut self, owner: &str) -> Vec<String> {
self.windows.remove(owner);
self.pending.retain(|_, target| target != owner);
let closed: Vec<String> = self.owners.iter().filter(|(id, window)| !self.windows.contains(*window) && !self.pending.contains_key(*id)).map(|(id, _)| id.clone()).collect();
for id in &closed { self.owners.remove(id); self.transfer_tokens.remove(id); }
closed
}
fn assign(&mut self, id: &str, owner: &str) {
self.owners.insert(id.into(), owner.into());
self.transfer_tokens.insert(id.into(), uuid::Uuid::new_v4().to_string());
}
fn adopt(&mut self, id: &str, owner: &str, token: Option<&str>) -> Result<String> {
let source = self.owners.get(id).cloned().ok_or("Unknown browser tab.")?;
if source == owner { return Err("This browser tab already belongs to this window.".into()); }
let pending = self.pending.get(id).map(String::as_str);
let dragged = pending.is_none() && token.is_some() && self.transfer_tokens.get(id).map(String::as_str) == token;
if pending != Some(owner) && !dragged { return Err("This browser tab has no valid transfer to this window.".into()); }
self.assign(id, owner);
self.pending.remove(id);
Ok(source)
}
}
struct Worker {
child: Child,
input: Box<dyn Write + Send>,
replies: mpsc::Receiver<Value>,
routing: Arc<Mutex<WindowTabs>>,
/// Requests that nobody waits for. The reader drops their replies.
discard: Arc<Mutex<HashSet<u64>>>,
sequence: u64,
healthy: bool,
}
/// Browser profiles, settings, and Chromium state. On Windows this is Local AppData,
/// so that the Chromium caches stay out of the roaming profile.
fn root(app: &AppHandle) -> Result<PathBuf> {
Ok(app.path().app_local_data_dir()?.join("browser"))
}
/// Releases up to 0.1.48 kept the browser data in the app data folder, which roams on Windows.
fn legacy_root(app: &AppHandle) -> Result<PathBuf> {
Ok(app.path().app_data_dir()?.join("browser"))
}
/// Move the browser data of an earlier release from `legacy` to `current`. The engine must not run.
/// Nothing moves when the paths are the same, when `legacy` does not exist, or when `current` exists.
/// When the rename fails, for example across volumes, copy the folder. `legacy` stays until the copy is complete.
fn migrate_profiles(legacy: &Path, current: &Path, rename: impl Fn(&Path, &Path) -> std::io::Result<()>) -> Result<()> {
if legacy == current || !legacy.is_dir() || fs::symlink_metadata(current).is_ok() {
return Ok(());
}
let failed = |error: Error| -> Error {
format!("RuneStone could not move the browser profiles from {} to {}: {error}", legacy.display(), current.display()).into()
};
let parent = current.parent().ok_or("Invalid browser profile folder.")?;
fs::create_dir_all(parent).map_err(|error| failed(error.into()))?;
if rename(legacy, current).is_ok() {
return Ok(());
}
let temporary = parent.join(format!(".browser-move-{}", uuid::Uuid::new_v4().simple()));
let copied = copy_profile(legacy, &temporary, &mut 0, &mut 0, false).and_then(|()| Ok(rename(&temporary, current)?));
if let Err(error) = copied {
let _ = fs::remove_dir_all(&temporary);
return Err(failed(error));
}
// The copy is complete. If the removal fails, only an old copy stays behind.
let _ = fs::remove_dir_all(legacy);
Ok(())
}
/// The engine must speak the protocol of this host. An engine from another release can differ.
fn ready(value: &Value) -> Result<()> {
if value["event"] != "ready" {
return Err("The browser runtime did not start.".into());
}
if value["protocol"].as_u64() != Some(crate::browser_engine::PROTOCOL) {
return Err("This browser engine does not match this RuneStone version. Install the browser engine again.".into());
}
Ok(())
}
fn authenticate_connection(
stream: TcpStream,
token: &str,
) -> Result<Option<(TcpStream, BufReader<TcpStream>)>> {
stream.set_nonblocking(false)?;
stream.set_nodelay(true)?;
stream.set_read_timeout(Some(Duration::from_secs(1)))?;
let mut reader = BufReader::new(stream.try_clone()?);
let mut bytes = Vec::new();
let read = reader.by_ref().take(256).read_until(b'\n', &mut bytes);
let received = serde_json::from_slice::<Value>(&bytes)
.ok()
.and_then(|value| value["token"].as_str().map(str::to_string));
if read.is_err() || received.as_deref() != Some(token) {
return Ok(None);
}
// Windows keeps the timeout on the cloned socket after the original changes.
reader.get_ref().set_read_timeout(None)?;
stream.set_read_timeout(None)?;
Ok(Some((stream, reader)))
}
impl Worker {
fn start(app: &AppHandle, routing: Arc<Mutex<WindowTabs>>) -> Result<Self> {
let directory = root(app)?;
migrate_profiles(&legacy_root(app)?, &directory, |from, to| fs::rename(from, to))?;
fs::create_dir_all(&directory)?;
let listener = std::net::TcpListener::bind(("127.0.0.1", 0))?;
listener.set_nonblocking(true)?;
let port = listener.local_addr()?.port();
let token = format!(
"{}{}",
uuid::Uuid::new_v4().simple(),
uuid::Uuid::new_v4().simple()
);
let mut command = Command::new(crate::browser_engine::executable(app)?);
command
.arg(format!("--rs-connect={port}"))
.arg(format!("--rs-browser-root={}", directory.display()))
.env("RUNESTONE_BROWSER_TOKEN", &token)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
command
.env_remove("ELECTRON_RUN_AS_NODE")
.env_remove("NODE_OPTIONS")
.env_remove("ELECTRON_DISABLE_SANDBOX");
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
command.creation_flags(windows_sys::Win32::System::Threading::CREATE_NO_WINDOW);
}
let mut child = command.spawn()?;
let deadline = Instant::now() + Duration::from_secs(30);
let (input, output): (Box<dyn Write + Send>, Box<dyn Read + Send>) = loop {
if let Ok((stream, _)) = listener.accept() {
if let Some((stream, reader)) = authenticate_connection(stream, &token)? {
break (Box::new(stream), Box::new(reader));
}
}
if Instant::now() >= deadline || child.try_wait()?.is_some() {
let _ = child.kill();
let _ = child.wait();
return Err("The browser runtime did not start.".into());
}
std::thread::sleep(Duration::from_millis(20));
};
drop(listener);
let (send, replies) = mpsc::sync_channel(16);
let handle = app.clone();
let routes = routing.clone();
let discard = Arc::new(Mutex::new(HashSet::new()));
let unanswered = discard.clone();
std::thread::spawn(move || {
let mut reader = BufReader::new(output);
loop {
let mut bytes = Vec::new();
match reader
.by_ref()
.take(6_000_001)
.read_until(b'\n', &mut bytes)
{
Ok(0) | Err(_) => break,
Ok(_) if bytes.len() > 6_000_000 || !bytes.ends_with(b"\n") => break,
_ => {}
}
let Ok(value) = serde_json::from_slice::<Value>(&bytes) else {
continue;
};
match value.get("event").and_then(Value::as_str) {
Some("frame") => {
if let Ok(routes) = routes.lock() {
if let Some(target) = value["tabId"].as_str().and_then(|id| routes.owners.get(id)) {
let _ = handle.emit_to(target, "browser-frame", &value);
}
}
}
Some("state") | Some("error") | Some("context-menu") | Some("open-link") => {
if let Ok(routes) = routes.lock() {
for target in &routes.windows {
if let Some(id) = value["tabId"].as_str() {
if routes.owners.get(id) != Some(target) { continue; }
}
let mut payload = value.clone();
if value.get("state").is_some() { payload["state"] = routes.snapshot(value["state"].clone(), target); }
let _ = handle.emit_to(target, "browser-state", &payload);
}
}
}
_ => {
let dropped = value["id"].as_u64().is_some_and(|id| {
unanswered.lock().is_ok_and(|mut ids| ids.remove(&id))
});
if !dropped && send.try_send(value).is_err() {
break;
}
}
}
}
});
let mut worker = Self {
child,
input,
replies,
routing,
discard,
sequence: 0,
healthy: true,
};
let started = worker.replies.recv_timeout(Duration::from_secs(30))
.map_err(|_| Error::from("The browser runtime did not start."))
.and_then(|value| ready(&value));
match started {
Ok(()) => Ok(worker),
Err(error) => {
let _ = worker.child.kill();
let _ = worker.child.wait();
Err(error)
}
}
}
fn request(&mut self, command: &str, args: Value) -> Result<Value> {
let response = match self.exchange(command, args) {
Ok(response) => response,
Err(error) => {
self.healthy = false;
return Err(error);
}
};
if let Some(error) = response["error"].as_str() {
return Err(error.into());
}
Ok(response["result"].clone())
}
/// Send a request and do not wait for its reply. The reader drops the reply.
fn notify(&mut self, command: &str, args: Value) -> Result<()> {
self.sequence += 1;
self.discard.lock()?.insert(self.sequence);
let message = json!({ "id": self.sequence, "command": command, "args": args });
let sent = writeln!(self.input, "{}", message).and_then(|_| self.input.flush());
if sent.is_err() {
self.healthy = false;
}
Ok(sent?)
}
fn exchange(&mut self, command: &str, args: Value) -> Result<Value> {
self.sequence += 1;
let message = json!({ "id": self.sequence, "command": command, "args": args });
writeln!(self.input, "{}", message)?;
self.input.flush()?;
let response = self
.replies
.recv_timeout(Duration::from_secs(30))
.map_err(|_| {
"The browser stopped responding. Open a new browser tab to restart it.".to_string()
})?;
if response["id"].as_u64() != Some(self.sequence) {
return Err("The browser response did not match the request.".into());
}
Ok(response)
}
fn stop(&mut self) -> Result<()> {
if !self.healthy {
let _ = self.child.kill();
let _ = self.child.wait();
return Ok(());
}
let requested = self.request("shutdown", json!({}));
let deadline = Instant::now() + Duration::from_secs(5);
while Instant::now() < deadline {
if self.child.try_wait()?.is_some() {
return requested.map(|_| ());
}
std::thread::sleep(Duration::from_millis(20));
}
let _ = self.child.kill();
let _ = self.child.wait();
Err("The browser did not stop cleanly. Profile duplication was cancelled.".into())
}
}
impl Drop for Worker {
fn drop(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
fn profile_id(value: &str) -> bool {
!value.is_empty()
&& value.len() <= 64
&& value
.bytes()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
}
/// Copy a profile folder and refuse links. `limited` applies the limit for profile duplication.
fn copy_profile(source: &Path, target: &Path, files: &mut usize, bytes: &mut u64, limited: bool) -> Result<()> {
if !source.exists() {
fs::create_dir_all(target)?;
return Ok(());
}
let metadata = fs::symlink_metadata(source)?;
// A junction is not a symbolic link, but the copy would also follow it.
if crate::fsutil::is_link(&metadata) {
return Err("Profile links cannot be duplicated.".into());
}
if metadata.is_dir() {
fs::create_dir_all(target)?;
for entry in fs::read_dir(source)? {
let entry = entry?;
copy_profile(&entry.path(), &target.join(entry.file_name()), files, bytes, limited)?;
}
} else if metadata.is_file() {
*files += 1;
*bytes += metadata.len();
if limited && (*files > 50_000 || *bytes > 2_000_000_000) {
return Err("This profile exceeds the duplication limit.".into());
}
fs::copy(source, target)?;
} else {
return Err("Unsupported profile entry.".into());
}
Ok(())
}
impl BrowserState {
fn connect(&self, owner: &str) -> Result<String> {
let mut sessions = self.sessions.lock()?;
Ok(sessions.entry(owner.to_string()).or_insert_with(|| uuid::Uuid::new_v4().to_string()).clone())
}
fn require_session(&self, owner: &str, token: &str) -> Result<()> {
if self.sessions.lock()?.get(owner).is_some_and(|saved| saved == token) {
Ok(())
} else {
Err("The browser session is unavailable in this window.".into())
}
}
/// Revoke the window's session and release its tabs. Return the tabs to close in the engine.
/// This step never waits for the engine or for a request in progress.
pub fn release_window(&self, owner: &str) -> Vec<String> {
if let Ok(mut sessions) = self.sessions.lock() { sessions.remove(owner); }
self.routing.lock().map(|mut routes| routes.close(owner)).unwrap_or_default()
}
/// Close released tabs in the engine, and stop the engine when no window uses it.
/// This can wait for a request in progress. It never holds the engine lock while it waits for a reply.
pub fn close_tabs(&self, closed: Vec<String>) {
let (mut worker, _stopping) = {
let Ok(mut guard) = self.inner.lock() else { return; };
let Some(worker) = guard.as_mut() else { return; };
if worker.healthy {
for id in closed {
if worker.notify("closeTab", json!({ "tabId": id })).is_err() { break; }
}
}
// A request can add a window while this cleanup waits for the lock.
if !self.routing.lock().is_ok_and(|routes| routes.windows.is_empty()) { return; }
let Some(worker) = guard.take() else { return; };
// Take the stop lock before the engine lock opens, so that a new engine waits for this one.
let Ok(stopping) = self.stopping.lock() else { return; };
(worker, stopping)
};
let _ = worker.stop();
}
pub fn close_window(&self, owner: &str) {
let closed = self.release_window(owner);
self.close_tabs(closed);
}
pub fn close_all(&self) {
if let Ok(mut sessions) = self.sessions.lock() { sessions.clear(); }
self.stop_engine();
}
/// Stop the engine and keep the window sessions, so that open windows can start a new engine later.
pub fn stop_engine(&self) {
if let Ok(mut guard) = self.inner.lock() {
if let Some(mut worker) = guard.take() {
let _ = worker.stop();
}
}
}
fn request(&self, app: &AppHandle, owner: &str, command: &str, args: Value) -> Result<Value> {
if !COMMANDS.contains(&command) || args.to_string().len() > 180_000 || !args.is_object() {
return Err("Invalid browser request.".into());
}
let mut guard = self.inner.lock()?;
if guard.as_ref().is_some_and(|worker| !worker.healthy) {
guard.take();
}
if guard.is_none() {
// Wait until a retired engine has stopped. The new engine has no tabs yet.
let _stopped = self.stopping.lock()?;
*self.routing.lock()? = WindowTabs::default();
*guard = Some(Worker::start(app, self.routing.clone())?);
}
let worker = guard.as_mut().unwrap();
worker.routing.lock()?.windows.insert(owner.to_string());
if command == "adoptTab" {
let id = args["tabId"].as_str().ok_or("Invalid browser tab.")?;
let result = worker.request("state", json!({}))?;
if !result["tabs"].as_array().is_some_and(|tabs| tabs.iter().any(|tab| tab["id"] == id)) {
return Err("Unknown browser tab.".into());
}
let source = {
let mut routes = worker.routing.lock()?;
routes.adopt(id, owner, args["transferToken"].as_str())?
};
let _ = app.emit_to(&source, "browser-tab-moved", json!({ "tabId": id }));
return Ok(worker.routing.lock()?.snapshot(result, owner));
}
if ["closeTab", "navigate", "back", "forward", "reload", "stop", "find", "stopFind", "openExternal", "moveToWindow", "resize", "visible", "focus", "input", "insertText", "edit", "contextAction", "copiedImage", "linkAt", "frameAck", "bookmark", "agentSnapshot"].contains(&command) {
let id = args["tabId"].as_str().ok_or("Invalid browser tab.")?;
match worker.routing.lock()?.owners.get(id) {
Some(window) if window == owner => {},
Some(_) => return Err("This browser tab belongs to another window.".into()),
None => return Err("Unknown browser tab.".into()),
}
}
if command == "moveToWindow" {
let id = args["tabId"].as_str().ok_or("Invalid browser tab.")?;
let label = format!("browser-{}", uuid::Uuid::new_v4());
{
let mut routes = worker.routing.lock()?;
if routes.pending.contains_key(id) { return Err("This tab already has a pending window move.".into()); }
routes.pending.insert(id.into(), label.clone());
routes.windows.insert(label.clone());
}
let mut url = tauri::Url::parse("http://localhost/").map_err(Error::from_display)?;
url.query_pairs_mut().append_pair("browserWindow", "true");
url.query_pairs_mut().append_pair("browserTab", id);
if args["pinned"] == true { url.query_pairs_mut().append_pair("browserPinned", "true"); }
let result = crate::window_frame::title_bar(tauri::WebviewWindowBuilder::new(app, &label, tauri::WebviewUrl::App(format!("?{}", url.query().unwrap_or_default()).into())))
.title("RuneStone Browser").inner_size(1100.0, 750.0).min_inner_size(500.0, 300.0).disable_drag_drop_handler().build();
if let Err(error) = result {
worker.routing.lock()?.close(&label);
return Err(Error::from(error));
}
return Ok(json!({ "windowLabel": label }));
}
if command != "duplicateProfile" {
let result = worker.request(command, args.clone())?;
let mut routes = worker.routing.lock()?;
if command == "newTab" {
if let Some(id) = result["tabId"].as_str() { routes.assign(id, owner); }
} else if command == "closeTab" {
if let Some(id) = args["tabId"].as_str() { routes.owners.remove(id); routes.pending.remove(id); routes.transfer_tokens.remove(id); }
}
return Ok(routes.snapshot(result, owner));
}
let plan = guard.as_mut().unwrap().request("prepareDuplicate", args)?;
let source_id = plan["sourceId"]
.as_str()
.filter(|id| profile_id(id))
.ok_or("Invalid source profile.")?;
let target_id = plan["id"]
.as_str()
.filter(|id| uuid::Uuid::parse_str(id).is_ok())
.ok_or("Invalid destination profile.")?;
let mut worker = guard.take().unwrap();
let routing = worker.routing.clone();
worker.stop()?;
drop(worker);
// Chromium is fully stopped before its databases are copied.
let partitions = root(app)?.join("Partitions");
let source = partitions.join(format!("runestone-{source_id}"));
let destination = partitions.join(format!("runestone-{target_id}"));
if destination.exists() {
return Err("The destination profile already exists.".into());
}
copy_profile(&source, &destination, &mut 0, &mut 0, true)?;
*guard = Some(Worker::start(app, routing.clone())?);
let result = guard.as_mut().unwrap().request("commitDuplicate", plan)?;
let snapshot = routing.lock()?.snapshot(result, owner);
Ok(snapshot)
}
}
#[tauri::command]
pub async fn browser_connect(state: State<'_, BrowserState>, window: tauri::Window) -> Result<String> {
state.connect(window.label())
}
#[tauri::command]
pub async fn browser_request(
app: AppHandle,
window: tauri::Window,
command: String,
args: Value,
session: Option<String>,
) -> Result<Value> {
let owner = window.label().to_string();
// A request can wait for the engine to start or to answer, so it runs on the blocking worker.
tauri::async_runtime::spawn_blocking(move || {
let state = app.state::<BrowserState>();
// Only the built-in browser gets a session from `browser_connect`. A request without one fails.
state.require_session(&owner, session.as_deref().unwrap_or_default())?;
state.request(&app, &owner, &command, args)
})
.await?
}
#[tauri::command]
pub async fn browser_stop(app: AppHandle, window: tauri::Window) -> Result<()> {
let owner = window.label().to_string();
tauri::async_runtime::spawn_blocking(move || app.state::<BrowserState>().close_window(&owner)).await?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn builtin_sessions_are_scoped_to_a_window_and_revoked_on_close() {
let state = BrowserState::default();
assert!(state.require_session("main", "missing").is_err());
let token = state.connect("main").unwrap();
assert!(state.require_session("main", &token).is_ok());
assert!(state.require_session("other", &token).is_err());
state.close_window("main");
assert!(state.require_session("main", &token).is_err());
let next = state.connect("main").unwrap();
assert_ne!(next, token);
state.close_all();
assert!(state.require_session("main", &next).is_err());
}
#[test]
fn drag_transfer_requires_the_owner_token_and_rejects_replays() {
let mut routes = WindowTabs::default();
routes.windows.extend(["main".into(), "browser-other".into()]);
routes.assign("a", "browser-other");
let snapshot = json!({ "tabs": [{ "id": "a" }] });
let token = routes.snapshot(snapshot.clone(), "browser-other")["tabs"][0]["transferToken"].as_str().unwrap().to_string();
assert!(routes.snapshot(snapshot, "main")["tabs"].as_array().unwrap().is_empty());
assert!(routes.adopt("a", "main", None).is_err());
assert!(routes.adopt("a", "main", Some("wrong-token")).is_err());
assert_eq!(routes.owners["a"], "browser-other");
assert_eq!(routes.adopt("a", "main", Some(&token)).unwrap(), "browser-other");
assert!(routes.adopt("a", "browser-other", Some(&token)).is_err());
assert!(routes.close("browser-other").is_empty());
assert_eq!(routes.owners["a"], "main");
assert_ne!(routes.transfer_tokens["a"], token);
assert_eq!(routes.close("main"), vec!["a"]);
assert!(routes.transfer_tokens.is_empty());
}
#[test]
fn a_pending_window_move_cannot_be_taken_by_a_drag() {
let mut routes = WindowTabs::default();
routes.assign("a", "main");
let token = routes.transfer_tokens["a"].clone();
routes.pending.insert("a".into(), "browser-target".into());
assert!(routes.adopt("a", "browser-other", Some(&token)).is_err());
assert_eq!(routes.adopt("a", "browser-target", None).unwrap(), "main");
assert!(routes.pending.is_empty());
}
#[test]
fn window_routing_preserves_moved_tabs_and_filters_snapshots() {
let mut routes = WindowTabs::default();
routes.windows.extend(["main".into(), "browser-other".into()]);
routes.owners.insert("a".into(), "main".into());
routes.owners.insert("b".into(), "browser-other".into());
let snapshot = json!({ "tabs": [{ "id": "a" }, { "id": "b" }], "profiles": [{ "id": "user" }] });
assert_eq!(routes.snapshot(snapshot.clone(), "main")["tabs"], json!([{ "id": "a" }]));
assert_eq!(routes.snapshot(snapshot, "browser-other")["tabs"], json!([{ "id": "b" }]));
routes.pending.insert("a".into(), "browser-other".into());
assert!(routes.close("main").is_empty());
assert!(routes.owners.contains_key("a"));
let mut closed = routes.close("browser-other");
closed.sort();
assert_eq!(closed, vec!["a", "b"]);
assert!(routes.owners.is_empty());
}
#[test]
fn cancelled_window_move_keeps_the_source_tab() {
let mut routes = WindowTabs::default();
routes.windows.extend(["main".into(), "browser-other".into()]);
routes.owners.insert("a".into(), "main".into());
routes.pending.insert("a".into(), "browser-other".into());
assert!(routes.close("browser-other").is_empty());
assert_eq!(routes.owners.get("a").map(String::as_str), Some("main"));
assert!(routes.pending.is_empty());
}
#[test]
fn authenticated_connection_survives_idle_period() {
let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
let address = listener.local_addr().unwrap();
let sender = std::thread::spawn(move || {
let mut stream = TcpStream::connect(address).unwrap();
writeln!(stream, "{}", json!({ "token": "test-token" })).unwrap();
std::thread::sleep(Duration::from_millis(1500));
writeln!(stream, "{}", json!({ "id": 1, "result": { "tabs": [] } })).unwrap();
});
let (stream, _) = listener.accept().unwrap();
let (input, mut reader) = authenticate_connection(stream, "test-token").unwrap().unwrap();
assert_eq!(input.read_timeout().unwrap(), None);
assert_eq!(reader.get_ref().read_timeout().unwrap(), None);
let mut line = String::new();
reader.read_line(&mut line).unwrap();
assert_eq!(serde_json::from_str::<Value>(&line).unwrap()["id"], 1);
sender.join().unwrap();
}
#[test]
fn authentication_preserves_buffered_messages_and_rejects_other_tokens() {
for accepted in [false, true] {
let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
let address = listener.local_addr().unwrap();
let sender = std::thread::spawn(move || {
let mut stream = TcpStream::connect(address).unwrap();
stream.write_all(b"{\"token\":\"test-token\"}\n{\"event\":\"ready\"}\n").unwrap();
});
let (stream, _) = listener.accept().unwrap();
let connection = authenticate_connection(stream, if accepted { "test-token" } else { "other-token" }).unwrap();
if accepted {
let (_, mut reader) = connection.unwrap();
let mut line = String::new();
reader.read_line(&mut line).unwrap();
assert_eq!(serde_json::from_str::<Value>(&line).unwrap()["event"], "ready");
} else {
assert!(connection.is_none());
}
sender.join().unwrap();
}
}
fn test_worker(replies: mpsc::Receiver<Value>) -> Worker {
Worker {
child: Command::new(std::env::current_exe().unwrap())
.arg("--list")
.stdout(Stdio::null())
.spawn()
.unwrap(),
input: Box::new(Vec::<u8>::new()),
replies,
routing: Arc::new(Mutex::new(WindowTabs::default())),
discard: Arc::new(Mutex::new(HashSet::new())),
sequence: 0,
healthy: true,
}
}
#[derive(Clone, Default)]
struct Sink(Arc<Mutex<Vec<u8>>>);
impl Write for Sink {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
#[test]
fn closing_a_window_releases_tabs_without_the_engine_lock() {
let state = BrowserState::default();
let token = state.connect("main").unwrap();
{
let mut routes = state.routing.lock().unwrap();
routes.windows.extend(["main".into(), "other".into()]);
routes.assign("a", "main");
routes.assign("b", "other");
}
let (send, replies) = mpsc::channel();
let sink = Sink::default();
let mut worker = test_worker(replies);
worker.input = Box::new(sink.clone());
worker.routing = state.routing.clone();
let discard = worker.discard.clone();
*state.inner.lock().unwrap() = Some(worker);
// A request in progress holds the engine lock, but the window is released at once.
let busy = state.inner.lock().unwrap();
let closed = state.release_window("main");
assert_eq!(closed, vec!["a"]);
assert!(state.require_session("main", &token).is_err());
assert!(!state.routing.lock().unwrap().owners.contains_key("a"));
drop(busy);
// No reply arrives, and the cleanup does not wait for one.
let start = Instant::now();
state.close_tabs(closed);
assert!(start.elapsed() < Duration::from_secs(5));
let sent = String::from_utf8(sink.0.lock().unwrap().clone()).unwrap();
assert!(sent.contains("\"closeTab\"") && sent.contains("\"a\""), "{sent}");
assert_eq!(discard.lock().unwrap().len(), 1);
assert!(state.inner.lock().unwrap().is_some(), "Another window still uses the engine.");
drop(send);
state.close_window("other");
assert!(state.inner.lock().unwrap().is_none(), "The last window stops the engine.");
assert!(state.routing.lock().unwrap().owners.is_empty());
}
#[test]
fn profile_copy_rejects_links_and_junctions() {
let base = std::env::temp_dir().join(format!("runestone-profile-{}", uuid::Uuid::new_v4()));
let source = base.join("source");
let outside = base.join("outside");
fs::create_dir_all(&source).unwrap();
fs::create_dir_all(&outside).unwrap();
fs::write(source.join("Cookies"), b"cookies").unwrap();
fs::write(outside.join("secret.txt"), b"secret").unwrap();
copy_profile(&source, &base.join("plain"), &mut 0, &mut 0, true).unwrap();
assert_eq!(fs::read(base.join("plain").join("Cookies")).unwrap(), b"cookies");
let link = source.join("linked");
// A junction needs no symbolic-link privilege on Windows.
#[cfg(windows)]
assert!(Command::new("cmd")
.args(["/C", "mklink", "/J"])
.arg(&link)
.arg(&outside)
.stdout(Stdio::null())
.status()
.unwrap()
.success());
#[cfg(unix)]
std::os::unix::fs::symlink(&outside, &link).unwrap();
let error = copy_profile(&source, &base.join("copy"), &mut 0, &mut 0, true).unwrap_err();
assert!(error.to_string().contains("links"), "{error}");
assert!(!base.join("copy").join("linked").join("secret.txt").exists());
#[cfg(windows)]
fs::remove_dir(&link).unwrap();
#[cfg(unix)]
fs::remove_file(&link).unwrap();
assert!(outside.join("secret.txt").exists());
fs::remove_dir_all(&base).unwrap();
}
#[test]
fn broken_transport_requires_a_fresh_worker() {
let (send, replies) = mpsc::channel();
drop(send);
let mut worker = test_worker(replies);
assert!(worker.request("state", json!({})).is_err());
assert!(!worker.healthy);
assert!(worker.stop().is_ok());
}
#[test]
fn invalid_settings_do_not_discard_the_worker() {
let (send, replies) = mpsc::channel();
send.send(json!({ "id": 1, "error": "Invalid browser settings." })).unwrap();
send.send(json!({ "id": 2, "result": { "tabs": [] } })).unwrap();
let mut worker = test_worker(replies);
assert!(worker.request("settings", json!({})).is_err());
assert!(worker.healthy);
assert_eq!(worker.request("state", json!({})).unwrap(), json!({ "tabs": [] }));
}
fn profile_fixture(base: &Path) -> (PathBuf, PathBuf) {
let legacy = base.join("Roaming").join("browser");
fs::create_dir_all(legacy.join("Partitions").join("runestone-user")).unwrap();
fs::write(legacy.join("browser.json"), b"{\"version\":1}").unwrap();
fs::write(legacy.join("Partitions").join("runestone-user").join("Cookies"), b"cookies").unwrap();
(legacy, base.join("Local").join("browser"))
}
fn temporary_base() -> PathBuf {
std::env::temp_dir().join(format!("runestone-migrate-{}", uuid::Uuid::new_v4()))
}
#[test]
fn migration_moves_profiles_and_keeps_existing_ones() {
let base = temporary_base();
let (legacy, current) = profile_fixture(&base);
migrate_profiles(&legacy, &current, |from, to| fs::rename(from, to)).unwrap();
assert!(!legacy.exists());
assert_eq!(fs::read(current.join("Partitions").join("runestone-user").join("Cookies")).unwrap(), b"cookies");
// A second start finds no old folder.
migrate_profiles(&legacy, &current, |_, _| panic!("Nothing must move.")).unwrap();
// When both folders exist, the new one wins and the old one stays.
let (legacy, _) = profile_fixture(&base);
fs::write(current.join("browser.json"), b"current").unwrap();
migrate_profiles(&legacy, &current, |_, _| panic!("Nothing must move.")).unwrap();
assert_eq!(fs::read(current.join("browser.json")).unwrap(), b"current");
assert!(legacy.join("browser.json").exists());
// The same path (macOS and Linux) and a missing old folder change nothing.
migrate_profiles(&current, &current, |_, _| panic!("Nothing must move.")).unwrap();
let empty = base.join("empty");
migrate_profiles(&base.join("missing"), &empty, |_, _| panic!("Nothing must move.")).unwrap();
assert!(!empty.exists());
fs::remove_dir_all(&base).unwrap();
}
#[test]
fn migration_copies_when_the_rename_fails() {
let base = temporary_base();
let (legacy, current) = profile_fixture(&base);
let source = legacy.clone();
let across_volumes = |from: &Path, to: &Path| {
if from == source { Err(std::io::Error::other("not the same device")) } else { fs::rename(from, to) }
};
migrate_profiles(&legacy, &current, across_volumes).unwrap();
assert!(!legacy.exists());
assert_eq!(fs::read(current.join("browser.json")).unwrap(), b"{\"version\":1}");
assert_eq!(fs::read(current.join("Partitions").join("runestone-user").join("Cookies")).unwrap(), b"cookies");
let names: Vec<_> = fs::read_dir(base.join("Local")).unwrap().map(|entry| entry.unwrap().file_name()).collect();
assert_eq!(names, vec![std::ffi::OsString::from("browser")], "No temporary copy stays.");
fs::remove_dir_all(&base).unwrap();
}
#[test]
fn a_failed_copy_keeps_the_old_profiles() {
let base = temporary_base();
let (legacy, current) = profile_fixture(&base);
let outside = base.join("outside");
fs::create_dir_all(&outside).unwrap();
let link = legacy.join("linked");
#[cfg(windows)]
assert!(Command::new("cmd").args(["/C", "mklink", "/J"]).arg(&link).arg(&outside).stdout(Stdio::null()).status().unwrap().success());
#[cfg(unix)]
std::os::unix::fs::symlink(&outside, &link).unwrap();
let error = migrate_profiles(&legacy, &current, |_, _| Err(std::io::Error::other("not the same device"))).unwrap_err();
assert!(error.to_string().contains("could not move the browser profiles"), "{error}");
assert!(legacy.join("browser.json").exists());
assert!(!current.exists());
assert_eq!(fs::read_dir(base.join("Local")).unwrap().count(), 0, "No temporary copy stays.");
#[cfg(windows)]
fs::remove_dir(&link).unwrap();
#[cfg(unix)]
fs::remove_file(&link).unwrap();
fs::remove_dir_all(&base).unwrap();
}
#[test]
fn the_engine_must_send_the_protocol_of_this_host() {
assert!(ready(&json!({ "event": "ready", "protocol": crate::browser_engine::PROTOCOL, "version": "0.1.8" })).is_ok());
assert!(ready(&json!({ "event": "ready" })).unwrap_err().to_string().contains("does not match"));
assert!(ready(&json!({ "event": "ready", "protocol": crate::browser_engine::PROTOCOL + 1 })).is_err());
assert!(ready(&json!({ "event": "state" })).unwrap_err().to_string().contains("did not start"));
}
#[test]
fn profile_names_cannot_escape_storage() {
for value in ["../other", "a/b", "a\\b", "C:", "", "."] {
assert!(!profile_id(value));
}
assert!(profile_id("user"));
assert!(profile_id("a-b-123"));
}
#[test]
fn protocol_does_not_expose_raw_execution_or_copy_commands() {
for name in [
"executeJavaScript",
"shell",
"prepareDuplicate",
"commitDuplicate",
"shutdown",
] {
assert!(!COMMANDS.contains(&name));
}
}
}