Skip to content
Merged
53 changes: 44 additions & 9 deletions apps/hub/src-tauri/src/apps.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,15 +66,14 @@ pub(crate) fn activate_connected_menu_item(

#[cfg(windows)]
fn official_catalog(app: tauri::AppHandle) -> Result<Catalog, String> {
let text = match crate::catalog_cache::read_catalog_v3_cache(app.clone())? {
Some(text) => text,
None => match crate::catalog_cache::read_catalog_v2_cache(app.clone())? {
Some(text) => text,
None => crate::catalog_cache::read_catalog_cache(app)?
.ok_or_else(|| "nexo.appNoCatalog".to_string())?,
},
};
nexo_catalog::parse_catalog(&text).map_err(|error| error.to_string())
let text = crate::catalog_cache::read_catalog_v4_cache(app)?
.ok_or_else(|| "nexo.appNoCatalog".to_string())?;
let document = nexo_catalog::parse_catalog_v4(&text).map_err(|error| error.to_string())?;
let platform = crate::platform::platform_key();
Ok(nexo_catalog::project_catalog_v4(
&document,
platform.as_deref().unwrap_or(""),
))
}

#[cfg(windows)]
Expand Down Expand Up @@ -1069,6 +1068,42 @@ mod tests {
assert!(launcher.launched.borrow().is_empty());
}

#[test]
fn apps_without_a_platform_entry_cannot_be_matched_opened_or_detected() {
let document = nexo_catalog::parse_catalog_v4(include_str!(
"../../../../crates/nexo-catalog/fixtures/v4.json"
))
.unwrap();
let darwin = nexo_catalog::project_catalog_v4(&document, "darwin-aarch64");
let windows = nexo_catalog::project_catalog_v4(&document, "windows-x86_64");
let hidden = windows
.apps
.iter()
.find(|app| app.id == "windows-only")
.unwrap();
let registry = fake(Ok(vec![entry("physical-a")]));
let launcher = FakeLauncher::default();
assert!(
observe(&darwin, &registry)
.iter()
.all(|item| item.id != hidden.id)
);
assert!(
official_duplicates(&darwin, &registry, &launcher)
.iter()
.all(|item| item.id != hidden.id)
);
assert_eq!(
open_official(&darwin, &registry, &launcher, &hidden.id),
Err("nexo.appNotOfficial".into())
);
assert_eq!(
install_detection(&darwin, hidden, &registry),
crate::install_service::Detection::Unknown
);
assert!(launcher.launched.borrow().is_empty());
}

#[test]
fn official_open_still_refuses_a_local_executable_path_as_an_id() {
let registry = fake(Ok(vec![entry("physical-a")]));
Expand Down
105 changes: 28 additions & 77 deletions apps/hub/src-tauri/src/catalog_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,11 @@ use std::sync::atomic::{AtomicU64, Ordering};
use tauri::{AppHandle, Manager};

static NEXT_TEMP: AtomicU64 = AtomicU64::new(0);
const CACHE_NAME: &str = "catalog-v4.json";

fn cache_name(version: u64) -> Result<&'static str, String> {
match version {
1 => Ok("catalog.json"),
2 => Ok("catalog-v2.json"),
3 => Ok("catalog-v3.json"),
_ => Err("Unsupported catalog cache version".into()),
}
}

fn read_version(directory: &Path, version: u64) -> Result<Option<String>, String> {
match std::fs::read_to_string(directory.join(cache_name(version)?)) {
Ok(text)
if nexo_catalog::parse_catalog(&text)
.is_ok_and(|catalog| catalog.schema_version == version) =>
{
Ok(Some(text))
}
fn read_cache(directory: &Path) -> Result<Option<String>, String> {
match std::fs::read_to_string(directory.join(CACHE_NAME)) {
Ok(text) if nexo_catalog::parse_catalog_v4(&text).is_ok() => Ok(Some(text)),
Ok(_) => Ok(None),
Err(error) if matches!(error.kind(), ErrorKind::NotFound | ErrorKind::InvalidData) => {
Ok(None)
Expand All @@ -30,15 +17,8 @@ fn read_version(directory: &Path, version: u64) -> Result<Option<String>, String
}
}

fn read_cache(directory: &Path) -> Result<Option<String>, String> {
read_version(directory, 1)
}

fn write_cache(directory: &Path, input: &str) -> Result<(), String> {
let version = nexo_catalog::parse_catalog(input)
.map_err(|error| error.to_string())?
.schema_version;
let target = cache_name(version)?;
nexo_catalog::parse_catalog_v4(input).map_err(|error| error.to_string())?;
std::fs::create_dir_all(directory).map_err(|error| error.to_string())?;
let name = format!(
".catalog-{}-{}.tmp",
Expand All @@ -56,7 +36,7 @@ fn write_cache(directory: &Path, input: &str) -> Result<(), String> {
file.write_all(input.as_bytes())?;
file.sync_all()?;
drop(file);
std::fs::rename(&temporary, directory.join(target))
std::fs::rename(&temporary, directory.join(CACHE_NAME))
})();
if result.is_err() && created {
let _ = std::fs::remove_file(&temporary);
Expand All @@ -65,32 +45,14 @@ fn write_cache(directory: &Path, input: &str) -> Result<(), String> {
}

#[tauri::command]
pub(crate) fn read_catalog_cache(app: AppHandle) -> Result<Option<String>, String> {
pub(crate) fn read_catalog_v4_cache(app: AppHandle) -> Result<Option<String>, String> {
let directory = app
.path()
.app_data_dir()
.map_err(|error| error.to_string())?;
read_cache(&directory)
}

#[tauri::command]
pub(crate) fn read_catalog_v2_cache(app: AppHandle) -> Result<Option<String>, String> {
let directory = app
.path()
.app_data_dir()
.map_err(|error| error.to_string())?;
read_version(&directory, 2)
}

#[tauri::command]
pub(crate) fn read_catalog_v3_cache(app: AppHandle) -> Result<Option<String>, String> {
let directory = app
.path()
.app_data_dir()
.map_err(|error| error.to_string())?;
read_version(&directory, 3)
}

#[tauri::command]
pub(crate) fn write_catalog_cache(app: AppHandle, input: String) -> Result<(), String> {
let directory = app
Expand All @@ -106,8 +68,8 @@ mod tests {
use std::sync::atomic::{AtomicU64, Ordering};

static NEXT: AtomicU64 = AtomicU64::new(0);
const VALID: &str = include_str!("../../../../crates/nexo-catalog/fixtures/full.json");
const EMPTY: &str = "{\"schemaVersion\":1,\"apps\":[]}";
const VALID: &str = include_str!("../../../../crates/nexo-catalog/fixtures/v4.json");
const EMPTY: &str = "{\"schemaVersion\":4,\"apps\":[]}";

struct Scratch(std::path::PathBuf);
impl Scratch {
Expand Down Expand Up @@ -138,45 +100,34 @@ mod tests {
}

#[test]
fn rejected_document_never_replaces_valid_cache() {
fn v4_cache_rejects_v3_and_invalid_documents_without_replacing_valid_data() {
let dir = Scratch::new();
write_cache(&dir.0, VALID).unwrap();
for invalid in ["{", "{\"schemaVersion\":4,\"apps\":[]}"] {
assert_eq!(read_cache(&dir.0).unwrap().as_deref(), Some(VALID));
for invalid in [
"{",
"{\"schemaVersion\":1,\"apps\":[]}",
"{\"schemaVersion\":2,\"apps\":[]}",
"{\"schemaVersion\":3,\"apps\":[]}",
"{\"schemaVersion\":4,\"apps\":[{}]}",
] {
assert!(write_cache(&dir.0, invalid).is_err());
assert_eq!(read_cache(&dir.0).unwrap().as_deref(), Some(VALID));
assert_eq!(
std::fs::read_to_string(dir.0.join(CACHE_NAME)).unwrap(),
VALID
);
}
}

#[test]
fn v2_write_does_not_replace_the_v1_cache() {
let dir = Scratch::new();
write_cache(&dir.0, VALID).unwrap();
let v2 = "{\"schemaVersion\":2,\"apps\":[]}";
write_cache(&dir.0, v2).unwrap();
assert_eq!(read_cache(&dir.0).unwrap().as_deref(), Some(VALID));
assert_eq!(read_version(&dir.0, 2).unwrap().as_deref(), Some(v2));
assert!(write_cache(&dir.0, "{\"schemaVersion\":4,\"apps\":[]}").is_err());
assert_eq!(read_version(&dir.0, 2).unwrap().as_deref(), Some(v2));
}

#[test]
fn v3_cache_is_separate_and_invalid_writes_preserve_all_versions() {
fn old_cache_files_are_ignored_and_corrupt_v4_recovers() {
let dir = Scratch::new();
let v2 = "{\"schemaVersion\":2,\"apps\":[]}";
let v3 = "{\"schemaVersion\":3,\"apps\":[]}";
write_cache(&dir.0, VALID).unwrap();
write_cache(&dir.0, v2).unwrap();
write_cache(&dir.0, v3).unwrap();
assert!(write_cache(&dir.0, "{\"schemaVersion\":3,\"apps\":[{}]}").is_err());
assert_eq!(read_cache(&dir.0).unwrap().as_deref(), Some(VALID));
assert_eq!(read_version(&dir.0, 2).unwrap().as_deref(), Some(v2));
assert_eq!(read_version(&dir.0, 3).unwrap().as_deref(), Some(v3));
}

#[test]
fn corrupt_cache_is_ignored_and_a_later_valid_write_recovers() {
let dir = Scratch::new();
std::fs::write(dir.0.join("catalog.json"), "{broken").unwrap();
for name in ["catalog.json", "catalog-v2.json", "catalog-v3.json"] {
std::fs::write(dir.0.join(name), "{\"schemaVersion\":3,\"apps\":[]}").unwrap();
}
assert_eq!(read_cache(&dir.0).unwrap(), None);
std::fs::write(dir.0.join(CACHE_NAME), "{broken").unwrap();
assert_eq!(read_cache(&dir.0).unwrap(), None);
write_cache(&dir.0, EMPTY).unwrap();
assert_eq!(read_cache(&dir.0).unwrap().as_deref(), Some(EMPTY));
Expand Down
31 changes: 21 additions & 10 deletions apps/hub/src-tauri/src/install_feed.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! Native v3 catalog source for installation authorization.
//! Native v4 catalog source for installation authorization.
//!
//! This is not an authorization by itself. A transaction must obtain a new catalog at
//! the action boundary and another immediately before spawning, then revalidate its
Expand All @@ -8,7 +8,7 @@ use crate::install_download::{Body, Network, ResponseKind};
use nexo_catalog::{Catalog, CatalogApp};
use std::time::Duration;

pub const OFFICIAL_V3_FEED: &str = "https://egdev6.github.io/nexo-catalog/v3/catalog.json";
pub const OFFICIAL_V4_FEED: &str = "https://egdev6.github.io/nexo-catalog/v4/catalog.json";
pub const FEED_LIMIT: u64 = 2 * 1024 * 1024;
pub const FEED_TIMEOUT: Duration = Duration::from_secs(8);

Expand Down Expand Up @@ -57,7 +57,7 @@ impl FreshCatalog {
&self.catalog
}

/// Select by official ID only. Validated v3 entries without keys remain display-only.
/// Select by official ID only. Validated v4 entries without keys remain display-only.
pub fn select(&self, id: &str) -> Result<Selection, SelectionError> {
let app = self
.catalog
Expand Down Expand Up @@ -104,11 +104,23 @@ pub trait CatalogFeed: Sync {

pub struct NativeFeed<N> {
network: N,
platform: Option<String>,
}

impl<N> NativeFeed<N> {
pub fn new(network: N) -> Self {
Self { network }
Self {
network,
platform: crate::platform::platform_key(),
}
}

#[cfg(test)]
pub(crate) fn for_platform(network: N, platform: Option<&str>) -> Self {
Self {
network,
platform: platform.map(str::to_owned),
}
}
}

Expand All @@ -117,10 +129,10 @@ impl<N: Network> CatalogFeed for NativeFeed<N> {
let fetch = async {
let response = self
.network
.get(OFFICIAL_V3_FEED)
.get(OFFICIAL_V4_FEED)
.await
.map_err(|_| FeedError::Network)?;
if response.effective_url != OFFICIAL_V3_FEED {
if response.effective_url != OFFICIAL_V4_FEED {
return Err(FeedError::InvalidResponse);
}
let ResponseKind::Ok { length, mut body } = response.kind else {
Expand Down Expand Up @@ -149,11 +161,10 @@ impl<N: Network> CatalogFeed for NativeFeed<N> {
return Err(FeedError::LengthMismatch);
}
let text = std::str::from_utf8(&bytes).map_err(|_| FeedError::InvalidCatalog)?;
let document =
nexo_catalog::parse_catalog_v4(text).map_err(|_| FeedError::InvalidCatalog)?;
let catalog =
nexo_catalog::parse_catalog(text).map_err(|_| FeedError::InvalidCatalog)?;
if catalog.schema_version != 3 {
return Err(FeedError::InvalidCatalog);
}
nexo_catalog::project_catalog_v4(&document, self.platform.as_deref().unwrap_or(""));
Ok(FreshCatalog { catalog })
};
tokio::time::timeout(FEED_TIMEOUT, fetch)
Expand Down
Loading