Download, verify, and install the browser engine
Each host build pins one engine version in src-tauri/browser-engine.json. The new engine manager downloads that ZIP over HTTPS, makes sure that its size and SHA-256 match the pin, extracts it safely to the local app data folder, and marks the installation last. It can also install a local ZIP, cancel, report progress, and remove the engine. The host refuses an engine that sends another protocol with its ready event.
This commit is contained in:
@@ -18,7 +18,7 @@ const server = net.createServer(client => {
|
|||||||
const line = buffer.slice(0, end); buffer = buffer.slice(end + 1);
|
const line = buffer.slice(0, end); buffer = buffer.slice(end + 1);
|
||||||
const message = JSON.parse(line);
|
const message = JSON.parse(line);
|
||||||
if (message.token) { assert.equal(message.token, token); console.log('PASS runtime authentication'); }
|
if (message.token) { assert.equal(message.token, token); console.log('PASS runtime authentication'); }
|
||||||
if (message.event === 'ready') client.write(JSON.stringify({ id: 1, command: 'state', args: {} }) + '\n');
|
if (message.event === 'ready') { assert.equal(message.protocol, 1); assert.match(message.version, /^\d+\.\d+\.\d+/); console.log('PASS runtime protocol'); client.write(JSON.stringify({ id: 1, command: 'state', args: {} }) + '\n'); }
|
||||||
if (message.id === 1) { assert.deepEqual(message.result.profiles, [{ id: 'user', name: 'User' }]); client.write(JSON.stringify({ id: 2, command: 'newTab', args: {} }) + '\n'); }
|
if (message.id === 1) { assert.deepEqual(message.result.profiles, [{ id: 'user', name: 'User' }]); client.write(JSON.stringify({ id: 2, command: 'newTab', args: {} }) + '\n'); }
|
||||||
if (message.id === 2) { assert.ok(message.result.tabId); console.log('PASS packaged runtime commands'); client.write(JSON.stringify({ id: 3, command: 'shutdown', args: {} }) + '\n'); }
|
if (message.id === 2) { assert.ok(message.result.tabId); console.log('PASS packaged runtime commands'); client.write(JSON.stringify({ id: 3, command: 'shutdown', args: {} }) + '\n'); }
|
||||||
if (message.id === 3) console.log('PASS clean shutdown response');
|
if (message.id === 3) console.log('PASS clean shutdown response');
|
||||||
|
|||||||
@@ -58,6 +58,7 @@ else {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
emit({ event: 'ready' });
|
// The host refuses an engine with another protocol. Keep PROTOCOL in src-tauri/src/browser_engine.rs the same.
|
||||||
|
emit({ event: 'ready', protocol: 1, version: app.getVersion() });
|
||||||
}).catch(error => { console.error(error); app.exit(1); });
|
}).catch(error => { console.error(error); app.exit(1); });
|
||||||
}
|
}
|
||||||
|
|||||||
+22
-2
@@ -283,16 +283,36 @@ Before you start the app, set `WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-de
|
|||||||
## Built-in browser runtime
|
## Built-in browser runtime
|
||||||
|
|
||||||
The browser interface is in `src/lib/browser/`. The browser engine, its tests, and its notices are in `browser-runtime/`.
|
The browser interface is in `src/lib/browser/`. The browser engine, its tests, and its notices are in `browser-runtime/`.
|
||||||
The installer includes the staged engine from `src-tauri/browser-engine/`.
|
The engine is a separate download. Users install it on first use.
|
||||||
|
|
||||||
1. Run `npm ci --prefix browser-runtime`.
|
1. Run `npm ci --prefix browser-runtime`.
|
||||||
2. Run `pnpm browser:check` and `pnpm browser:test`.
|
2. Run `pnpm browser:check` and `pnpm browser:test`.
|
||||||
3. Run `pnpm browser:test:engine` for the native engine tests.
|
3. Run `pnpm browser:test:engine` for the native engine tests.
|
||||||
4. Run `npm --prefix browser-runtime run package`.
|
4. Run `npm --prefix browser-runtime run package`.
|
||||||
5. Run `pnpm browser:stage` before you build an installer.
|
5. Run `pnpm browser:stage` to use this engine in `pnpm tauri dev`.
|
||||||
|
|
||||||
Each browser window gets a session token at startup. Native requests check that token, and cleanup revokes it.
|
Each browser window gets a session token at startup. Native requests check that token, and cleanup revokes it.
|
||||||
|
|
||||||
|
### Engine download
|
||||||
|
|
||||||
|
Each host build pins one engine version in `src-tauri/browser-engine.json`: the version, the protocol, and the URL, size, and SHA-256 hash for each platform.
|
||||||
|
A platform key is the operating system and the processor, for example `windows-x86_64`. Without an entry for its platform, the host reports that no engine is available.
|
||||||
|
|
||||||
|
On request, `src-tauri/src/browser_engine.rs` downloads the ZIP over HTTPS into `browser-engine/.download/` in the local app data folder. A redirect must also use HTTPS.
|
||||||
|
The host stops when the size or the SHA-256 hash differs from the pin. It extracts the ZIP into a new folder, refuses unsafe paths and links, and needs the engine program at the root of the archive.
|
||||||
|
Then it writes `installed.json` and renames the folder to `browser-engine/<version>/`. It removes the other versions.
|
||||||
|
At each start, the host compares `installed.json` with the pin. It does not hash the files again. **Install from file** applies the same size, hash, and archive checks to a local ZIP.
|
||||||
|
|
||||||
|
| Engine | When the host starts it |
|
||||||
|
| --- | --- |
|
||||||
|
| `src-tauri/browser-engine/`, from `pnpm browser:stage` | Debug builds without a manifest override |
|
||||||
|
| `browser-engine/<version>/` in the local app data folder | Release builds, and debug builds with `RUNESTONE_BROWSER_ENGINE_MANIFEST` |
|
||||||
|
|
||||||
|
`RUNESTONE_BROWSER_ENGINE_MANIFEST` names a manifest file for a native test. Only debug builds read it. With it, the host also accepts HTTP links, for a local test server.
|
||||||
|
|
||||||
|
The engine sends `protocol` and `version` with its `ready` event. The host stops an engine with a different protocol.
|
||||||
|
`PROTOCOL` in `browser_engine.rs` and the `ready` event in `browser-runtime/src/engine-main.mjs` must change together. After a change, package and stage the engine again.
|
||||||
|
|
||||||
The browser data is in the Tauri `app_local_data_dir()`. Releases up to 0.1.48 kept it in `app_data_dir()`, which roams on Windows.
|
The browser data is in the Tauri `app_local_data_dir()`. Releases up to 0.1.48 kept it in `app_data_dir()`, which roams on Windows.
|
||||||
Before the engine starts, `src-tauri/src/browser.rs` moves an old `browser` folder to the new place. Across volumes, it copies the folder and then deletes the old one.
|
Before the engine starts, `src-tauri/src/browser.rs` moves an old `browser` folder to the new place. Across volumes, it copies the folder and then deletes the old one.
|
||||||
If the new folder exists, the host uses it and leaves the old folder. If the move fails, the engine does not start, and the error names both folders.
|
If the new folder exists, the host uses it and leaves the old folder. If the move fails, the engine does not start, and the error names both folders.
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"version": "0.1.7",
|
||||||
|
"protocol": 1,
|
||||||
|
"platforms": {}
|
||||||
|
}
|
||||||
@@ -38,6 +38,11 @@ fn main() {
|
|||||||
"browser_request",
|
"browser_request",
|
||||||
"browser_connect",
|
"browser_connect",
|
||||||
"browser_stop",
|
"browser_stop",
|
||||||
|
"browser_engine_status",
|
||||||
|
"browser_engine_install",
|
||||||
|
"browser_engine_install_file",
|
||||||
|
"browser_engine_cancel",
|
||||||
|
"browser_engine_remove",
|
||||||
"git_status",
|
"git_status",
|
||||||
"git_diff",
|
"git_diff",
|
||||||
"git_stage",
|
"git_stage",
|
||||||
|
|||||||
@@ -9,6 +9,9 @@
|
|||||||
"allow-browser-request",
|
"allow-browser-request",
|
||||||
"allow-browser-connect",
|
"allow-browser-connect",
|
||||||
"allow-browser-stop",
|
"allow-browser-stop",
|
||||||
|
"allow-browser-engine-status",
|
||||||
|
"allow-browser-engine-install",
|
||||||
|
"allow-browser-engine-cancel",
|
||||||
"allow-plugins-snapshot",
|
"allow-plugins-snapshot",
|
||||||
"allow-settings-read",
|
"allow-settings-read",
|
||||||
"allow-window-snap-layouts",
|
"allow-window-snap-layouts",
|
||||||
|
|||||||
@@ -27,6 +27,11 @@
|
|||||||
"allow-browser-request",
|
"allow-browser-request",
|
||||||
"allow-browser-connect",
|
"allow-browser-connect",
|
||||||
"allow-browser-stop",
|
"allow-browser-stop",
|
||||||
|
"allow-browser-engine-status",
|
||||||
|
"allow-browser-engine-install",
|
||||||
|
"allow-browser-engine-install-file",
|
||||||
|
"allow-browser-engine-cancel",
|
||||||
|
"allow-browser-engine-remove",
|
||||||
"allow-git-status",
|
"allow-git-status",
|
||||||
"allow-git-diff",
|
"allow-git-diff",
|
||||||
"allow-git-stage",
|
"allow-git-stage",
|
||||||
|
|||||||
@@ -35,6 +35,11 @@
|
|||||||
"allow-browser-request",
|
"allow-browser-request",
|
||||||
"allow-browser-connect",
|
"allow-browser-connect",
|
||||||
"allow-browser-stop",
|
"allow-browser-stop",
|
||||||
|
"allow-browser-engine-status",
|
||||||
|
"allow-browser-engine-install",
|
||||||
|
"allow-browser-engine-install-file",
|
||||||
|
"allow-browser-engine-cancel",
|
||||||
|
"allow-browser-engine-remove",
|
||||||
"allow-completion-request",
|
"allow-completion-request",
|
||||||
"allow-completion-cancel",
|
"allow-completion-cancel",
|
||||||
"allow-backgrounds-choose-folder",
|
"allow-backgrounds-choose-folder",
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-browser-engine-cancel"
|
||||||
|
description = "Enables the browser_engine_cancel command without any pre-configured scope."
|
||||||
|
commands.allow = ["browser_engine_cancel"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-browser-engine-cancel"
|
||||||
|
description = "Denies the browser_engine_cancel command without any pre-configured scope."
|
||||||
|
commands.deny = ["browser_engine_cancel"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-browser-engine-install"
|
||||||
|
description = "Enables the browser_engine_install command without any pre-configured scope."
|
||||||
|
commands.allow = ["browser_engine_install"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-browser-engine-install"
|
||||||
|
description = "Denies the browser_engine_install command without any pre-configured scope."
|
||||||
|
commands.deny = ["browser_engine_install"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-browser-engine-install-file"
|
||||||
|
description = "Enables the browser_engine_install_file command without any pre-configured scope."
|
||||||
|
commands.allow = ["browser_engine_install_file"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-browser-engine-install-file"
|
||||||
|
description = "Denies the browser_engine_install_file command without any pre-configured scope."
|
||||||
|
commands.deny = ["browser_engine_install_file"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-browser-engine-remove"
|
||||||
|
description = "Enables the browser_engine_remove command without any pre-configured scope."
|
||||||
|
commands.allow = ["browser_engine_remove"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-browser-engine-remove"
|
||||||
|
description = "Denies the browser_engine_remove command without any pre-configured scope."
|
||||||
|
commands.deny = ["browser_engine_remove"]
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-browser-engine-status"
|
||||||
|
description = "Enables the browser_engine_status command without any pre-configured scope."
|
||||||
|
commands.allow = ["browser_engine_status"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-browser-engine-status"
|
||||||
|
description = "Denies the browser_engine_status command without any pre-configured scope."
|
||||||
|
commands.deny = ["browser_engine_status"]
|
||||||
+26
-29
@@ -143,32 +143,15 @@ fn migrate_profiles(legacy: &Path, current: &Path, rename: impl Fn(&Path, &Path)
|
|||||||
let _ = fs::remove_dir_all(legacy);
|
let _ = fs::remove_dir_all(legacy);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
fn executable(app: &AppHandle) -> Result<PathBuf> {
|
/// The engine must speak the protocol of this host. An engine from another release can differ.
|
||||||
let name = if cfg!(windows) {
|
fn ready(value: &Value) -> Result<()> {
|
||||||
"RuneStone-Browser.exe"
|
if value["event"] != "ready" {
|
||||||
} else if cfg!(target_os = "macos") {
|
return Err("The browser runtime did not start.".into());
|
||||||
"RuneStone-Browser.app/Contents/MacOS/RuneStone-Browser"
|
|
||||||
} else {
|
|
||||||
"RuneStone-Browser"
|
|
||||||
};
|
|
||||||
#[cfg(debug_assertions)]
|
|
||||||
{
|
|
||||||
let development = Path::new(env!("CARGO_MANIFEST_DIR"))
|
|
||||||
.join("browser-engine")
|
|
||||||
.join(name);
|
|
||||||
if development.is_file() {
|
|
||||||
return Ok(development);
|
|
||||||
}
|
}
|
||||||
|
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());
|
||||||
}
|
}
|
||||||
let packaged = app
|
Ok(())
|
||||||
.path()
|
|
||||||
.resource_dir()?
|
|
||||||
.join("browser-engine")
|
|
||||||
.join(name);
|
|
||||||
if packaged.is_file() {
|
|
||||||
return Ok(packaged);
|
|
||||||
}
|
|
||||||
Err("The browser runtime is missing. Build RuneStone with its browser runtime.".into())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn authenticate_connection(
|
fn authenticate_connection(
|
||||||
@@ -206,7 +189,7 @@ impl Worker {
|
|||||||
uuid::Uuid::new_v4().simple(),
|
uuid::Uuid::new_v4().simple(),
|
||||||
uuid::Uuid::new_v4().simple()
|
uuid::Uuid::new_v4().simple()
|
||||||
);
|
);
|
||||||
let mut command = Command::new(executable(app)?);
|
let mut command = Command::new(crate::browser_engine::executable(app)?);
|
||||||
command
|
command
|
||||||
.arg(format!("--rs-connect={port}"))
|
.arg(format!("--rs-connect={port}"))
|
||||||
.arg(format!("--rs-browser-root={}", directory.display()))
|
.arg(format!("--rs-browser-root={}", directory.display()))
|
||||||
@@ -300,12 +283,15 @@ impl Worker {
|
|||||||
sequence: 0,
|
sequence: 0,
|
||||||
healthy: true,
|
healthy: true,
|
||||||
};
|
};
|
||||||
match worker.replies.recv_timeout(Duration::from_secs(30)) {
|
let started = worker.replies.recv_timeout(Duration::from_secs(30))
|
||||||
Ok(value) if value["event"] == "ready" => Ok(worker),
|
.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.kill();
|
||||||
let _ = worker.child.wait();
|
let _ = worker.child.wait();
|
||||||
Err("The browser runtime did not start.".into())
|
Err(error)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -455,6 +441,10 @@ impl BrowserState {
|
|||||||
}
|
}
|
||||||
pub fn close_all(&self) {
|
pub fn close_all(&self) {
|
||||||
if let Ok(mut sessions) = self.sessions.lock() { sessions.clear(); }
|
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 Ok(mut guard) = self.inner.lock() {
|
||||||
if let Some(mut worker) = guard.take() {
|
if let Some(mut worker) = guard.take() {
|
||||||
let _ = worker.stop();
|
let _ = worker.stop();
|
||||||
@@ -887,6 +877,13 @@ mod tests {
|
|||||||
fs::remove_dir_all(&base).unwrap();
|
fs::remove_dir_all(&base).unwrap();
|
||||||
}
|
}
|
||||||
#[test]
|
#[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() {
|
fn profile_names_cannot_escape_storage() {
|
||||||
for value in ["../other", "a/b", "a\\b", "C:", "", "."] {
|
for value in ["../other", "a/b", "a\\b", "C:", "", "."] {
|
||||||
assert!(!profile_id(value));
|
assert!(!profile_id(value));
|
||||||
|
|||||||
@@ -0,0 +1,679 @@
|
|||||||
|
//! The browser engine is a separate download. Each host build pins one engine version in
|
||||||
|
//! `browser-engine.json`. On request, the host downloads that engine, makes sure that its size
|
||||||
|
//! and SHA-256 match the pin, and extracts it to the local app data folder.
|
||||||
|
//! See docs/development.md#engine-download.
|
||||||
|
use reqwest::{blocking::Client, Url};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
use std::{
|
||||||
|
collections::{BTreeSet, HashMap},
|
||||||
|
fs,
|
||||||
|
io::{Read, Write},
|
||||||
|
path::{Path, PathBuf},
|
||||||
|
sync::{
|
||||||
|
atomic::{AtomicBool, Ordering},
|
||||||
|
Arc, Mutex,
|
||||||
|
},
|
||||||
|
time::{Duration, Instant},
|
||||||
|
};
|
||||||
|
use tauri::{AppHandle, Emitter, Manager};
|
||||||
|
use tauri_plugin_dialog::DialogExt;
|
||||||
|
|
||||||
|
use crate::error::{Error, Result};
|
||||||
|
|
||||||
|
/// The protocol between the host and the engine. The engine sends it with its `ready` event.
|
||||||
|
pub const PROTOCOL: u64 = 1;
|
||||||
|
const PINNED: &str = include_str!("../browser-engine.json");
|
||||||
|
/// The extracted engine of Electron 44 has 73 files and 377 MB.
|
||||||
|
const MAX_ENTRIES: usize = 10_000;
|
||||||
|
const MAX_EXTRACTED: u64 = 1024 * 1024 * 1024;
|
||||||
|
const MARKER: &str = "installed.json";
|
||||||
|
const WORK: &str = ".download";
|
||||||
|
const CANCELLED: &str = "The browser engine download was cancelled.";
|
||||||
|
|
||||||
|
#[derive(Deserialize, Clone, Debug)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct Manifest {
|
||||||
|
pub version: String,
|
||||||
|
pub protocol: u64,
|
||||||
|
#[serde(default)]
|
||||||
|
pub platforms: HashMap<String, Package>,
|
||||||
|
}
|
||||||
|
#[derive(Deserialize, Clone, Debug)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct Package {
|
||||||
|
pub url: String,
|
||||||
|
pub bytes: u64,
|
||||||
|
pub sha256: String,
|
||||||
|
}
|
||||||
|
#[derive(Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct Marker {
|
||||||
|
version: String,
|
||||||
|
sha256: String,
|
||||||
|
installed_at: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the interface shows about the engine.
|
||||||
|
#[derive(Serialize, Clone, Debug, Default, PartialEq)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct Status {
|
||||||
|
/// `installed`, `missing`, `update`, `downloading`, `installing`, `unavailable`, or `development`.
|
||||||
|
pub state: String,
|
||||||
|
/// The engine version that this host needs.
|
||||||
|
pub version: String,
|
||||||
|
/// The download size in bytes.
|
||||||
|
pub bytes: u64,
|
||||||
|
pub received: u64,
|
||||||
|
pub error: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct EngineState {
|
||||||
|
job: Mutex<Job>,
|
||||||
|
}
|
||||||
|
#[derive(Default, Clone)]
|
||||||
|
struct Job {
|
||||||
|
phase: Option<&'static str>,
|
||||||
|
received: u64,
|
||||||
|
error: Option<String>,
|
||||||
|
cancel: Arc<AtomicBool>,
|
||||||
|
}
|
||||||
|
enum Source {
|
||||||
|
Download,
|
||||||
|
File(PathBuf),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn platform() -> String {
|
||||||
|
format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH)
|
||||||
|
}
|
||||||
|
pub fn executable_name() -> &'static str {
|
||||||
|
if cfg!(windows) {
|
||||||
|
"RuneStone-Browser.exe"
|
||||||
|
} else if cfg!(target_os = "macos") {
|
||||||
|
"RuneStone-Browser.app/Contents/MacOS/RuneStone-Browser"
|
||||||
|
} else {
|
||||||
|
"RuneStone-Browser"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn valid_version(value: &str) -> bool {
|
||||||
|
!value.is_empty()
|
||||||
|
&& value.len() <= 40
|
||||||
|
&& value.as_bytes()[0].is_ascii_digit()
|
||||||
|
&& value.bytes().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'.')
|
||||||
|
&& !value.contains("..")
|
||||||
|
}
|
||||||
|
fn parse(text: &str) -> Result<Manifest> {
|
||||||
|
let manifest: Manifest = serde_json::from_str(text).map_err(|error| format!("The browser engine manifest is invalid: {error}"))?;
|
||||||
|
if !valid_version(&manifest.version) {
|
||||||
|
return Err("The browser engine manifest has an invalid version.".into());
|
||||||
|
}
|
||||||
|
for package in manifest.platforms.values() {
|
||||||
|
let hex = package.sha256.len() == 64 && package.sha256.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c));
|
||||||
|
if !hex || package.bytes == 0 || Url::parse(&package.url).is_err() {
|
||||||
|
return Err("The browser engine manifest has an invalid package.".into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(manifest)
|
||||||
|
}
|
||||||
|
/// The manifest file of a native test. Only debug builds read it.
|
||||||
|
fn override_path() -> Option<PathBuf> {
|
||||||
|
if cfg!(debug_assertions) {
|
||||||
|
std::env::var_os("RUNESTONE_BROWSER_ENGINE_MANIFEST").map(PathBuf::from)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn manifest() -> Result<Manifest> {
|
||||||
|
match override_path() {
|
||||||
|
Some(path) => parse(&fs::read_to_string(path)?),
|
||||||
|
None => parse(PINNED),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn engines(app: &AppHandle) -> Result<PathBuf> {
|
||||||
|
Ok(app.path().app_local_data_dir()?.join("browser-engine"))
|
||||||
|
}
|
||||||
|
/// The engine that `pnpm browser:stage` puts in `src-tauri/browser-engine` for `pnpm tauri dev`.
|
||||||
|
/// A manifest override turns it off, so that a native test uses the download.
|
||||||
|
fn development_engine() -> Option<PathBuf> {
|
||||||
|
if !cfg!(debug_assertions) || override_path().is_some() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("browser-engine").join(executable_name());
|
||||||
|
path.is_file().then_some(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The installed engine that matches the pin, if any.
|
||||||
|
fn installed(root: &Path, manifest: &Manifest) -> Option<PathBuf> {
|
||||||
|
let package = manifest.platforms.get(&platform())?;
|
||||||
|
let folder = root.join(&manifest.version);
|
||||||
|
let marker: Marker = serde_json::from_slice(&fs::read(folder.join(MARKER)).ok()?).ok()?;
|
||||||
|
let executable = folder.join(executable_name());
|
||||||
|
(marker.version == manifest.version && marker.sha256 == package.sha256 && executable.is_file()).then_some(executable)
|
||||||
|
}
|
||||||
|
/// Version folders with a complete installation, also for other versions.
|
||||||
|
fn installed_versions(root: &Path) -> Vec<String> {
|
||||||
|
let Ok(entries) = fs::read_dir(root) else { return Vec::new() };
|
||||||
|
entries
|
||||||
|
.filter_map(|entry| entry.ok())
|
||||||
|
.filter(|entry| entry.path().join(MARKER).is_file())
|
||||||
|
.filter_map(|entry| entry.file_name().into_string().ok())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The engine executable to start.
|
||||||
|
pub fn executable(app: &AppHandle) -> Result<PathBuf> {
|
||||||
|
if let Some(path) = development_engine() {
|
||||||
|
return Ok(path);
|
||||||
|
}
|
||||||
|
let manifest = manifest()?;
|
||||||
|
installed(&engines(app)?, &manifest).ok_or_else(|| "The browser engine is not installed.".into())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn describe(manifest: &Result<Manifest>, root: &Path, job: &Job, development: bool) -> Status {
|
||||||
|
let manifest = match manifest {
|
||||||
|
Ok(manifest) => manifest,
|
||||||
|
Err(error) => return Status { state: "unavailable".into(), error: Some(error.to_string()), ..Status::default() },
|
||||||
|
};
|
||||||
|
let base = Status { version: manifest.version.clone(), received: job.received, error: job.error.clone(), ..Status::default() };
|
||||||
|
if development {
|
||||||
|
return Status { state: "development".into(), ..base };
|
||||||
|
}
|
||||||
|
let Some(package) = manifest.platforms.get(&platform()) else {
|
||||||
|
return Status { state: "unavailable".into(), ..base };
|
||||||
|
};
|
||||||
|
let state = match job.phase {
|
||||||
|
Some(phase) => phase,
|
||||||
|
None if installed(root, manifest).is_some() => "installed",
|
||||||
|
None if !installed_versions(root).is_empty() => "update",
|
||||||
|
None => "missing",
|
||||||
|
};
|
||||||
|
Status { state: state.into(), bytes: package.bytes, ..base }
|
||||||
|
}
|
||||||
|
fn status(app: &AppHandle) -> Result<Status> {
|
||||||
|
let job = app.state::<EngineState>().job.lock()?.clone();
|
||||||
|
Ok(describe(&manifest(), &engines(app)?, &job, development_engine().is_some()))
|
||||||
|
}
|
||||||
|
fn publish(app: &AppHandle) {
|
||||||
|
if let Ok(status) = status(app) {
|
||||||
|
let _ = app.emit("browser-engine", &status);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A redirect may not leave HTTPS. A native test can allow HTTP for its local server.
|
||||||
|
fn allowed(url: &Url, allow_http: bool) -> bool {
|
||||||
|
url.scheme() == "https" || (allow_http && url.scheme() == "http")
|
||||||
|
}
|
||||||
|
/// Download `package` to `target` and make sure that its size and SHA-256 match.
|
||||||
|
/// `target` must not exist. On failure, the function removes it.
|
||||||
|
fn download(package: &Package, target: &Path, allow_http: bool, cancel: &AtomicBool, report: &mut dyn FnMut(u64)) -> Result<()> {
|
||||||
|
let url = Url::parse(&package.url).map_err(|_| "The browser engine link is invalid.")?;
|
||||||
|
if !allowed(&url, allow_http) {
|
||||||
|
return Err("The browser engine link must use HTTPS.".into());
|
||||||
|
}
|
||||||
|
let client = Client::builder()
|
||||||
|
.user_agent("RuneStone-browser-engine/1")
|
||||||
|
.connect_timeout(Duration::from_secs(15))
|
||||||
|
// A limit for each read, not for the whole download.
|
||||||
|
.timeout(Duration::from_secs(60))
|
||||||
|
.redirect(reqwest::redirect::Policy::custom(move |attempt| {
|
||||||
|
if attempt.previous().len() >= 5 {
|
||||||
|
attempt.error("The download server redirected too many times.")
|
||||||
|
} else if !allowed(attempt.url(), allow_http) {
|
||||||
|
attempt.error("The download server redirected away from HTTPS.")
|
||||||
|
} else {
|
||||||
|
attempt.follow()
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
.build()
|
||||||
|
.map_err(|_| "Cannot start the download client.")?;
|
||||||
|
let result = (|| -> Result<()> {
|
||||||
|
let mut response = client.get(url).send().map_err(|error| format!("Cannot reach the download server: {error}"))?;
|
||||||
|
if !response.status().is_success() {
|
||||||
|
return Err(format!("The download server answered {}.", response.status()).into());
|
||||||
|
}
|
||||||
|
if response.content_length().is_some_and(|length| length != package.bytes) {
|
||||||
|
return Err("The download does not have the expected size.".into());
|
||||||
|
}
|
||||||
|
let mut file = fs::File::options().write(true).create_new(true).open(target)?;
|
||||||
|
let (mut hasher, mut received, mut buffer) = (Sha256::new(), 0u64, vec![0; 256 * 1024]);
|
||||||
|
loop {
|
||||||
|
if cancel.load(Ordering::Relaxed) {
|
||||||
|
return Err(CANCELLED.into());
|
||||||
|
}
|
||||||
|
let read = response.read(&mut buffer).map_err(|error| format!("The download stopped: {error}"))?;
|
||||||
|
if read == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
received += read as u64;
|
||||||
|
if received > package.bytes {
|
||||||
|
return Err("The download is larger than expected.".into());
|
||||||
|
}
|
||||||
|
hasher.update(&buffer[..read]);
|
||||||
|
file.write_all(&buffer[..read])?;
|
||||||
|
report(received);
|
||||||
|
}
|
||||||
|
if received != package.bytes {
|
||||||
|
return Err("The download is incomplete.".into());
|
||||||
|
}
|
||||||
|
if format!("{:x}", hasher.finalize()) != package.sha256 {
|
||||||
|
return Err("The download does not match the expected SHA-256 hash.".into());
|
||||||
|
}
|
||||||
|
Ok(file.sync_all()?)
|
||||||
|
})();
|
||||||
|
if result.is_err() {
|
||||||
|
let _ = fs::remove_file(target);
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
/// Make sure that a local ZIP has the size and SHA-256 of the pin.
|
||||||
|
fn verify_file(path: &Path, package: &Package, cancel: &AtomicBool) -> Result<()> {
|
||||||
|
let metadata = fs::symlink_metadata(path)?;
|
||||||
|
if !metadata.is_file() || metadata.len() != package.bytes {
|
||||||
|
return Err("This file is not the browser engine that this RuneStone version needs. Its size is different.".into());
|
||||||
|
}
|
||||||
|
let (mut file, mut hasher, mut buffer) = (fs::File::open(path)?, Sha256::new(), vec![0; 256 * 1024]);
|
||||||
|
loop {
|
||||||
|
if cancel.load(Ordering::Relaxed) {
|
||||||
|
return Err(CANCELLED.into());
|
||||||
|
}
|
||||||
|
let read = file.read(&mut buffer)?;
|
||||||
|
if read == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
hasher.update(&buffer[..read]);
|
||||||
|
}
|
||||||
|
if format!("{:x}", hasher.finalize()) != package.sha256 {
|
||||||
|
return Err("This file is not the browser engine that this RuneStone version needs. Its SHA-256 hash is different.".into());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn valid_component(name: &str) -> bool {
|
||||||
|
crate::fsutil::is_plain_component(name)
|
||||||
|
&& name.len() <= 120
|
||||||
|
&& !name.starts_with(' ')
|
||||||
|
&& !name.ends_with(' ')
|
||||||
|
&& name.bytes().all(|c| c.is_ascii_alphanumeric() || b" ._+-".contains(&c))
|
||||||
|
}
|
||||||
|
/// Extract an engine ZIP into the new folder `target`. Refuse unsafe paths, links, and archives over `limit` bytes.
|
||||||
|
fn extract(archive: &Path, target: &Path, limit: u64) -> Result<()> {
|
||||||
|
let mut archive = zip::ZipArchive::new(fs::File::open(archive)?).map_err(|_| "The browser engine archive is not a valid ZIP file.")?;
|
||||||
|
if archive.len() > MAX_ENTRIES {
|
||||||
|
return Err("The browser engine archive contains too many entries.".into());
|
||||||
|
}
|
||||||
|
fs::create_dir(target)?;
|
||||||
|
let (mut names, mut total) = (BTreeSet::new(), 0u64);
|
||||||
|
for index in 0..archive.len() {
|
||||||
|
let mut file = archive.by_index(index)?;
|
||||||
|
let name = std::str::from_utf8(file.name_raw())?.trim_end_matches('/').to_string();
|
||||||
|
let parts: Vec<&str> = name.split('/').collect();
|
||||||
|
if parts.len() > 16 || !parts.iter().all(|part| valid_component(part)) {
|
||||||
|
return Err(format!("The browser engine archive contains an invalid path: {name}").into());
|
||||||
|
}
|
||||||
|
if !names.insert(name.to_ascii_lowercase()) {
|
||||||
|
return Err("The browser engine archive contains duplicate paths.".into());
|
||||||
|
}
|
||||||
|
let kind = file.unix_mode().map(|mode| mode & 0o170000);
|
||||||
|
if kind.is_some_and(|kind| kind != 0 && kind != 0o100000 && kind != 0o040000) || file.is_symlink() {
|
||||||
|
return Err("The browser engine archive contains links or special files.".into());
|
||||||
|
}
|
||||||
|
let path: PathBuf = parts.iter().fold(target.to_path_buf(), |path, part| path.join(part));
|
||||||
|
if file.is_dir() {
|
||||||
|
fs::create_dir_all(&path)?;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if let Some(parent) = path.parent() {
|
||||||
|
fs::create_dir_all(parent)?;
|
||||||
|
}
|
||||||
|
let remaining = limit.saturating_sub(total);
|
||||||
|
let mut output = fs::File::options().write(true).create_new(true).open(&path)?;
|
||||||
|
let written = std::io::copy(&mut file.by_ref().take(remaining.saturating_add(1)), &mut output)?;
|
||||||
|
total += written;
|
||||||
|
if written > remaining {
|
||||||
|
return Err("The browser engine archive is too large.".into());
|
||||||
|
}
|
||||||
|
#[cfg(unix)]
|
||||||
|
if let Some(mode) = file.unix_mode() {
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
fs::set_permissions(&path, fs::Permissions::from_mode(mode & 0o755))?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !target.join(executable_name()).is_file() {
|
||||||
|
return Err("The browser engine archive does not contain the engine program.".into());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
/// Extract a verified archive and put it in the version folder of the pin.
|
||||||
|
fn install_archive(archive: &Path, root: &Path, manifest: &Manifest, package: &Package) -> Result<()> {
|
||||||
|
let work = root.join(WORK);
|
||||||
|
fs::create_dir_all(&work)?;
|
||||||
|
let staged = work.join(format!("extract-{}", uuid::Uuid::new_v4().simple()));
|
||||||
|
let result = (|| -> Result<()> {
|
||||||
|
extract(archive, &staged, MAX_EXTRACTED)?;
|
||||||
|
let installed_at = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|time| time.as_millis() as u64).unwrap_or(0);
|
||||||
|
let marker = Marker { version: manifest.version.clone(), sha256: package.sha256.clone(), installed_at };
|
||||||
|
fs::write(staged.join(MARKER), serde_json::to_vec_pretty(&marker)?)?;
|
||||||
|
let target = root.join(&manifest.version);
|
||||||
|
// A folder without a valid marker is an incomplete earlier attempt. No engine runs from it.
|
||||||
|
if fs::symlink_metadata(&target).is_ok() {
|
||||||
|
fs::remove_dir_all(&target)?;
|
||||||
|
}
|
||||||
|
Ok(fs::rename(&staged, &target)?)
|
||||||
|
})();
|
||||||
|
if result.is_err() {
|
||||||
|
let _ = fs::remove_dir_all(&staged);
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
/// Remove the other version folders and the work folder. No engine runs from them.
|
||||||
|
fn remove_others(root: &Path, keep: &str) {
|
||||||
|
let Ok(entries) = fs::read_dir(root) else { return };
|
||||||
|
for entry in entries.filter_map(|entry| entry.ok()) {
|
||||||
|
if entry.file_name() != keep {
|
||||||
|
let _ = fs::remove_dir_all(entry.path());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Windows can keep the program file locked for a moment after the engine stops.
|
||||||
|
fn remove_with_retries(path: &Path) -> Result<()> {
|
||||||
|
for attempt in 0.. {
|
||||||
|
match fs::remove_dir_all(path) {
|
||||||
|
Ok(()) => return Ok(()),
|
||||||
|
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
|
||||||
|
Err(_) if attempt < 10 => std::thread::sleep(Duration::from_millis(200)),
|
||||||
|
Err(error) => return Err(format!("Cannot remove the browser engine: {error}").into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
unreachable!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run(app: &AppHandle, source: Source, cancel: &AtomicBool) -> Result<()> {
|
||||||
|
let manifest = manifest()?;
|
||||||
|
let package = manifest.platforms.get(&platform()).cloned().ok_or("No browser engine is available for this platform.")?;
|
||||||
|
let root = engines(app)?;
|
||||||
|
if installed(&root, &manifest).is_some() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let work = root.join(WORK);
|
||||||
|
let _ = fs::remove_dir_all(&work);
|
||||||
|
fs::create_dir_all(&work)?;
|
||||||
|
let archive = match source {
|
||||||
|
Source::Download => {
|
||||||
|
let file = work.join("engine.zip");
|
||||||
|
let mut last = Instant::now();
|
||||||
|
download(&package, &file, override_path().is_some(), cancel, &mut |received| {
|
||||||
|
if last.elapsed() >= Duration::from_millis(250) || received == package.bytes {
|
||||||
|
last = Instant::now();
|
||||||
|
if let Ok(mut job) = app.state::<EngineState>().job.lock() { job.received = received; }
|
||||||
|
publish(app);
|
||||||
|
}
|
||||||
|
})?;
|
||||||
|
file
|
||||||
|
}
|
||||||
|
Source::File(path) => {
|
||||||
|
verify_file(&path, &package, cancel)?;
|
||||||
|
path
|
||||||
|
}
|
||||||
|
};
|
||||||
|
app.state::<EngineState>().job.lock()?.phase = Some("installing");
|
||||||
|
publish(app);
|
||||||
|
install_archive(&archive, &root, &manifest, &package)?;
|
||||||
|
remove_others(&root, &manifest.version);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
fn start(app: &AppHandle, source: Source) -> Result<Status> {
|
||||||
|
let state = app.state::<EngineState>();
|
||||||
|
let cancel = {
|
||||||
|
let mut job = state.job.lock()?;
|
||||||
|
// One download at a time. A second request gets the status of the first.
|
||||||
|
if job.phase.is_none() {
|
||||||
|
let phase = if matches!(source, Source::Download) { "downloading" } else { "installing" };
|
||||||
|
*job = Job { phase: Some(phase), ..Job::default() };
|
||||||
|
Some(job.cancel.clone())
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if let Some(cancel) = cancel {
|
||||||
|
let handle = app.clone();
|
||||||
|
std::thread::Builder::new().name("browser-engine".into()).spawn(move || {
|
||||||
|
let result = run(&handle, source, &cancel);
|
||||||
|
if let Ok(mut job) = handle.state::<EngineState>().job.lock() {
|
||||||
|
job.phase = None;
|
||||||
|
job.error = result.err().map(|error| error.to_string()).filter(|error| error != CANCELLED);
|
||||||
|
}
|
||||||
|
publish(&handle);
|
||||||
|
})?;
|
||||||
|
}
|
||||||
|
publish(app);
|
||||||
|
status(app)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn browser_engine_status(app: AppHandle) -> Result<Status> {
|
||||||
|
tauri::async_runtime::spawn_blocking(move || status(&app)).await?
|
||||||
|
}
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn browser_engine_install(app: AppHandle) -> Result<Status> {
|
||||||
|
tauri::async_runtime::spawn_blocking(move || start(&app, Source::Download)).await?
|
||||||
|
}
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn browser_engine_install_file(app: AppHandle) -> Result<Status> {
|
||||||
|
tauri::async_runtime::spawn_blocking(move || {
|
||||||
|
let chosen = app.dialog().file().set_title("Install the browser engine").add_filter("Browser engine ZIP", &["zip"]).blocking_pick_file();
|
||||||
|
match chosen {
|
||||||
|
Some(path) => start(&app, Source::File(path.into_path().map_err(Error::from_display)?)),
|
||||||
|
None => status(&app),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await?
|
||||||
|
}
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn browser_engine_cancel(app: AppHandle) -> Result<Status> {
|
||||||
|
tauri::async_runtime::spawn_blocking(move || {
|
||||||
|
app.state::<EngineState>().job.lock()?.cancel.store(true, Ordering::Relaxed);
|
||||||
|
status(&app)
|
||||||
|
})
|
||||||
|
.await?
|
||||||
|
}
|
||||||
|
/// Stop the engine and remove all engine versions. The browser profiles stay.
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn browser_engine_remove(app: AppHandle) -> Result<Status> {
|
||||||
|
tauri::async_runtime::spawn_blocking(move || {
|
||||||
|
if app.state::<EngineState>().job.lock()?.phase.is_some() {
|
||||||
|
return Err("Wait until the browser engine installation ends.".into());
|
||||||
|
}
|
||||||
|
// The windows keep their sessions, so that their tabs can start a newly installed engine.
|
||||||
|
app.state::<crate::browser::BrowserState>().stop_engine();
|
||||||
|
remove_with_retries(&engines(&app)?)?;
|
||||||
|
publish(&app);
|
||||||
|
status(&app)
|
||||||
|
})
|
||||||
|
.await?
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::plugin_sources::tests::server;
|
||||||
|
|
||||||
|
fn base() -> PathBuf {
|
||||||
|
let path = std::env::temp_dir().join(format!("runestone-engine-{}", uuid::Uuid::new_v4()));
|
||||||
|
fs::create_dir_all(&path).unwrap();
|
||||||
|
path
|
||||||
|
}
|
||||||
|
fn zip(path: &Path, entries: &[(&str, &[u8])]) -> Vec<u8> {
|
||||||
|
let mut writer = zip::ZipWriter::new(fs::File::create(path).unwrap());
|
||||||
|
for (name, data) in entries {
|
||||||
|
writer.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
|
||||||
|
writer.write_all(data).unwrap();
|
||||||
|
}
|
||||||
|
writer.finish().unwrap();
|
||||||
|
fs::read(path).unwrap()
|
||||||
|
}
|
||||||
|
fn package(url: &str, bytes: &[u8]) -> Package {
|
||||||
|
Package { url: url.into(), bytes: bytes.len() as u64, sha256: format!("{:x}", Sha256::digest(bytes)) }
|
||||||
|
}
|
||||||
|
fn manifest(version: &str, package: Package) -> Manifest {
|
||||||
|
Manifest { version: version.into(), protocol: PROTOCOL, platforms: HashMap::from([(platform(), package)]) }
|
||||||
|
}
|
||||||
|
fn engine_files() -> Vec<(&'static str, &'static [u8])> {
|
||||||
|
vec![(executable_name(), b"engine"), ("locales/en-US.pak", b"strings"), ("resources/app.asar", b"app")]
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_pinned_manifest_parses_and_invalid_manifests_fail() {
|
||||||
|
let pinned = parse(PINNED).unwrap();
|
||||||
|
assert_eq!(pinned.protocol, PROTOCOL);
|
||||||
|
for text in [
|
||||||
|
r#"{"version":"../1","protocol":1}"#,
|
||||||
|
r#"{"version":"0.1.8","protocol":1,"platforms":{"windows-x86_64":{"url":"x","bytes":1,"sha256":"00"}}}"#,
|
||||||
|
r#"{"version":"0.1.8","protocol":1,"extra":true}"#,
|
||||||
|
] {
|
||||||
|
assert!(parse(text).is_err(), "{text}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn download_checks_size_hash_scheme_and_cancel() {
|
||||||
|
let root = base();
|
||||||
|
let bytes = b"engine archive".to_vec();
|
||||||
|
let (url, handle) = server(vec![("200 OK".into(), bytes.clone())]);
|
||||||
|
let target = root.join("engine.zip");
|
||||||
|
let mut reports = Vec::new();
|
||||||
|
download(&package(&format!("{url}/engine.zip"), &bytes), &target, true, &AtomicBool::new(false), &mut |received| reports.push(received)).unwrap();
|
||||||
|
assert_eq!(fs::read(&target).unwrap(), bytes);
|
||||||
|
assert_eq!(reports.last(), Some(&(bytes.len() as u64)));
|
||||||
|
handle.join().unwrap();
|
||||||
|
fs::remove_file(&target).unwrap();
|
||||||
|
|
||||||
|
let (url, handle) = server(vec![("200 OK".into(), b"engine archivX".to_vec())]);
|
||||||
|
let error = download(&package(&format!("{url}/engine.zip"), &bytes), &target, true, &AtomicBool::new(false), &mut |_| {}).unwrap_err();
|
||||||
|
assert!(error.to_string().contains("SHA-256"), "{error}");
|
||||||
|
assert!(!target.exists(), "A failed download leaves no file.");
|
||||||
|
handle.join().unwrap();
|
||||||
|
|
||||||
|
let (url, handle) = server(vec![("200 OK".into(), b"engine".to_vec())]);
|
||||||
|
let error = download(&package(&format!("{url}/engine.zip"), &bytes), &target, true, &AtomicBool::new(false), &mut |_| {}).unwrap_err();
|
||||||
|
assert!(error.to_string().contains("expected size"), "{error}");
|
||||||
|
handle.join().unwrap();
|
||||||
|
|
||||||
|
let (url, handle) = server(vec![("404 Not Found".into(), Vec::new())]);
|
||||||
|
let error = download(&package(&format!("{url}/engine.zip"), &bytes), &target, true, &AtomicBool::new(false), &mut |_| {}).unwrap_err();
|
||||||
|
assert!(error.to_string().contains("404"), "{error}");
|
||||||
|
handle.join().unwrap();
|
||||||
|
|
||||||
|
let (url, handle) = server(vec![("200 OK".into(), bytes.clone())]);
|
||||||
|
let error = download(&package(&format!("{url}/engine.zip"), &bytes), &target, true, &AtomicBool::new(true), &mut |_| {}).unwrap_err();
|
||||||
|
assert_eq!(error.to_string(), CANCELLED);
|
||||||
|
assert!(!target.exists());
|
||||||
|
handle.join().unwrap();
|
||||||
|
|
||||||
|
let error = download(&package("http://127.0.0.1:9/engine.zip", &bytes), &target, false, &AtomicBool::new(false), &mut |_| {}).unwrap_err();
|
||||||
|
assert!(error.to_string().contains("HTTPS"), "{error}");
|
||||||
|
assert!(allowed(&Url::parse("https://example.com").unwrap(), false));
|
||||||
|
assert!(!allowed(&Url::parse("http://example.com").unwrap(), false));
|
||||||
|
assert!(!allowed(&Url::parse("file:///C:/engine.zip").unwrap(), true));
|
||||||
|
fs::remove_dir_all(&root).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn redirects_must_stay_on_an_allowed_scheme() {
|
||||||
|
let bytes = b"engine archive".to_vec();
|
||||||
|
let (target, target_server) = server(vec![("200 OK".into(), bytes.clone())]);
|
||||||
|
let (origin, origin_server) = server(vec![(format!("302 Found\r\nLocation: {target}/engine.zip"), Vec::new())]);
|
||||||
|
let root = base();
|
||||||
|
let file = root.join("engine.zip");
|
||||||
|
download(&package(&format!("{origin}/engine.zip"), &bytes), &file, true, &AtomicBool::new(false), &mut |_| {}).unwrap();
|
||||||
|
assert_eq!(fs::read(&file).unwrap(), bytes);
|
||||||
|
origin_server.join().unwrap();
|
||||||
|
target_server.join().unwrap();
|
||||||
|
fs::remove_dir_all(&root).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn extraction_refuses_unsafe_archives() {
|
||||||
|
let root = base();
|
||||||
|
let good = root.join("good.zip");
|
||||||
|
zip(&good, &engine_files());
|
||||||
|
extract(&good, &root.join("good"), MAX_EXTRACTED).unwrap();
|
||||||
|
assert_eq!(fs::read(root.join("good").join("locales").join("en-US.pak")).unwrap(), b"strings");
|
||||||
|
for (index, name) in ["../evil.txt", "/absolute.txt", "a\\b.txt", "C:evil.txt", "locales/../../evil.txt", "NUL", "con.txt"].iter().enumerate() {
|
||||||
|
let archive = root.join(format!("bad-{index}.zip"));
|
||||||
|
let mut entries = engine_files();
|
||||||
|
entries.push((name, b"evil"));
|
||||||
|
zip(&archive, &entries);
|
||||||
|
assert!(extract(&archive, &root.join(format!("bad-{index}")), MAX_EXTRACTED).is_err(), "{name}");
|
||||||
|
}
|
||||||
|
assert!(!root.join("evil.txt").exists() && !root.parent().unwrap().join("evil.txt").exists());
|
||||||
|
let duplicate = root.join("duplicate.zip");
|
||||||
|
zip(&duplicate, &[(executable_name(), b"a"), ("Locales/A.pak", b"a"), ("locales/a.pak", b"b")]);
|
||||||
|
assert!(extract(&duplicate, &root.join("duplicate"), MAX_EXTRACTED).unwrap_err().to_string().contains("duplicate"));
|
||||||
|
let missing = root.join("missing.zip");
|
||||||
|
zip(&missing, &[("locales/en-US.pak", b"strings")]);
|
||||||
|
assert!(extract(&missing, &root.join("missing"), MAX_EXTRACTED).unwrap_err().to_string().contains("engine program"));
|
||||||
|
assert!(extract(&good, &root.join("small"), 8).unwrap_err().to_string().contains("too large"));
|
||||||
|
let link = root.join("link.zip");
|
||||||
|
let mut writer = zip::ZipWriter::new(fs::File::create(&link).unwrap());
|
||||||
|
writer.start_file(executable_name(), zip::write::SimpleFileOptions::default()).unwrap();
|
||||||
|
writer.write_all(b"engine").unwrap();
|
||||||
|
writer.add_symlink("resources", "../../outside", zip::write::SimpleFileOptions::default()).unwrap();
|
||||||
|
writer.finish().unwrap();
|
||||||
|
assert!(extract(&link, &root.join("link"), MAX_EXTRACTED).unwrap_err().to_string().contains("links"));
|
||||||
|
fs::write(root.join("not-a-zip.zip"), b"text").unwrap();
|
||||||
|
assert!(extract(&root.join("not-a-zip.zip"), &root.join("text"), MAX_EXTRACTED).is_err());
|
||||||
|
fs::remove_dir_all(&root).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn installation_marks_the_pinned_version_and_removes_older_ones() {
|
||||||
|
let root = base();
|
||||||
|
let engines = root.join("browser-engine");
|
||||||
|
let first = root.join("first.zip");
|
||||||
|
let bytes = zip(&first, &engine_files());
|
||||||
|
let old = manifest("0.1.7", package("https://example.com/first.zip", &bytes));
|
||||||
|
install_archive(&first, &engines, &old, &old.platforms[&platform()]).unwrap();
|
||||||
|
assert_eq!(installed(&engines, &old), Some(engines.join("0.1.7").join(executable_name())));
|
||||||
|
// Another pin with a different hash does not accept this folder.
|
||||||
|
let other = manifest("0.1.7", package("https://example.com/first.zip", b"other"));
|
||||||
|
assert_eq!(installed(&engines, &other), None);
|
||||||
|
|
||||||
|
let second = root.join("second.zip");
|
||||||
|
let mut entries = engine_files();
|
||||||
|
entries.push(("version", b"0.1.8"));
|
||||||
|
let bytes = zip(&second, &entries);
|
||||||
|
let new = manifest("0.1.8", package("https://example.com/second.zip", &bytes));
|
||||||
|
let job = Job::default();
|
||||||
|
assert_eq!(describe(&Ok(new.clone()), &engines, &job, false).state, "update");
|
||||||
|
verify_file(&second, &new.platforms[&platform()], &AtomicBool::new(false)).unwrap();
|
||||||
|
assert!(verify_file(&first, &new.platforms[&platform()], &AtomicBool::new(false)).is_err());
|
||||||
|
install_archive(&second, &engines, &new, &new.platforms[&platform()]).unwrap();
|
||||||
|
remove_others(&engines, &new.version);
|
||||||
|
assert!(installed(&engines, &new).is_some());
|
||||||
|
assert_eq!(installed_versions(&engines), vec!["0.1.8".to_string()]);
|
||||||
|
assert_eq!(fs::read_dir(&engines).unwrap().count(), 1, "No work folder or old version stays.");
|
||||||
|
fs::remove_dir_all(&root).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn status_names_each_engine_state() {
|
||||||
|
let root = base();
|
||||||
|
let bytes = b"engine".to_vec();
|
||||||
|
let pin = manifest("0.1.8", package("https://example.com/engine.zip", &bytes));
|
||||||
|
let idle = Job::default();
|
||||||
|
let state = |manifest: &Result<Manifest>, job: &Job, development: bool| describe(manifest, &root, job, development).state;
|
||||||
|
assert_eq!(state(&Ok(pin.clone()), &idle, false), "missing");
|
||||||
|
assert_eq!(describe(&Ok(pin.clone()), &root, &idle, false).bytes, bytes.len() as u64);
|
||||||
|
assert_eq!(state(&Ok(pin.clone()), &idle, true), "development");
|
||||||
|
let downloading = Job { phase: Some("downloading"), received: 3, ..Job::default() };
|
||||||
|
assert_eq!(describe(&Ok(pin.clone()), &root, &downloading, false), Status { state: "downloading".into(), version: "0.1.8".into(), bytes: 6, received: 3, error: None });
|
||||||
|
let failed = Job { error: Some("The download stopped.".into()), ..Job::default() };
|
||||||
|
assert_eq!(describe(&Ok(pin.clone()), &root, &failed, false).error.as_deref(), Some("The download stopped."));
|
||||||
|
let elsewhere = Manifest { platforms: HashMap::new(), ..pin.clone() };
|
||||||
|
assert_eq!(state(&Ok(elsewhere), &idle, false), "unavailable");
|
||||||
|
assert_eq!(state(&Err("broken".into()), &idle, false), "unavailable");
|
||||||
|
fs::remove_dir_all(&root).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@ mod plugins;
|
|||||||
mod plugin_sources;
|
mod plugin_sources;
|
||||||
mod workspace;
|
mod workspace;
|
||||||
mod browser;
|
mod browser;
|
||||||
|
mod browser_engine;
|
||||||
mod git;
|
mod git;
|
||||||
mod completion;
|
mod completion;
|
||||||
mod settings;
|
mod settings;
|
||||||
@@ -30,6 +31,7 @@ pub fn run() {
|
|||||||
.manage(PtyState::new())
|
.manage(PtyState::new())
|
||||||
.manage(plugins::PluginState::default())
|
.manage(plugins::PluginState::default())
|
||||||
.manage(browser::BrowserState::default())
|
.manage(browser::BrowserState::default())
|
||||||
|
.manage(browser_engine::EngineState::default())
|
||||||
.manage(completion::CompletionState::default())
|
.manage(completion::CompletionState::default())
|
||||||
.manage(settings::SettingsState::default())
|
.manage(settings::SettingsState::default())
|
||||||
.manage(preferences::PreferencesState::default())
|
.manage(preferences::PreferencesState::default())
|
||||||
@@ -68,6 +70,11 @@ pub fn run() {
|
|||||||
browser::browser_request,
|
browser::browser_request,
|
||||||
browser::browser_connect,
|
browser::browser_connect,
|
||||||
browser::browser_stop,
|
browser::browser_stop,
|
||||||
|
browser_engine::browser_engine_status,
|
||||||
|
browser_engine::browser_engine_install,
|
||||||
|
browser_engine::browser_engine_install_file,
|
||||||
|
browser_engine::browser_engine_cancel,
|
||||||
|
browser_engine::browser_engine_remove,
|
||||||
git::git_status,
|
git::git_status,
|
||||||
git::git_diff,
|
git::git_diff,
|
||||||
git::git_stage,
|
git::git_stage,
|
||||||
|
|||||||
Reference in New Issue
Block a user