Release RuneStone 0.1.7 with plugin documents and shared menus
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
mod pty;
|
||||
mod plugins;
|
||||
mod plugin_sources;
|
||||
mod workspace;
|
||||
|
||||
use pty::PtyState;
|
||||
@@ -22,6 +23,7 @@ pub fn run() {
|
||||
workspace::workspace_new,
|
||||
workspace::workspace_list,
|
||||
workspace::workspace_read,
|
||||
workspace::workspace_read_bytes,
|
||||
workspace::workspace_write,
|
||||
workspace::workspace_create,
|
||||
workspace::workspace_rename,
|
||||
@@ -34,6 +36,7 @@ pub fn run() {
|
||||
workspace::workspace_search,
|
||||
plugins::plugins_snapshot,
|
||||
plugins::plugins_choose,
|
||||
plugins::plugins_from_git,
|
||||
plugins::plugins_cancel,
|
||||
plugins::plugins_install,
|
||||
plugins::plugins_set_enabled,
|
||||
|
||||
@@ -0,0 +1,373 @@
|
||||
//! Release downloads are separate from package validation and installation.
|
||||
use reqwest::{blocking::Client, Url};
|
||||
use serde_json::Value;
|
||||
use std::{io::Read, time::Duration};
|
||||
|
||||
type Result<T> = std::result::Result<T, String>;
|
||||
const MAX_METADATA: usize = 2 * 1024 * 1024;
|
||||
const MAX_ARCHIVE: usize = 100 * 1024 * 1024;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Repository {
|
||||
pub url: Url,
|
||||
pub api: Url,
|
||||
}
|
||||
|
||||
fn web_url(input: &str) -> Result<Url> {
|
||||
let url = Url::parse(input).map_err(|_| "Enter a complete HTTP or HTTPS link.")?;
|
||||
if !matches!(url.scheme(), "http" | "https")
|
||||
|| url.host_str().is_none()
|
||||
|| !url.username().is_empty()
|
||||
|| url.password().is_some()
|
||||
|| url.fragment().is_some()
|
||||
{
|
||||
return Err("Use an HTTP or HTTPS link without credentials or a fragment.".into());
|
||||
}
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
impl Repository {
|
||||
pub fn parse(input: &str, tag: &str) -> Result<Self> {
|
||||
let mut url = web_url(input.trim())?;
|
||||
if url.query().is_some() {
|
||||
return Err("Use a repository link without a query.".into());
|
||||
}
|
||||
let path = url
|
||||
.path()
|
||||
.trim_end_matches('/')
|
||||
.trim_end_matches(".git")
|
||||
.to_owned();
|
||||
let parts: Vec<_> = path.trim_start_matches('/').split('/').collect();
|
||||
if parts.len() != 2
|
||||
|| parts.iter().any(|part| {
|
||||
part.is_empty()
|
||||
|| *part == "."
|
||||
|| *part == ".."
|
||||
|| !part
|
||||
.bytes()
|
||||
.all(|c| c.is_ascii_alphanumeric() || b"._-".contains(&c))
|
||||
})
|
||||
{
|
||||
return Err(
|
||||
"Use the repository root link, such as https://host/owner/repository.".into(),
|
||||
);
|
||||
}
|
||||
url.set_path(&path);
|
||||
let mut api = url.clone();
|
||||
api.set_path("/");
|
||||
{
|
||||
let mut segments = api
|
||||
.path_segments_mut()
|
||||
.map_err(|_| "Invalid repository link.")?;
|
||||
segments.clear();
|
||||
segments
|
||||
.extend(["api", "v1", "repos"])
|
||||
.extend(&parts)
|
||||
.push("releases");
|
||||
let tag = tag.trim();
|
||||
if tag.is_empty() {
|
||||
segments.push("latest");
|
||||
} else {
|
||||
if tag.len() > 200 || tag.chars().any(char::is_control) || matches!(tag, "." | "..")
|
||||
{
|
||||
return Err("Enter a release tag with at most 200 characters.".into());
|
||||
}
|
||||
segments.push("tags");
|
||||
segments.push(tag);
|
||||
}
|
||||
}
|
||||
Ok(Self { url, api })
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Download {
|
||||
pub bytes: Vec<u8>,
|
||||
pub source: String,
|
||||
}
|
||||
|
||||
fn read_limited(reader: impl Read, limit: usize) -> Result<Vec<u8>> {
|
||||
let mut bytes = Vec::new();
|
||||
reader
|
||||
.take(limit as u64 + 1)
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|_| "The download was interrupted. Try again.")?;
|
||||
if bytes.len() > limit {
|
||||
return Err("The download exceeds its size limit.".into());
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
// Send credentials only to the release API's origin, including after redirects.
|
||||
fn get(
|
||||
client: &Client,
|
||||
start: Url,
|
||||
auth_origin: &Url,
|
||||
authorization: Option<&str>,
|
||||
limit: usize,
|
||||
) -> Result<Vec<u8>> {
|
||||
let mut url = start;
|
||||
let started = std::time::Instant::now();
|
||||
for _ in 0..=5 {
|
||||
let remaining = Duration::from_secs(60)
|
||||
.checked_sub(started.elapsed())
|
||||
.filter(|remaining| !remaining.is_zero())
|
||||
.ok_or("The download timed out. Try again.")?;
|
||||
let mut request = client.get(url.clone()).timeout(remaining);
|
||||
if url.origin() == auth_origin.origin() {
|
||||
if let Some(value) = authorization {
|
||||
request = request.header(reqwest::header::AUTHORIZATION, value);
|
||||
}
|
||||
}
|
||||
let response = request
|
||||
.send()
|
||||
.map_err(|_| "Cannot reach the release server. Check the link and connection.")?;
|
||||
if response.status().is_redirection() {
|
||||
let location = response
|
||||
.headers()
|
||||
.get(reqwest::header::LOCATION)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.ok_or("The server returned an invalid redirect.")?;
|
||||
let next = url
|
||||
.join(location)
|
||||
.map_err(|_| "The server returned an invalid redirect.")?;
|
||||
web_url(next.as_str())?;
|
||||
if url.scheme() == "https" && next.scheme() != "https" {
|
||||
return Err("The server redirected a secure link to HTTP.".into());
|
||||
}
|
||||
url = next;
|
||||
continue;
|
||||
}
|
||||
if !response.status().is_success() {
|
||||
return Err(match response.status().as_u16() {
|
||||
401 | 403 => "Access denied. Check the token and repository read access.".into(),
|
||||
404 => "Release not found. Check the repository, release tag, and token for private access.".into(),
|
||||
429 => "The server request limit was reached. Try again later.".into(),
|
||||
code => format!("The release server returned HTTP {code}."),
|
||||
});
|
||||
}
|
||||
if response
|
||||
.content_length()
|
||||
.is_some_and(|size| size > limit as u64)
|
||||
{
|
||||
return Err("The download exceeds its size limit.".into());
|
||||
}
|
||||
return read_limited(response, limit);
|
||||
}
|
||||
Err("The server returned too many redirects.".into())
|
||||
}
|
||||
|
||||
fn asset(metadata: &Value) -> Result<(String, Url)> {
|
||||
if metadata["draft"].as_bool() == Some(true) {
|
||||
return Err("Publish the release before installing its plugin.".into());
|
||||
}
|
||||
let tag = metadata["tag_name"]
|
||||
.as_str()
|
||||
.filter(|tag| !tag.is_empty())
|
||||
.ok_or("The release has no tag.")?;
|
||||
let assets = &metadata["assets"];
|
||||
let zips: Vec<_> = assets
|
||||
.as_array()
|
||||
.ok_or("The release has no attached plugin ZIP.")?
|
||||
.iter()
|
||||
.filter(|item| {
|
||||
item["name"]
|
||||
.as_str()
|
||||
.is_some_and(|name| name.to_ascii_lowercase().ends_with(".zip"))
|
||||
})
|
||||
.collect();
|
||||
if zips.len() != 1 {
|
||||
return Err(
|
||||
"The release must contain exactly one plugin ZIP. Source archives do not count.".into(),
|
||||
);
|
||||
}
|
||||
let item = zips[0];
|
||||
let link = item["browser_download_url"]
|
||||
.as_str()
|
||||
.ok_or("The plugin ZIP has no download link.")?;
|
||||
if item["size"]
|
||||
.as_u64()
|
||||
.is_some_and(|size| size > MAX_ARCHIVE as u64)
|
||||
{
|
||||
return Err("The archive exceeds 100 MiB.".into());
|
||||
}
|
||||
Ok((tag.to_owned(), web_url(link)?))
|
||||
}
|
||||
|
||||
pub fn download(repository: &Repository, token: Option<&str>) -> Result<Download> {
|
||||
let authorization = token
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(|value| format!("token {value}"));
|
||||
download_authorized(repository, authorization.as_deref())
|
||||
}
|
||||
|
||||
fn download_authorized(repository: &Repository, authorization: Option<&str>) -> Result<Download> {
|
||||
let client = Client::builder()
|
||||
.user_agent("RuneStone-plugin-installer/0.1")
|
||||
.connect_timeout(Duration::from_secs(10))
|
||||
.timeout(Duration::from_secs(60))
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.build()
|
||||
.map_err(|_| "Cannot start the download client.")?;
|
||||
let metadata = get(
|
||||
&client,
|
||||
repository.api.clone(),
|
||||
&repository.api,
|
||||
authorization,
|
||||
MAX_METADATA,
|
||||
)?;
|
||||
let metadata: Value = serde_json::from_slice(&metadata)
|
||||
.map_err(|_| "The server did not return release metadata.")?;
|
||||
let (tag, url) = asset(&metadata)?;
|
||||
if repository.url.scheme() == "https" && url.scheme() != "https" {
|
||||
return Err("The plugin ZIP must use HTTPS for this repository.".into());
|
||||
}
|
||||
let bytes = get(
|
||||
&client,
|
||||
url.clone(),
|
||||
&repository.api,
|
||||
authorization,
|
||||
MAX_ARCHIVE,
|
||||
)?;
|
||||
// Query parameters can contain temporary download credentials.
|
||||
let mut display = url;
|
||||
display.set_query(None);
|
||||
Ok(Download {
|
||||
bytes,
|
||||
source: format!("{} @ {}\n{}", repository.url, tag, display),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
use std::{io::Write, net::TcpListener, thread, time::Instant};
|
||||
|
||||
pub fn server(responses: Vec<(String, Vec<u8>)>) -> (String, thread::JoinHandle<Vec<String>>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
listener.set_nonblocking(true).unwrap();
|
||||
let base = format!("http://{}", listener.local_addr().unwrap());
|
||||
let handle = thread::spawn(move || {
|
||||
let mut requests = Vec::new();
|
||||
for (headers, body) in responses {
|
||||
let start = Instant::now();
|
||||
let mut stream = loop {
|
||||
match listener.accept() {
|
||||
Ok((stream, _)) => break stream,
|
||||
Err(error)
|
||||
if error.kind() == std::io::ErrorKind::WouldBlock
|
||||
&& start.elapsed() < Duration::from_secs(15) =>
|
||||
{
|
||||
thread::sleep(Duration::from_millis(10))
|
||||
}
|
||||
Err(error) => panic!("Test server did not receive a request: {error}"),
|
||||
}
|
||||
};
|
||||
stream.set_nonblocking(false).unwrap();
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(5)))
|
||||
.unwrap();
|
||||
let mut request = Vec::new();
|
||||
while !request.ends_with(b"\r\n\r\n") {
|
||||
let mut byte = [0];
|
||||
stream.read_exact(&mut byte).unwrap();
|
||||
request.push(byte[0]);
|
||||
assert!(request.len() < 16384);
|
||||
}
|
||||
requests.push(String::from_utf8(request).unwrap());
|
||||
write!(
|
||||
stream,
|
||||
"HTTP/1.1 {headers}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
|
||||
body.len()
|
||||
)
|
||||
.unwrap();
|
||||
stream.write_all(&body).unwrap();
|
||||
}
|
||||
requests
|
||||
});
|
||||
(base, handle)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn network_errors_limits_and_redirect_credentials() {
|
||||
let client = Client::builder()
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.build()
|
||||
.unwrap();
|
||||
let (target, target_server) = server(vec![("200 OK".into(), b"zip".to_vec())]);
|
||||
let (origin, origin_server) = server(vec![(
|
||||
format!("302 Found\r\nLocation: {target}/download"),
|
||||
vec![],
|
||||
)]);
|
||||
let url = Url::parse(&origin).unwrap();
|
||||
assert_eq!(
|
||||
get(&client, url.clone(), &url, Some("token secret"), 10).unwrap(),
|
||||
b"zip"
|
||||
);
|
||||
assert!(origin_server.join().unwrap()[0].contains("authorization: token secret"));
|
||||
assert!(!target_server.join().unwrap()[0]
|
||||
.to_lowercase()
|
||||
.contains("authorization:"));
|
||||
for (status, body, limit, message) in [
|
||||
("404 Not Found", vec![], 100, "Release not found"),
|
||||
("403 Forbidden", vec![], 100, "Access denied"),
|
||||
("200 OK", b"12345".to_vec(), 4, "size limit"),
|
||||
(
|
||||
"302 Found\r\nLocation: file:///secret",
|
||||
vec![],
|
||||
100,
|
||||
"HTTP or HTTPS",
|
||||
),
|
||||
] {
|
||||
let (base, handle) = server(vec![(status.into(), body)]);
|
||||
let url = Url::parse(&base).unwrap();
|
||||
assert!(get(&client, url.clone(), &url, None, limit)
|
||||
.unwrap_err()
|
||||
.contains(message));
|
||||
handle.join().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repository_routes_and_tags() {
|
||||
let cases = [
|
||||
(
|
||||
"https://git.example/owner/demo.git/",
|
||||
"",
|
||||
"https://git.example/api/v1/repos/owner/demo/releases/latest",
|
||||
),
|
||||
(
|
||||
"http://localhost:6610/group/demo",
|
||||
"trial/1",
|
||||
"http://localhost:6610/api/v1/repos/group/demo/releases/tags/trial%2F1",
|
||||
),
|
||||
];
|
||||
for (url, tag, expected) in cases {
|
||||
assert_eq!(Repository::parse(url, tag).unwrap().api.as_str(), expected);
|
||||
}
|
||||
for bad in [
|
||||
"file:///tmp/plugin",
|
||||
"git@example:owner/demo",
|
||||
"https://user:secret@example/a/b",
|
||||
"https://example/a/b?token=secret",
|
||||
"https://example/a/b/tree/main",
|
||||
"https://example/a/b#main",
|
||||
] {
|
||||
assert!(Repository::parse(bad, "").is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn release_assets_are_explicit_and_unambiguous() {
|
||||
let zip = json!({"name":"org.test.demo-1.0.0.zip", "browser_download_url":"https://example/demo.zip"});
|
||||
assert!(asset(&json!({"tag_name":"v1", "assets":[zip.clone()]})).is_ok());
|
||||
assert!(asset(
|
||||
&json!({"tag_name":"v1", "zipball_url":"https://example/source.zip", "assets":[]})
|
||||
)
|
||||
.is_err());
|
||||
assert!(asset(&json!({"tag_name":"v1", "assets":[zip.clone(),zip.clone()]})).is_err());
|
||||
assert!(asset(&json!({"tag_name":"v1", "draft":true, "assets":[zip]})).is_err());
|
||||
assert!(read_limited(&b"12345"[..], 4).is_err());
|
||||
assert_eq!(read_limited(&b"1234"[..], 4).unwrap(), b"1234");
|
||||
}
|
||||
}
|
||||
+272
-53
@@ -6,7 +6,7 @@ use std::{
|
||||
io::Read,
|
||||
path::{Path, PathBuf},
|
||||
sync::Mutex,
|
||||
time::{Duration, Instant},
|
||||
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
use tauri::{AppHandle, Emitter, Manager, State};
|
||||
use tauri_plugin_dialog::DialogExt;
|
||||
@@ -44,6 +44,8 @@ struct Installed {
|
||||
hash: String,
|
||||
enabled: bool,
|
||||
#[serde(default)]
|
||||
installed_at: Option<u64>,
|
||||
#[serde(default)]
|
||||
removal: Option<String>,
|
||||
#[serde(default)]
|
||||
removal_files: BTreeMap<String, String>,
|
||||
@@ -59,6 +61,7 @@ pub struct PluginRow {
|
||||
pub manifest: Manifest,
|
||||
pub hash: String,
|
||||
pub enabled: bool,
|
||||
pub installed_at: Option<u64>,
|
||||
pub path: String,
|
||||
pub error: Option<String>,
|
||||
pub removal: bool,
|
||||
@@ -77,7 +80,7 @@ pub struct CandidateRow {
|
||||
}
|
||||
struct Candidate {
|
||||
owner: String,
|
||||
source: PathBuf,
|
||||
source: Option<PathBuf>,
|
||||
directory: PathBuf,
|
||||
hash: String,
|
||||
manifest: Manifest,
|
||||
@@ -267,11 +270,6 @@ fn tree_hash(path: &Path) -> Result<String> {
|
||||
Ok(fingerprint(&directory_files(path)?))
|
||||
}
|
||||
fn package(source: &Path) -> Result<Package> {
|
||||
let source = if source.file_name().is_some_and(|n| n == "plugin.json") {
|
||||
source.parent().ok_or("Missing plugin folder.")?
|
||||
} else {
|
||||
source
|
||||
};
|
||||
let mut files = BTreeMap::new();
|
||||
let mut names = BTreeSet::new();
|
||||
let mut total = 0;
|
||||
@@ -279,9 +277,7 @@ fn package(source: &Path) -> Result<Package> {
|
||||
if meta.is_dir() {
|
||||
walk(source, source, &mut files, &mut names, &mut total, &mut 0)?;
|
||||
} else {
|
||||
if source.extension().and_then(|s| s.to_str()) != Some("runestone-plugin") {
|
||||
return Err("Select a .runestone-plugin package or plugin.json.".into());
|
||||
}
|
||||
require_zip(source)?;
|
||||
if meta.len() > MAX_TOTAL as u64 {
|
||||
return Err("The archive exceeds 100 MiB.".into());
|
||||
}
|
||||
@@ -369,6 +365,19 @@ fn package(source: &Path) -> Result<Package> {
|
||||
hash,
|
||||
})
|
||||
}
|
||||
fn require_zip(source: &Path) -> Result<()> {
|
||||
if !source
|
||||
.extension()
|
||||
.and_then(|s| s.to_str())
|
||||
.is_some_and(|s| s.eq_ignore_ascii_case("zip"))
|
||||
|| !plain(source)?.is_file()
|
||||
{
|
||||
return Err(
|
||||
"Select a plugin .zip file. The archive must contain plugin.json at its root.".into(),
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn safe_child(parent: &Path, child: &Path) -> Result<()> {
|
||||
plain(parent)?;
|
||||
plain(child)?;
|
||||
@@ -517,6 +526,7 @@ impl Service {
|
||||
manifest,
|
||||
hash,
|
||||
enabled: record.enabled && error.is_none() && !self.removing.contains_key(id),
|
||||
installed_at: record.installed_at,
|
||||
path: path.to_string_lossy().into_owned(),
|
||||
error,
|
||||
removal: record.removal.is_some(),
|
||||
@@ -543,6 +553,7 @@ impl Service {
|
||||
manifest: current.manifest,
|
||||
hash: current.hash,
|
||||
enabled: false,
|
||||
installed_at: None,
|
||||
removal: None,
|
||||
removal_files: BTreeMap::new(),
|
||||
},
|
||||
@@ -609,7 +620,7 @@ impl Service {
|
||||
token.clone(),
|
||||
Candidate {
|
||||
owner: owner.into(),
|
||||
source,
|
||||
source: Some(source),
|
||||
directory: staging,
|
||||
hash: current.hash,
|
||||
manifest: manifest.clone(),
|
||||
@@ -641,6 +652,22 @@ impl Service {
|
||||
}
|
||||
}
|
||||
}
|
||||
fn inspect_download(&mut self, owner: &str, download: crate::plugin_sources::Download) -> Result<CandidateRow> {
|
||||
let parent = self.directory("plugin-staging")?;
|
||||
let archive = parent.join(format!("{}.zip", uid()));
|
||||
fs::write(&archive, download.bytes).map_err(fail)?;
|
||||
let mut row = self.inspect(owner, archive.clone());
|
||||
if let Some(candidate) = self.candidates.get_mut(&row.token) {
|
||||
// Review pins the downloaded bytes. Remote releases can change independently.
|
||||
candidate.source = None;
|
||||
}
|
||||
row.source = download.source;
|
||||
if let Err(error) = erase(&parent, &archive) {
|
||||
if let Some(candidate) = self.candidates.remove(&row.token) { let _ = erase(&parent, &candidate.directory); }
|
||||
return Err(error);
|
||||
}
|
||||
Ok(row)
|
||||
}
|
||||
fn install(&mut self, owner: &str, token: &str, enabled: bool) -> Result<String> {
|
||||
let candidate = self
|
||||
.candidates
|
||||
@@ -653,7 +680,7 @@ impl Service {
|
||||
if self.catalog.plugins.contains_key(&id) {
|
||||
return Err("This plugin ID is already installed.".into());
|
||||
}
|
||||
if package(&candidate.source)?.hash != candidate.hash
|
||||
if candidate.source.as_ref().map(|source| package(source)).transpose()?.is_some_and(|source| source.hash != candidate.hash)
|
||||
|| package(&candidate.directory)?.hash != candidate.hash
|
||||
{
|
||||
return Err("The package changed after review. Select it again.".into());
|
||||
@@ -664,6 +691,10 @@ impl Service {
|
||||
return Err("The plugin directory already exists.".into());
|
||||
}
|
||||
safe_child(&self.directory("plugin-staging")?, &candidate.directory)?;
|
||||
let installed_at = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_err(fail)?
|
||||
.as_millis() as u64;
|
||||
// Persist disabled first. A crash cannot enable unreviewed or partial code.
|
||||
self.catalog.plugins.insert(
|
||||
id.clone(),
|
||||
@@ -671,6 +702,7 @@ impl Service {
|
||||
manifest: candidate.manifest.clone(),
|
||||
hash: candidate.hash.clone(),
|
||||
enabled: false,
|
||||
installed_at: Some(installed_at),
|
||||
removal: None,
|
||||
removal_files: BTreeMap::new(),
|
||||
},
|
||||
@@ -874,61 +906,56 @@ pub async fn plugins_snapshot(app: AppHandle, state: State<'_, PluginState>) ->
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn plugins_choose(
|
||||
app: AppHandle,
|
||||
window: tauri::Window,
|
||||
folder: bool,
|
||||
) -> Result<Vec<CandidateRow>> {
|
||||
pub async fn plugins_choose(app: AppHandle, window: tauri::Window) -> Result<Vec<CandidateRow>> {
|
||||
let picker_app = app.clone();
|
||||
let source = tauri::async_runtime::spawn_blocking(move || {
|
||||
let picker = picker_app
|
||||
picker_app
|
||||
.dialog()
|
||||
.file()
|
||||
.set_title("Install RuneStone plugins");
|
||||
if folder {
|
||||
picker.blocking_pick_folder()
|
||||
} else {
|
||||
picker
|
||||
.add_filter("RuneStone plugins", &["runestone-plugin", "json"])
|
||||
.blocking_pick_file()
|
||||
}
|
||||
.set_title("Install plugin ZIP")
|
||||
.add_filter("Plugin ZIP archives", &["zip"])
|
||||
.blocking_pick_files()
|
||||
})
|
||||
.await
|
||||
.map_err(fail)?;
|
||||
let Some(source) = source else {
|
||||
let Some(sources) = source else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let source = source.into_path().map_err(fail)?;
|
||||
if sources.len() > 100 {
|
||||
return Err("Select at most 100 plugin ZIP files.".into());
|
||||
}
|
||||
let paths: Vec<PathBuf> = sources
|
||||
.into_iter()
|
||||
.map(|source| source.into_path().map_err(fail))
|
||||
.collect::<Result<_>>()?;
|
||||
for path in &paths {
|
||||
require_zip(path)?;
|
||||
}
|
||||
app.state::<PluginState>().with(&app, |service| {
|
||||
let mut paths = Vec::new();
|
||||
if source.is_dir() && !source.join("plugin.json").exists() {
|
||||
plain(&source)?;
|
||||
for (index, entry) in fs::read_dir(&source).map_err(fail)?.enumerate() {
|
||||
if index >= 100 {
|
||||
return Err("Choose a collection with at most 100 entries.".into());
|
||||
}
|
||||
let path = entry.map_err(fail)?.path();
|
||||
if path.is_dir()
|
||||
|| path.extension().and_then(|n| n.to_str()) == Some("runestone-plugin")
|
||||
{
|
||||
paths.push(path);
|
||||
}
|
||||
}
|
||||
if paths.len() > 100 {
|
||||
return Err("Choose a collection with at most 100 plugins.".into());
|
||||
}
|
||||
} else {
|
||||
paths.push(source);
|
||||
}
|
||||
if paths.is_empty() {
|
||||
return Err("No plugin packages or folders were found.".into());
|
||||
}
|
||||
Ok(paths
|
||||
.into_iter()
|
||||
.map(|path| service.inspect(window.label(), path))
|
||||
.collect())
|
||||
})
|
||||
}
|
||||
#[tauri::command]
|
||||
pub async fn plugins_from_git(
|
||||
app: AppHandle,
|
||||
window: tauri::Window,
|
||||
url: String,
|
||||
tag: String,
|
||||
token: Option<String>,
|
||||
) -> Result<Vec<CandidateRow>> {
|
||||
let repository = crate::plugin_sources::Repository::parse(&url, &tag)?;
|
||||
// Network access never holds the plugin service lock.
|
||||
let download = tauri::async_runtime::spawn_blocking(move || {
|
||||
crate::plugin_sources::download(&repository, token.as_deref())
|
||||
}).await.map_err(fail)??;
|
||||
app.state::<PluginState>().with(&app, |service| {
|
||||
Ok(vec![service.inspect_download(window.label(), download)?])
|
||||
})
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn plugins_cancel(
|
||||
app: AppHandle,
|
||||
@@ -1263,11 +1290,203 @@ mod tests {
|
||||
}
|
||||
zip.finish().unwrap();
|
||||
}
|
||||
fn review_remote(fixture: &mut Fixture, bytes: Vec<u8>) -> CandidateRow {
|
||||
use crate::plugin_sources::{tests::server, Repository};
|
||||
let (asset_url, asset_server) = server(vec![("200 OK".into(), bytes)]);
|
||||
let metadata = serde_json::json!({"tag_name":"trial-1", "assets":[{
|
||||
"name":"plugin.zip", "browser_download_url":format!("{asset_url}/plugin.zip")
|
||||
}]});
|
||||
let (base, metadata_server) = server(vec![("200 OK".into(), serde_json::to_vec(&metadata).unwrap())]);
|
||||
let repository = Repository::parse(&format!("{base}/owner/plugin.git"), "trial-1").unwrap();
|
||||
let download = crate::plugin_sources::download(&repository, Some("test-token")).unwrap();
|
||||
let requests = metadata_server.join().unwrap();
|
||||
assert!(requests[0].starts_with("GET /api/v1/repos/owner/plugin/releases/tags/trial-1 "));
|
||||
assert!(requests[0].contains("authorization: token test-token"));
|
||||
assert!(!asset_server.join().unwrap()[0].contains("test-token"));
|
||||
fixture.service.inspect_download("main", download).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_download_uses_review_and_package_checks() {
|
||||
let mut f = Fixture::new();
|
||||
let archive_path = f.root.join("demo.zip");
|
||||
let manifest = fs::read(f.source.join("plugin.json")).unwrap();
|
||||
archive(&archive_path, &[("plugin.json", &manifest), ("main.js", b"export function activate() {}")]);
|
||||
let bytes = fs::read(&archive_path).unwrap();
|
||||
let candidate = review_remote(&mut f, bytes.clone());
|
||||
assert!(candidate.error.is_none(), "{:?}", candidate.error);
|
||||
assert!(candidate.source.contains("trial-1"));
|
||||
assert!(f.service.candidates[&candidate.token].source.is_none());
|
||||
assert!(f.service.install("other-window", &candidate.token, false).is_err());
|
||||
let staging = f.service.candidates[&candidate.token].directory.clone();
|
||||
fs::write(staging.join("main.js"), "changed").unwrap();
|
||||
assert!(f.service.install("main", &candidate.token, false).is_err());
|
||||
let candidate = review_remote(&mut f, bytes);
|
||||
let id = candidate.manifest.as_ref().unwrap().id.clone();
|
||||
f.service.install("main", &candidate.token, false).unwrap();
|
||||
assert!(!f.service.row(&id).unwrap().enabled);
|
||||
assert!(f.service.install("main", &candidate.token, false).is_err());
|
||||
let invalid = review_remote(&mut f, b"not a zip".to_vec());
|
||||
assert!(invalid.error.is_some());
|
||||
archive(&archive_path, &[("../outside", b"bad")]);
|
||||
let invalid = review_remote(&mut f, fs::read(&archive_path).unwrap());
|
||||
assert!(invalid.error.is_some());
|
||||
assert!(!f.root.join("outside").exists());
|
||||
assert!(fs::read_dir(f.service.directory("plugin-staging").unwrap()).unwrap()
|
||||
.all(|entry| entry.unwrap().path().extension().is_none_or(|ext| ext != "zip")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "Set RUNESTONE_GIT_TRIAL_PACKAGES to the folder with the four trial ZIPs."]
|
||||
fn four_plugin_release_trial() {
|
||||
let directory = PathBuf::from(std::env::var("RUNESTONE_GIT_TRIAL_PACKAGES").unwrap());
|
||||
let archives: Vec<_> = fs::read_dir(directory).unwrap().map(|entry| entry.unwrap().path())
|
||||
.filter(|path| path.extension().is_some_and(|ext| ext == "zip")).collect();
|
||||
assert_eq!(archives.len(), 4);
|
||||
let mut f = Fixture::new();
|
||||
let mut ids = BTreeSet::new();
|
||||
for path in archives {
|
||||
let expected = package(&path).unwrap();
|
||||
let candidate = review_remote(&mut f, fs::read(&path).unwrap());
|
||||
assert!(candidate.error.is_none(), "{:?}", candidate.error);
|
||||
let id = candidate.manifest.as_ref().unwrap().id.clone();
|
||||
f.service.install("main", &candidate.token, false).unwrap();
|
||||
assert_eq!(f.service.row(&id).unwrap().hash, expected.hash);
|
||||
assert!(!f.service.row(&id).unwrap().enabled);
|
||||
println!("Release download, review, and isolated install passed: {} {}", id, expected.manifest.version);
|
||||
ids.insert(id);
|
||||
}
|
||||
assert_eq!(ids.len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "Requires an approved live Gitea release and repository read access."]
|
||||
fn live_gitea_release_trial() {
|
||||
let repository = crate::plugin_sources::Repository::parse(
|
||||
&std::env::var("RUNESTONE_GIT_TRIAL_URL").unwrap(),
|
||||
&std::env::var("RUNESTONE_GIT_TRIAL_TAG").unwrap(),
|
||||
).unwrap();
|
||||
let token = std::env::var("RUNESTONE_GIT_TRIAL_TOKEN").ok();
|
||||
let download = crate::plugin_sources::download(&repository, token.as_deref()).unwrap();
|
||||
let expected = package(&PathBuf::from(std::env::var("RUNESTONE_GIT_TRIAL_ZIP").unwrap())).unwrap();
|
||||
let mut f = Fixture::new();
|
||||
let candidate = f.service.inspect_download("main", download).unwrap();
|
||||
assert!(candidate.error.is_none(), "{:?}", candidate.error);
|
||||
let id = candidate.manifest.as_ref().unwrap().id.clone();
|
||||
f.service.install("main", &candidate.token, false).unwrap();
|
||||
assert_eq!(f.service.row(&id).unwrap().hash, expected.hash);
|
||||
assert!(!f.service.row(&id).unwrap().enabled);
|
||||
println!("Live Gitea download, review, and isolated install passed: {} {}", id, expected.manifest.version);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_time_survives_reload_and_state_changes() {
|
||||
let mut f = Fixture::new();
|
||||
let before = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_millis() as u64;
|
||||
let id = f.install(false);
|
||||
let after = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_millis() as u64;
|
||||
let installed_at = f.service.row(&id).unwrap().installed_at.unwrap();
|
||||
assert!((before..=after).contains(&installed_at));
|
||||
let mut reopened = Service::open(f.root.join("app")).unwrap();
|
||||
reopened.catalog.plugins.get_mut(&id).unwrap().enabled = true;
|
||||
reopened.persist().unwrap();
|
||||
let mut reopened = Service::open(f.root.join("app")).unwrap();
|
||||
let snapshot = serde_json::to_value(reopened.snapshot().unwrap()).unwrap();
|
||||
assert_eq!(snapshot["plugins"][0]["installedAt"], installed_at);
|
||||
let plan = reopened.prepare("main", &id).unwrap();
|
||||
assert_eq!(plan.plugin.installed_at, Some(installed_at));
|
||||
reopened.begin_remove("main", &plan.token).unwrap();
|
||||
reopened.finish_remove(&id).unwrap();
|
||||
assert!(!reopened.catalog.plugins.contains_key(&id));
|
||||
f.service = reopened;
|
||||
f.install(true);
|
||||
assert!(f.service.row(&id).unwrap().installed_at.unwrap() >= installed_at);
|
||||
}
|
||||
#[test]
|
||||
fn legacy_and_discovered_plugins_keep_unknown_install_times() {
|
||||
let mut f = Fixture::new();
|
||||
let id = f.install(false);
|
||||
let path = f.root.join("app/plugin-state.json");
|
||||
let mut catalog = serde_json::to_value(&f.service.catalog).unwrap();
|
||||
catalog["plugins"][&id]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("installedAt");
|
||||
fs::write(&path, serde_json::to_vec(&catalog).unwrap()).unwrap();
|
||||
let mut reopened = Service::open(f.root.join("app")).unwrap();
|
||||
assert_eq!(reopened.snapshot().unwrap().plugins[0].installed_at, None);
|
||||
reopened.catalog.plugins.clear();
|
||||
reopened.persist().unwrap();
|
||||
assert_eq!(reopened.snapshot().unwrap().plugins[0].installed_at, None);
|
||||
let mut reopened = Service::open(f.root.join("app")).unwrap();
|
||||
assert_eq!(reopened.snapshot().unwrap().plugins[0].installed_at, None);
|
||||
}
|
||||
#[test]
|
||||
fn installer_accepts_only_zip_files() {
|
||||
let f = Fixture::new();
|
||||
assert!(require_zip(&f.source).is_err());
|
||||
assert!(require_zip(&f.source.join("plugin.json")).is_err());
|
||||
let legacy = f.root.join("demo.runestone-plugin");
|
||||
archive(&legacy, &[("main.js", b"test")]);
|
||||
assert!(require_zip(&legacy).is_err());
|
||||
assert!(package(&legacy).is_err());
|
||||
let upper = f.root.join("demo.ZIP");
|
||||
fs::copy(&legacy, &upper).unwrap();
|
||||
assert!(require_zip(&upper).is_ok());
|
||||
let wrapped = f.root.join("wrapped.zip");
|
||||
archive(&wrapped, &[("demo/plugin.json", b"{}")]);
|
||||
assert!(package(&wrapped).unwrap_err().contains("at its root"));
|
||||
}
|
||||
#[test]
|
||||
fn author_packager_produces_an_installable_repeatable_zip() {
|
||||
let mut f = Fixture::new();
|
||||
fs::create_dir(f.source.join("assets")).unwrap();
|
||||
fs::write(f.source.join("assets/style.css"), "body { color: red; }").unwrap();
|
||||
let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../scripts/packagePlugin.mjs");
|
||||
let output = f.root.join("releases");
|
||||
let build = || {
|
||||
let result = std::process::Command::new("node")
|
||||
.arg(&script)
|
||||
.arg(&f.source)
|
||||
.arg(&output)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
result.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&result.stderr)
|
||||
);
|
||||
};
|
||||
build();
|
||||
let path = output.join("org.test.demo-1.0.0.zip");
|
||||
let first = fs::read(&path).unwrap();
|
||||
build();
|
||||
assert_eq!(first, fs::read(&path).unwrap());
|
||||
assert_eq!(
|
||||
package(&path).unwrap().hash,
|
||||
package(&f.source).unwrap().hash
|
||||
);
|
||||
let row = f.service.inspect("main", path);
|
||||
assert!(row.error.is_none(), "{:?}", row.error);
|
||||
f.service.install("main", &row.token, false).unwrap();
|
||||
let installed = f.service.row("org.test.demo").unwrap();
|
||||
assert!(!installed.enabled);
|
||||
assert_eq!(
|
||||
fs::read(Path::new(&installed.path).join("assets/style.css")).unwrap(),
|
||||
b"body { color: red; }"
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn installs_directory_and_zip_without_changing_source() {
|
||||
let mut f = Fixture::new();
|
||||
let original = package(&f.source).unwrap();
|
||||
let archive_path = f.root.join("demo.runestone-plugin");
|
||||
let archive_path = f.root.join("demo.zip");
|
||||
let entries: Vec<_> = original
|
||||
.files
|
||||
.iter()
|
||||
@@ -1336,7 +1555,7 @@ mod tests {
|
||||
assert!(!valid_id(id), "{id}");
|
||||
}
|
||||
let f = Fixture::new();
|
||||
let path = f.root.join("bad.runestone-plugin");
|
||||
let path = f.root.join("bad.zip");
|
||||
archive(&path, &[("../outside", b"test")]);
|
||||
assert!(package(&path).is_err());
|
||||
assert!(!f.root.join("outside").exists());
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use std::fs;
|
||||
use std::collections::HashMap;
|
||||
use std::io::Write;
|
||||
use std::io::{Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
@@ -511,14 +511,43 @@ fn list_entries(root: &Path, rel: &str) -> WsResult<Vec<TreeEntry>> {
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn workspace_read(window: tauri::Window, state: State<WorkspaceState>, rel: String) -> WsResult<String> {
|
||||
pub fn workspace_read(window: tauri::Window, state: State<WorkspaceState>, rel: String, missing_ok: Option<bool>) -> WsResult<Option<String>> {
|
||||
let root = current_root(&state, window.label())?;
|
||||
let path = resolve_existing(&root, &rel)?;
|
||||
let path = if missing_ok.unwrap_or(false) { resolve_for_write(&root, &rel)? } else { resolve_existing(&root, &rel)? };
|
||||
if path.is_dir() {
|
||||
return Err(err("path is a folder"));
|
||||
}
|
||||
let bytes = fs::read(&path)?;
|
||||
String::from_utf8(bytes).map_err(|_| err("file is not valid UTF-8"))
|
||||
read_optional_text(&path, missing_ok.unwrap_or(false))
|
||||
}
|
||||
|
||||
fn read_optional_text(path: &Path, missing_ok: bool) -> WsResult<Option<String>> {
|
||||
match fs::read(path) {
|
||||
Ok(bytes) => String::from_utf8(bytes).map(Some).map_err(|_| err("file is not valid UTF-8")),
|
||||
Err(error) if missing_ok && error.kind() == std::io::ErrorKind::NotFound => Ok(None),
|
||||
Err(error) => Err(error.into()),
|
||||
}
|
||||
}
|
||||
|
||||
const MAX_BINARY_BYTES: u64 = 64 * 1024 * 1024;
|
||||
|
||||
fn read_workspace_bytes(root: &Path, rel: &str) -> WsResult<Vec<u8>> {
|
||||
let path = resolve_existing(root, rel)?;
|
||||
let file = fs::File::open(path)?;
|
||||
let metadata = file.metadata()?;
|
||||
if !metadata.is_file() { return Err(err("The path must be a file.")); }
|
||||
if metadata.len() > MAX_BINARY_BYTES { return Err(err("The file exceeds the 64 MiB limit.")); }
|
||||
let mut bytes = Vec::new();
|
||||
file.take(MAX_BINARY_BYTES + 1).read_to_end(&mut bytes)?;
|
||||
if bytes.len() as u64 > MAX_BINARY_BYTES { return Err(err("The file exceeds the 64 MiB limit.")); }
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn workspace_read_bytes(window: tauri::Window, state: State<'_, WorkspaceState>, rel: String) -> WsResult<tauri::ipc::Response> {
|
||||
let root = current_root(&state, window.label())?;
|
||||
let bytes = tauri::async_runtime::spawn_blocking(move || read_workspace_bytes(&root, &rel))
|
||||
.await.map_err(|e| err(e.to_string()))??;
|
||||
Ok(tauri::ipc::Response::new(bytes))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -590,7 +619,7 @@ fn is_internal_name(name: &str) -> bool {
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn workspace_create(window: tauri::Window, state: State<WorkspaceState>, rel: String, kind: String) -> WsResult<()> {
|
||||
pub fn workspace_create(window: tauri::Window, state: State<WorkspaceState>, rel: String, kind: String, contents: Option<String>) -> WsResult<()> {
|
||||
let root = current_root(&state, window.label())?;
|
||||
let path = resolve_for_write(&root, &rel)?;
|
||||
if path.exists() {
|
||||
@@ -598,6 +627,8 @@ pub fn workspace_create(window: tauri::Window, state: State<WorkspaceState>, rel
|
||||
}
|
||||
if kind == "folder" {
|
||||
fs::create_dir_all(&path)?;
|
||||
} else if let Some(contents) = contents {
|
||||
create_text_if_absent(&path, &contents)?;
|
||||
} else {
|
||||
if let Some(parent) = path.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
@@ -610,6 +641,24 @@ pub fn workspace_create(window: tauri::Window, state: State<WorkspaceState>, rel
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Publish a complete file without replacing a destination created by another writer.
|
||||
fn create_text_if_absent(path: &Path, contents: &str) -> WsResult<()> {
|
||||
static NEXT_CREATE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
let parent = path.parent().ok_or_else(|| err("file has no parent"))?;
|
||||
fs::create_dir_all(parent)?;
|
||||
let temp = parent.join(format!(".runestone-save-create-{}-{}", std::process::id(), NEXT_CREATE.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));
|
||||
let mut file = fs::OpenOptions::new().write(true).create_new(true).open(&temp)?;
|
||||
let result = (|| -> WsResult<()> {
|
||||
file.write_all(contents.as_bytes())?;
|
||||
file.sync_all()?;
|
||||
drop(file);
|
||||
fs::hard_link(&temp, path)?;
|
||||
Ok(())
|
||||
})();
|
||||
let _ = fs::remove_file(&temp);
|
||||
result
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn workspace_rename(window: tauri::Window, state: State<WorkspaceState>, from: String, to: String) -> WsResult<()> {
|
||||
let root = current_root(&state, window.label())?;
|
||||
@@ -887,6 +936,42 @@ mod tests {
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[test]
|
||||
fn binary_reads_preserve_bytes_and_enforce_workspace_and_size_limits() {
|
||||
let fixture = std::env::temp_dir().join(format!("rs-binary-{}", std::process::id()));
|
||||
let root = fixture.join("workspace");
|
||||
fs::create_dir_all(&root).unwrap();
|
||||
let root = dunce::canonicalize(root).unwrap();
|
||||
let bytes = b"%PDF-1.7\n\xff\x00\xfe";
|
||||
fs::write(root.join("test.pdf"), bytes).unwrap();
|
||||
fs::write(fixture.join("outside.pdf"), bytes).unwrap();
|
||||
assert_eq!(read_workspace_bytes(&root, "test.pdf").unwrap(), bytes);
|
||||
assert!(read_workspace_bytes(&root, "../outside.pdf").is_err());
|
||||
assert!(read_workspace_bytes(&root, &fixture.join("outside.pdf").to_string_lossy()).is_err());
|
||||
assert!(read_workspace_bytes(&root, "").is_err());
|
||||
assert!(read_workspace_bytes(&root, "missing.pdf").is_err());
|
||||
fs::File::create(root.join("large.pdf")).unwrap().set_len(MAX_BINARY_BYTES + 1).unwrap();
|
||||
assert!(read_workspace_bytes(&root, "large.pdf").unwrap_err().to_string().contains("64 MiB"));
|
||||
fs::remove_dir_all(fixture).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_files_publish_complete_text_without_overwriting() {
|
||||
let root = std::env::temp_dir().join(format!("rs-plugin-create-{}", std::process::id()));
|
||||
fs::create_dir_all(&root).unwrap();
|
||||
let path = root.join("note.md");
|
||||
assert_eq!(read_optional_text(&path, true).unwrap(), None);
|
||||
assert!(read_optional_text(&path, false).is_err());
|
||||
create_text_if_absent(&path, "complete note\n").unwrap();
|
||||
assert_eq!(read_optional_text(&path, true).unwrap().as_deref(), Some("complete note\n"));
|
||||
assert!(create_text_if_absent(&path, "replacement").is_err());
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "complete note\n");
|
||||
assert_eq!(fs::read_dir(&root).unwrap().count(), 1);
|
||||
assert!(read_optional_text(&root, true).is_err());
|
||||
fs::remove_file(path).unwrap();
|
||||
fs::remove_dir(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignore_files_do_not_hide_workspace_entries_or_search_results() {
|
||||
let fixture = std::env::temp_dir().join(format!("rs-ignore-rules-{}", std::process::id()));
|
||||
|
||||
Reference in New Issue
Block a user