diff --git a/.github/workflows/rust-core.yml b/.github/workflows/rust-core.yml index 335d9717..f9e88fb2 100644 --- a/.github/workflows/rust-core.yml +++ b/.github/workflows/rust-core.yml @@ -112,12 +112,15 @@ jobs: # Code behind cfg(windows) compiles only for Windows. Checking it here # finds its errors without a Windows runner; default features only, # because the remote server feature targets Unix hosts. Clippy only - # checks and never links, so SQLite (bundled for the Motty import) is - # told to link a system library instead of compiling its C source, - # which needs the MSVC tools that a Linux runner does not have. + # checks and never links, so the C dependencies use host pkg-config + # metadata instead of compiling for MSVC on a Linux runner. + - name: Install Windows lint metadata + run: sudo apt-get install -y libzstd-dev - name: Lint for Windows env: LIBSQLITE3_SYS_USE_PKG_CONFIG: "1" + ZSTD_SYS_USE_PKG_CONFIG: "1" + PKG_CONFIG_ALLOW_CROSS: "1" run: | read -ra packages <<< "$PACKAGES" cargo clippy --locked --manifest-path rust/Cargo.toml "${packages[@]}" --all-targets --target x86_64-pc-windows-msvc -- -D warnings diff --git a/rust/Cargo.lock b/rust/Cargo.lock index dd0737b2..1c19fe85 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -182,6 +182,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d262e149917187838d5b42777c8253bcb64500067342904e7d429499a6f277e" dependencies = [ "find-msvc-tools", + "jobserver", + "libc", "shlex", ] @@ -883,6 +885,16 @@ version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47f142fe24a9c9944451e8349de0a56af5f3e7226dc46f3ed4d4ecc0b85af75e" +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + [[package]] name = "js-sys" version = "0.3.104" @@ -1386,7 +1398,9 @@ dependencies = [ "lithe-protocol", "serde", "serde_json", + "sha2", "url", + "zstd", ] [[package]] @@ -3061,3 +3075,31 @@ dependencies = [ "log", "simd-adler32", ] + +[[package]] +name = "zstd" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50adf04cf3ec914b0b9905c9dde90c80fe74bfd701e331fc80a39c512c525278" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "7.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "498d94ad68720c89b4fbe41b9090850651e68cb2dd9210ce7ffbff3a94653819" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.1.3+zstd.1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f729a06d0257428fd9d997ac8db7e1407bd0262ab016b085b36bc52957c0052d" +dependencies = [ + "cc", + "pkg-config", +] diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 4df21a34..a4b1a877 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -526,6 +526,7 @@ or removing a command fails until the table changes in the same commit. | `plugins.editorActions.decode` | Validate independent action registration, collection or click results | | `plugins.hostApi.describe` | Describe backend host methods and their required grants from Core's method table | | `plugins.hostApi.authorize` | Check a method, service and current session grants using Core's capability rules; the host still checks session and resource ownership | +| `plugins.workflow` | Validate host workflow requests and project bounded inputs, pagination, and output | | `plugins.editorProviders.decode` | Validate editor provider registrations and provider function results | | `keymap.decodeImport` | Validate a normalized shortcut import against the host's action catalog | | `keymap.planImportSources` | Plan the selected provider's declared shortcut source inputs | @@ -600,6 +601,8 @@ or removing a command fails until the table changes in the same commit. | `project.extractArchive` | Extract a downloaded project archive into the staging directory, refusing unsafe entries | | `plugins.marketplace.validateIndex` | Validate a marketplace index and report each plugin's availability for one platform | | `plugins.marketplace.resolveSource` | Resolve a user-entered marketplace source to the index and companion recommendations URLs to fetch | +| `plugins.marketplace.selectDelta` | Select an exact-base delta from a marketplace companion | +| `plugins.marketplace.applyDelta` | Rebuild a marketplace ZIP in caller-owned private staging | | `plugins.marketplace.installReview` | List a package's permissions and programs, and those not yet approved | | `plugins.marketplace.recommendForWorkspace` | Match sampled workspace files against marketplace recommendation catalogs and indexes | | `workspace.snapshot` | Enumerate visible workspace nodes and relative file paths; `nestedWorktrees` lists linked worktrees checked out inside their own repository, which are left out of the tree, files, and search index; hidden folders, Core's own and the ones enabled plugins declare through `workspace.configureVisibility`, are skipped without being read; `includeTree: false` returns only `files` and a childless `root`; `files` (and the tree, when included) keep the lowercase traversal order that bounded consumers such as Windows Quick Open rely on, not the natural display order of `workspace.listDirectories` | @@ -5453,7 +5456,21 @@ See the plugin contract's [output link matchers](../../shared/plugins/contract/v1/README.md#output-link-matchers). -The `plugins.marketplace.*` commands are equally pure: hosts fetch indexes and +`resolveSource` also provides `deltasURL` beside the canonical and pinned +index URLs. `selectDelta` takes +`{index, pluginID, platform, repository, fromVersion, fromSHA256, toVersion, toSHA256, archiveURL}` +and returns `{status: "ok", patch}`, with `patch` set to null when the base and +target have no applicable delta. The index is the optional companion described +in the [plugin marketplace contract](../../shared/plugins/contract/v1/README.md#delta-archives). + +`applyDelta` takes `{patch, basePath, patchPath, outputPath}` and returns +`{status: "ok", applied: true}` after verifying the base, patch and rebuilt ZIP. +The paths are local and absolute. The output path must be absent in the caller's +private staging directory. The caller removes staging on error or cancellation. +A malformed or mismatched selection or reconstruction uses `plugin.delta.invalid`. +Both commands are desktop-only Core commands and are not callable by a plugin. + +Hosts fetch marketplace indexes and archives and pass the parsed JSON. `validateIndex` accepts `{ index, sourceKind: "official" | "thirdParty", platform, hostCapabilities? }` and returns `{ status: "ok", index: { plugins, rejected } }` with per-entry diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index c7f09d95..3d1bbc87 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -300,6 +300,10 @@ pub enum PluginsCommand { EditorProvidersDecode, /// Validates and filters a marketplace index (`plugins.marketplace.validateIndex`). MarketplaceValidateIndex, + /// Selects an optional, exact-base marketplace delta. + MarketplaceSelectDelta, + /// Rebuilds and verifies a marketplace ZIP in private staging. + MarketplaceApplyDelta, /// Resolves a user-entered marketplace source URL (`plugins.marketplace.resolveSource`). MarketplaceResolveSource, /// Lists a package's permissions and programs before installation (`plugins.marketplace.installReview`). @@ -1368,6 +1372,12 @@ impl CoreCommand { "plugins.marketplace.validateIndex" => { Some(Self::Plugins(PluginsCommand::MarketplaceValidateIndex)) } + "plugins.marketplace.selectDelta" => { + Some(Self::Plugins(PluginsCommand::MarketplaceSelectDelta)) + } + "plugins.marketplace.applyDelta" => { + Some(Self::Plugins(PluginsCommand::MarketplaceApplyDelta)) + } "plugins.marketplace.resolveSource" => { Some(Self::Plugins(PluginsCommand::MarketplaceResolveSource)) } diff --git a/rust/crates/core/src/runtime/dispatcher/plugins.rs b/rust/crates/core/src/runtime/dispatcher/plugins.rs index 3777eb0f..90aec708 100644 --- a/rust/crates/core/src/runtime/dispatcher/plugins.rs +++ b/rust/crates/core/src/runtime/dispatcher/plugins.rs @@ -169,6 +169,12 @@ pub(super) fn dispatch( payload, lithe_plugin_marketplace::validate_index_command, ), + PluginsCommand::MarketplaceSelectDelta => { + plugin_response(id, payload, lithe_plugin_marketplace::select_delta_command) + } + PluginsCommand::MarketplaceApplyDelta => { + plugin_response(id, payload, lithe_plugin_marketplace::apply_delta_command) + } PluginsCommand::MarketplaceResolveSource => plugin_response( id, payload, diff --git a/rust/crates/platform/src/scoped_read.rs b/rust/crates/platform/src/scoped_read.rs index 93a9aa98..2cf8b6fd 100644 --- a/rust/crates/platform/src/scoped_read.rs +++ b/rust/crates/platform/src/scoped_read.rs @@ -121,7 +121,7 @@ impl Directory { if matches!(component, std::path::Component::Prefix(_)) { continue; } - let handle = windows_open(&path, false)?; + let handle = windows_open(&path, WindowsOpen::Directory)?; let info = metadata(handle.metadata()?); if info.kind == Kind::Symlink { return Err(link_refused()); @@ -152,7 +152,7 @@ impl Directory { #[cfg(windows)] { let path = self.path.join(name); - let handle = windows_open(&path, false)?; + let handle = windows_open(&path, WindowsOpen::Directory)?; let info = metadata(handle.metadata()?); if info.kind == Kind::Symlink { return Err(link_refused()); @@ -174,7 +174,7 @@ impl Directory { #[cfg(unix)] let handle = unix_open(&self.handle, name, libc::O_NONBLOCK)?; #[cfg(windows)] - let handle = windows_open(&self.path.join(name), true)?; + let handle = windows_open(&self.path.join(name), WindowsOpen::File)?; let info = metadata(handle.metadata()?); if info.kind == Kind::Symlink { return Err(link_refused()); @@ -206,7 +206,7 @@ impl Directory { } #[cfg(windows)] { - windows_open(&self.path.join(name), false)? + windows_open(&self.path.join(name), WindowsOpen::Metadata)? .metadata() .map(metadata) } @@ -382,24 +382,33 @@ unsafe fn errno() -> *mut i32 { } #[cfg(windows)] -fn windows_open(path: &Path, read: bool) -> io::Result { +enum WindowsOpen { + Directory, + File, + Metadata, +} + +#[cfg(windows)] +fn windows_open(path: &Path, purpose: WindowsOpen) -> io::Result { use std::os::windows::fs::OpenOptionsExt; use windows_sys::Win32::Storage::FileSystem::{ FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_READ_ATTRIBUTES, - FILE_SHARE_READ, FILE_SHARE_WRITE, + FILE_SHARE_READ, FILE_SHARE_WRITE, FILE_TRAVERSE, }; let mut options = std::fs::OpenOptions::new(); - if read { - options.read(true); - } else { - options.access_mode(FILE_READ_ATTRIBUTES); + match purpose { + // Attribute-only handles do not enforce sharing. Traversal makes the + // directory's rename share restriction effective without listing it. + WindowsOpen::Directory => options + .access_mode(FILE_READ_ATTRIBUTES | FILE_TRAVERSE) + .share_mode(FILE_SHARE_READ), + WindowsOpen::File => options + .read(true) + .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE), + WindowsOpen::Metadata => options + .access_mode(FILE_READ_ATTRIBUTES) + .share_mode(FILE_SHARE_READ), } - options - .share_mode(if read { - FILE_SHARE_READ | FILE_SHARE_WRITE - } else { - FILE_SHARE_READ - }) - .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT) - .open(path) + .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT) + .open(path) } diff --git a/rust/crates/plugin-marketplace/Cargo.toml b/rust/crates/plugin-marketplace/Cargo.toml index c3a3c4f8..0bf6f0b0 100644 --- a/rust/crates/plugin-marketplace/Cargo.toml +++ b/rust/crates/plugin-marketplace/Cargo.toml @@ -12,3 +12,5 @@ lithe-protocol = { path = "../protocol" } serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0", features = ["preserve_order"] } url = "2.5" +sha2 = "0.10" +zstd = { version = "0.13", default-features = false } diff --git a/rust/crates/plugin-marketplace/src/delta.rs b/rust/crates/plugin-marketplace/src/delta.rs new file mode 100644 index 00000000..9a76039a --- /dev/null +++ b/rust/crates/plugin-marketplace/src/delta.rs @@ -0,0 +1,352 @@ +//! Selection and byte-exact reconstruction of marketplace ZIP deltas. +//! +//! The main index is authoritative for compatibility and the target hash. A +//! companion can only describe how to obtain those same bytes. The host owns +//! networking, cache admission and the private staging directory. + +use super::{is_platform, is_sha256, outcome, parse_repository, parse_version, release_asset_tag}; +use lithe_plugin_model::{decode_payload, is_plugin_id, PluginRejection, Validation}; +use lithe_protocol::{cancellation, CoreError}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; +use std::fs::{self, File}; +use std::io::{BufReader, Read, Seek, Write}; +use std::path::{Path, PathBuf}; + +const FORMAT: &str = "zstd-prefix"; +const SUFFIX: &str = ".zip.zst"; +const MAX_ZIP_BYTES: u64 = 64 << 20; +const MAX_WINDOW_LOG: u32 = 27; +const MAX_ENTRIES: usize = 20_000; +const CHUNK_BYTES: usize = 32 << 10; + +#[derive(Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Patch { + #[serde(rename = "pluginID")] + plugin_id: String, + platform: String, + from_version: String, + #[serde(rename = "fromSHA256")] + from_sha256: String, + to_version: String, + #[serde(rename = "toSHA256")] + to_sha256: String, + to_size: u64, + format: String, + #[serde(rename = "downloadURL")] + download_url: String, + sha256: String, + size: u64, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Index { + schema_version: u64, + patches: Vec, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Select { + index: Index, + #[serde(rename = "pluginID")] + plugin_id: String, + platform: String, + repository: String, + from_version: String, + #[serde(rename = "fromSHA256")] + from_sha256: String, + to_version: String, + #[serde(rename = "toSHA256")] + to_sha256: String, + #[serde(rename = "archiveURL")] + archive_url: String, +} + +fn invalid(message: impl Into) -> PluginRejection { + PluginRejection::new("plugin.delta.invalid", message) +} + +fn valid_sizes(patch: &Patch) -> bool { + patch.to_size > 0 + && patch.to_size <= MAX_ZIP_BYTES + && patch.size > 0 + && patch.size <= patch.to_size * 3 / 4 +} + +/// Returns a single supported patch for the exact approved base and selected target, +/// or `patch: null` when the companion has no applicable entry. +pub fn select_delta_command(payload: Value) -> Result { + let request: Select = decode_payload(payload, "plugins.marketplace.selectDelta")?; + Ok(outcome("patch", select(request))) +} + +fn select(request: Select) -> Validation { + if request.index.schema_version != 0 || request.index.patches.len() > MAX_ENTRIES { + return Err(invalid("Unsupported or oversized plugin delta index.")); + } + let Some(repository) = parse_repository(&request.repository) else { + return Err(invalid("The plugin repository is invalid.")); + }; + let tag = release_asset_tag(&request.archive_url, &repository, ".zip") + .ok_or_else(|| invalid("The target archive does not belong to the plugin release."))?; + let from = parse_version(&request.from_version); + let to = parse_version(&request.to_version); + if !matches!((from, to), (Some(from), Some(to)) if from < to) + || !is_plugin_id(&request.plugin_id) + || !is_platform(&request.platform) + || !is_sha256(&request.from_sha256) + || !is_sha256(&request.to_sha256) + { + return Err(invalid( + "The plugin delta request has invalid identity facts.", + )); + } + let mut selected = None; + for entry in request.index.patches { + if entry["pluginID"] != request.plugin_id + || entry["platform"] != request.platform + || entry["fromVersion"] != request.from_version + || entry["fromSHA256"] != request.from_sha256 + || entry["toVersion"] != request.to_version + || entry["toSHA256"] != request.to_sha256 + || entry["format"] != FORMAT + { + continue; + } + let patch: Patch = serde_json::from_value(entry) + .map_err(|_| invalid("The matching plugin delta entry is malformed."))?; + if !valid_sizes(&patch) + || !is_sha256(&patch.sha256) + || release_asset_tag(&patch.download_url, &repository, SUFFIX).as_deref() + != Some(tag.as_str()) + { + return Err(invalid("The matching plugin delta asset is invalid.")); + } + if selected.replace(patch).is_some() { + return Err(invalid("The plugin delta selection is ambiguous.")); + } + } + Ok(json!(selected)) +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Apply { + patch: Patch, + base_path: PathBuf, + patch_path: PathBuf, + output_path: PathBuf, +} + +/// Rebuilds a selected marketplace archive from the base and patch files, in a +/// fresh path in the host's private staging directory. If the command fails, +/// the caller owns deletion of the staging directory including any partial output. +pub fn apply_delta_command(payload: Value) -> Result { + let request: Apply = decode_payload(payload, "plugins.marketplace.applyDelta")?; + Ok(outcome("applied", apply(&request)?)) +} + +fn apply(request: &Apply) -> Result, CoreError> { + cancellation::check()?; + let patch = &request.patch; + if patch.format != FORMAT + || !valid_sizes(patch) + || ![&patch.from_sha256, &patch.to_sha256, &patch.sha256] + .iter() + .all(|digest| is_sha256(digest)) + || ![ + &request.base_path, + &request.patch_path, + &request.output_path, + ] + .iter() + .all(|path| path.is_absolute()) + { + return Ok(Err(invalid( + "The plugin delta application request is invalid.", + ))); + } + + // Keep the verified base snapshot in one bounded buffer. The patch is verified + // and decoded from the same file handle. The host owns its private staging. + let result = rebuild(request); + if let Err(error) = &result { + if let Some(interruption) = error + .get_ref() + .and_then(|cause| cause.downcast_ref::()) + { + return Err(interruption.0.clone()); + } + } + cancellation::check()?; + Ok(result + .map(|()| json!(true)) + .map_err(|error| invalid(error.to_string()))) +} + +fn regular_file(path: &Path) -> std::io::Result { + if !fs::symlink_metadata(path)?.file_type().is_file() { + return Err(std::io::Error::other( + "Expected a regular plugin delta file.", + )); + } + File::open(path) +} + +#[derive(Debug)] +struct Interrupted(CoreError); + +impl std::fmt::Display for Interrupted { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(&self.0.message) + } +} + +impl std::error::Error for Interrupted {} + +fn check_progress() -> std::io::Result<()> { + cancellation::check().map_err(|error| std::io::Error::other(Interrupted(error))) +} + +fn copy_verified( + mut source: R, + mut target: W, + limit: u64, + exact_size: Option, + expected: &str, +) -> std::io::Result<()> { + let mut hash = Sha256::new(); + let mut length = 0; + let mut buffer = [0; CHUNK_BYTES]; + loop { + check_progress()?; + let count = source.read(&mut buffer)?; + if count == 0 { + break; + } + length += count as u64; + if length > limit { + return Err(std::io::Error::other( + "Plugin delta file exceeds its size limit.", + )); + } + hash.update(&buffer[..count]); + target.write_all(&buffer[..count])?; + } + if exact_size.is_some_and(|size| size != length) || format!("{:x}", hash.finalize()) != expected + { + return Err(std::io::Error::other( + "Plugin delta length or SHA-256 does not match.", + )); + } + Ok(()) +} + +fn rebuild(request: &Apply) -> std::io::Result<()> { + let patch = &request.patch; + let base = regular_file(&request.base_path)?; + let size = base.metadata()?.len(); + if size == 0 || size > MAX_ZIP_BYTES { + return Err(std::io::Error::other( + "Plugin delta base exceeds its size limit.", + )); + } + let mut prefix = Vec::with_capacity(size as usize); + copy_verified( + base, + &mut prefix, + MAX_ZIP_BYTES, + Some(size), + &patch.from_sha256, + )?; + + let mut patch_file = regular_file(&request.patch_path)?; + copy_verified( + &mut patch_file, + std::io::sink(), + patch.size, + Some(patch.size), + &patch.sha256, + )?; + patch_file.rewind()?; + let mut delta = + zstd::stream::read::Decoder::with_ref_prefix(BufReader::new(patch_file), &prefix)?; + delta.window_log_max(MAX_WINDOW_LOG)?; + let mut output = File::create_new(&request.output_path)?; + copy_verified( + delta, + &mut output, + patch.to_size, + Some(patch.to_size), + &patch.to_sha256, + )?; + output.flush() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn request() -> Value { + let index: Value = serde_json::from_str(include_str!( + "../../../../shared/plugins/contract/v1/fixtures/marketplace/delta-index.json" + )) + .unwrap(); + json!({ + "pluginID": "io.example.delta", "platform": "darwin-arm64", + "repository": "https://github.com/example/delta", "fromVersion": "1.0.0", + "fromSHA256": "a".repeat(64), "toVersion": "1.1.0", "toSHA256": "b".repeat(64), + "archiveURL": "https://github.com/example/delta/releases/download/v1.1.0/delta-darwin-arm64.zip", + "index": index, + }) + } + + #[test] + fn delta_needs_exact_platform_and_digests() { + let body = request(); + let selected = select_delta_command(body.clone()).unwrap(); + assert_eq!(selected["patch"], body["index"]["patches"][0]); + for (key, value) in [ + ("platform", json!("windows-x64")), + ("fromSHA256", json!("f".repeat(64))), + ("toSHA256", json!("f".repeat(64))), + ] { + let mut different = body.clone(); + different[key] = value; + assert_eq!( + select_delta_command(different).unwrap(), + json!({ "status": "ok", "patch": null }) + ); + } + } + + #[test] + fn delta_refuses_wrong_release_oversize_and_duplicate_entries() { + let body = request(); + for (field, value) in [ + ( + "downloadURL", + json!("https://github.com/other/delta/releases/download/v1.1.0/file.zip.zst"), + ), + ( + "downloadURL", + json!("https://github.com/example/delta/releases/download/v1.0.0/file.zip.zst"), + ), + ("size", json!(4096)), + ] { + let mut invalid = body.clone(); + invalid["index"]["patches"][0][field] = value; + let reply = select_delta_command(invalid).unwrap(); + assert_eq!(reply["error"]["code"], "plugin.delta.invalid"); + } + let mut duplicate = body; + let patches = duplicate["index"]["patches"].as_array_mut().unwrap(); + patches.push(patches[0].clone()); + let reply = select_delta_command(duplicate).unwrap(); + assert_eq!(reply["error"]["code"], "plugin.delta.invalid"); + } +} diff --git a/rust/crates/plugin-marketplace/src/lib.rs b/rust/crates/plugin-marketplace/src/lib.rs index 5a05b8e8..681ca204 100644 --- a/rust/crates/plugin-marketplace/src/lib.rs +++ b/rust/crates/plugin-marketplace/src/lib.rs @@ -8,6 +8,10 @@ //! start, so macOS and Windows present the same catalog and the same trust //! prompts. The contract lives in `shared/plugins/contract/v1/`. +mod delta; + +pub use delta::{apply_delta_command, select_delta_command}; + use lithe_plugin_manifest::{validate_manifest_value, SUPPORTED_PLUGIN_API_VERSIONS}; use lithe_plugin_model::capabilities::{self, HostCapabilities, Requires}; use lithe_plugin_model::{ @@ -28,6 +32,7 @@ pub const MARKETPLACE_RECOMMENDATIONS_SCHEMA_VERSION: u64 = 0; pub const REPOSITORY_INDEX_FILE_NAME: &str = "lithe-plugin-index.json"; /// Companion workspace-recommendation file resolved beside a marketplace index. pub const REPOSITORY_RECOMMENDATIONS_FILE_NAME: &str = "lithe-plugin-recommendations.json"; +const DELTAS_FILE_NAME: &str = "lithe-plugin-deltas.json"; /// Platforms with a Lithe host today. Other well-formed identifiers are /// accepted so an index can list future platforms without breaking older /// hosts; they simply never match. @@ -552,7 +557,8 @@ fn resolve_source(input: &str, commit: Option<&str>) -> Validation { ( json!({ "indexURL": index_url, - "recommendationsURL": sibling_recommendations_url(&index_url), + "recommendationsURL": sibling_url(&index_url, REPOSITORY_RECOMMENDATIONS_FILE_NAME), + "deltasURL": sibling_url(&index_url, DELTAS_FILE_NAME), "repository": repository.web_url(), "displayName": format!("{}/{}", repository.owner, repository.name), }), @@ -574,7 +580,8 @@ fn resolve_source(input: &str, commit: Option<&str>) -> Validation { ( json!({ "indexURL": index_url.as_str(), - "recommendationsURL": sibling_recommendations_url(index_url.as_str()), + "recommendationsURL": sibling_url(index_url.as_str(), REPOSITORY_RECOMMENDATIONS_FILE_NAME), + "deltasURL": if index_url.query().is_none() { sibling_url(index_url.as_str(), DELTAS_FILE_NAME) } else { String::new() }, "repository": repository.as_ref().map(GitHubRepository::web_url), "displayName": repository .map(|repository| format!("{}/{}", repository.owner, repository.name)) @@ -597,7 +604,8 @@ fn resolve_source(input: &str, commit: Option<&str>) -> Validation { ); json!({ "commit": commit, - "recommendationsURL": sibling_recommendations_url(&index_url), + "recommendationsURL": sibling_url(&index_url, REPOSITORY_RECOMMENDATIONS_FILE_NAME), + "deltasURL": sibling_url(&index_url, DELTAS_FILE_NAME), "indexURL": index_url, }) }); @@ -643,9 +651,8 @@ fn is_object_name(value: &str) -> bool { matches!(value.len(), 40 | 64) && value.bytes().all(|byte| byte.is_ascii_hexdigit()) } -/// Derives the companion `lithe-plugin-recommendations.json` URL in the same -/// directory as a validated `indexURL`, dropping any query or fragment. -fn sibling_recommendations_url(index_url: &str) -> String { +/// Resolves a companion in a validated index's directory, without the index query or fragment. +fn sibling_url(index_url: &str, name: &str) -> String { let Ok(mut url) = Url::parse(index_url) else { return String::new(); }; @@ -654,7 +661,7 @@ fn sibling_recommendations_url(index_url: &str) -> String { if let Ok(mut segments) = url.path_segments_mut() { segments.pop_if_empty(); segments.pop(); - segments.push(REPOSITORY_RECOMMENDATIONS_FILE_NAME); + segments.push(name); } url.to_string() } @@ -797,29 +804,28 @@ fn parse_repository(value: &str) -> Option { /// of exactly the entry's repository, so an index cannot point a plugin at /// another project's release. fn is_release_asset(value: &str, repository: &GitHubRepository) -> bool { - let Some(url) = parse_https(value) else { - return false; - }; + release_asset_tag(value, repository, ".zip").is_some() +} + +fn release_asset_tag(value: &str, repository: &GitHubRepository, suffix: &str) -> Option { + let url = parse_https(value)?; if !url .host_str() .is_some_and(|host| host.eq_ignore_ascii_case("github.com")) || url.query().is_some() || url.fragment().is_some() { - return false; + return None; } - let Some(segments) = url.path_segments().map(Iterator::collect::>) else { - return false; - }; + let segments: Vec<_> = url.path_segments()?.collect(); match segments.as_slice() { - [owner, name, "releases", "download", tag, asset] => { - repository_from_parts(owner, name) - .is_some_and(|candidate| candidate.same_as(repository)) - && is_path_component(tag) - && is_path_component(asset) - && asset.to_ascii_lowercase().ends_with(".zip") - } - _ => false, + [owner, name, "releases", "download", tag, asset] => (repository_from_parts(owner, name) + .is_some_and(|candidate| candidate.same_as(repository)) + && is_path_component(tag) + && is_path_component(asset) + && asset.to_ascii_lowercase().ends_with(suffix)) + .then(|| (*tag).to_owned()), + _ => None, } } diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 747df9ee..a2d42fe8 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -1889,6 +1889,28 @@ plugins and their release archives. Hosts fetch, cache, and download; Rust Core decides validity and availability through `plugins.marketplace.*` so every product shows the same catalog and the same install review. +### Delta archives + +A marketplace can publish [`lithe-plugin-deltas.json`](plugin-delta-index.schema.json) +beside its version-0 index. The main index remains authoritative for version, +host compatibility, permissions review and the full archive digest. GitHub +companions use the commit that supplied the main index. A source containing a +query has no delta companion, so private link credentials need not travel to it. + +A `zstd-prefix` entry transforms the exact base ZIP into the target ZIP. The +publisher creates it with Zstandard `--patch-from=OLD.zip`. The asset must end +in `.zip.zst` and belong to the same GitHub Release as the target archive. The +base and target must refer to the same plugin and platform, with a strictly newer +target. An entry binds both archive SHA-256 digests, target byte size, patch URL, +patch SHA-256 and patch byte size. ZIPs up to 64 MiB and patches up to 75% of the +target byte count are eligible. The decoder allows a 128 MiB maximum window. + +The host uses a cached base only from the installed version's approved source. +Missing, unsupported or invalid deltas lead to ordinary full downloads. +Cancellation ends the operation. The host verifies the target ZIP through the +same installation path regardless of how it obtained the archive. A delta +grants no extra permission or right to change marketplace source. + ### Sources - The host ships one **official** source: the index at diff --git a/shared/plugins/contract/v1/fixtures/marketplace/delta-index.json b/shared/plugins/contract/v1/fixtures/marketplace/delta-index.json new file mode 100644 index 00000000..19c4f914 --- /dev/null +++ b/shared/plugins/contract/v1/fixtures/marketplace/delta-index.json @@ -0,0 +1,18 @@ +{ + "schemaVersion": 0, + "patches": [ + { + "pluginID": "io.example.delta", + "platform": "darwin-arm64", + "fromVersion": "1.0.0", + "fromSHA256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "toVersion": "1.1.0", + "toSHA256": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "toSize": 4096, + "format": "zstd-prefix", + "downloadURL": "https://github.com/example/delta/releases/download/v1.1.0/delta-darwin-arm64.from-1.0.0.zip.zst", + "sha256": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "size": 124 + } + ] +} diff --git a/shared/plugins/contract/v1/fixtures/marketplace/source-urls.json b/shared/plugins/contract/v1/fixtures/marketplace/source-urls.json index 5e09ad67..7739c07a 100644 --- a/shared/plugins/contract/v1/fixtures/marketplace/source-urls.json +++ b/shared/plugins/contract/v1/fixtures/marketplace/source-urls.json @@ -1,17 +1,17 @@ { "schemaVersion": 1, - "description": "plugins.marketplace.resolveSource inputs and the index and companion recommendations URLs every host must fetch, the GitHub repository and ref a host may look the newest commit of, the same files pinned at a commit the host passes back, or the rejection code.", + "description": "plugins.marketplace.resolveSource inputs and the index and companion recommendations and delta URLs every host must fetch, the GitHub repository and ref a host may look the newest commit of, the same files pinned at a commit the host passes back, or the rejection code.", "cases": [ - {"input": "https://github.com/example/lithe-plugins", "expected": {"indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-recommendations.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins", "revision": {"repository": {"owner": "example", "name": "lithe-plugins"}, "ref": "HEAD"}}}, - {"input": " https://github.com/example/lithe-plugins.git/ ", "expected": {"indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-recommendations.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins", "revision": {"repository": {"owner": "example", "name": "lithe-plugins"}, "ref": "HEAD"}}}, - {"input": "https://github.com/example/lithe-plugins/blob/release/v1/indexes/lithe-plugin-index.json", "expected": {"indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/release/v1/indexes/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/release/v1/indexes/lithe-plugin-recommendations.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins", "revision": {"repository": {"owner": "example", "name": "lithe-plugins"}, "ref": "release"}}}, - {"input": "https://raw.githubusercontent.com/example/lithe-plugins/main/lithe-plugin-index.json", "expected": {"indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/main/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/main/lithe-plugin-recommendations.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins", "revision": {"repository": {"owner": "example", "name": "lithe-plugins"}, "ref": "main"}}}, - {"input": "https://plugins.example.com/lithe/index.json#latest", "expected": {"indexURL": "https://plugins.example.com/lithe/index.json", "recommendationsURL": "https://plugins.example.com/lithe/lithe-plugin-recommendations.json", "repository": null, "displayName": "plugins.example.com", "revision": null}}, - {"input": "https://github.com/example/lithe-plugins", "commit": "0123456789ABCDEF0123456789ABCDEF01234567", "expected": {"indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-recommendations.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins", "revision": {"repository": {"owner": "example", "name": "lithe-plugins"}, "ref": "HEAD"}, "pinned": {"commit": "0123456789abcdef0123456789abcdef01234567", "indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/0123456789abcdef0123456789abcdef01234567/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/0123456789abcdef0123456789abcdef01234567/lithe-plugin-recommendations.json"}}}, - {"input": "https://raw.githubusercontent.com/example/lithe-plugins/refs/heads/release/v1/indexes/lithe-plugin-index.json", "commit": "0123456789abcdef0123456789abcdef01234567", "expected": {"indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/refs/heads/release/v1/indexes/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/refs/heads/release/v1/indexes/lithe-plugin-recommendations.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins", "revision": {"repository": {"owner": "example", "name": "lithe-plugins"}, "ref": "refs/heads/release"}, "pinned": {"commit": "0123456789abcdef0123456789abcdef01234567", "indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/0123456789abcdef0123456789abcdef01234567/v1/indexes/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/0123456789abcdef0123456789abcdef01234567/v1/indexes/lithe-plugin-recommendations.json"}}}, - {"input": "https://raw.githubusercontent.com/example/lithe-plugins/0123456789abcdef0123456789abcdef01234567/lithe-plugin-index.json", "commit": "0123456789abcdef0123456789abcdef01234567", "expected": {"indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/0123456789abcdef0123456789abcdef01234567/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/0123456789abcdef0123456789abcdef01234567/lithe-plugin-recommendations.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins", "revision": null, "pinned": null}}, - {"input": "https://raw.githubusercontent.com/example/lithe-plugins/main/lithe-plugin-index.json?token=abc", "commit": "0123456789abcdef0123456789abcdef01234567", "expected": {"indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/main/lithe-plugin-index.json?token=abc", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/main/lithe-plugin-recommendations.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins", "revision": null, "pinned": null}}, - {"input": "https://plugins.example.com/lithe/index.json", "commit": "0123456789abcdef0123456789abcdef01234567", "expected": {"indexURL": "https://plugins.example.com/lithe/index.json", "recommendationsURL": "https://plugins.example.com/lithe/lithe-plugin-recommendations.json", "repository": null, "displayName": "plugins.example.com", "revision": null, "pinned": null}}, + {"input": "https://github.com/example/lithe-plugins", "expected": {"indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-recommendations.json", "deltasURL": "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-deltas.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins", "revision": {"repository": {"owner": "example", "name": "lithe-plugins"}, "ref": "HEAD"}}}, + {"input": " https://github.com/example/lithe-plugins.git/ ", "expected": {"indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-recommendations.json", "deltasURL": "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-deltas.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins", "revision": {"repository": {"owner": "example", "name": "lithe-plugins"}, "ref": "HEAD"}}}, + {"input": "https://github.com/example/lithe-plugins/blob/release/v1/indexes/lithe-plugin-index.json", "expected": {"indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/release/v1/indexes/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/release/v1/indexes/lithe-plugin-recommendations.json", "deltasURL": "https://raw.githubusercontent.com/example/lithe-plugins/release/v1/indexes/lithe-plugin-deltas.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins", "revision": {"repository": {"owner": "example", "name": "lithe-plugins"}, "ref": "release"}}}, + {"input": "https://raw.githubusercontent.com/example/lithe-plugins/main/lithe-plugin-index.json", "expected": {"indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/main/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/main/lithe-plugin-recommendations.json", "deltasURL": "https://raw.githubusercontent.com/example/lithe-plugins/main/lithe-plugin-deltas.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins", "revision": {"repository": {"owner": "example", "name": "lithe-plugins"}, "ref": "main"}}}, + {"input": "https://plugins.example.com/lithe/index.json#latest", "expected": {"indexURL": "https://plugins.example.com/lithe/index.json", "recommendationsURL": "https://plugins.example.com/lithe/lithe-plugin-recommendations.json", "deltasURL": "https://plugins.example.com/lithe/lithe-plugin-deltas.json", "repository": null, "displayName": "plugins.example.com", "revision": null}}, + {"input": "https://github.com/example/lithe-plugins", "commit": "0123456789ABCDEF0123456789ABCDEF01234567", "expected": {"indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-recommendations.json", "deltasURL": "https://raw.githubusercontent.com/example/lithe-plugins/HEAD/lithe-plugin-deltas.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins", "revision": {"repository": {"owner": "example", "name": "lithe-plugins"}, "ref": "HEAD"}, "pinned": {"commit": "0123456789abcdef0123456789abcdef01234567", "indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/0123456789abcdef0123456789abcdef01234567/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/0123456789abcdef0123456789abcdef01234567/lithe-plugin-recommendations.json", "deltasURL": "https://raw.githubusercontent.com/example/lithe-plugins/0123456789abcdef0123456789abcdef01234567/lithe-plugin-deltas.json"}}}, + {"input": "https://raw.githubusercontent.com/example/lithe-plugins/refs/heads/release/v1/indexes/lithe-plugin-index.json", "commit": "0123456789abcdef0123456789abcdef01234567", "expected": {"indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/refs/heads/release/v1/indexes/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/refs/heads/release/v1/indexes/lithe-plugin-recommendations.json", "deltasURL": "https://raw.githubusercontent.com/example/lithe-plugins/refs/heads/release/v1/indexes/lithe-plugin-deltas.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins", "revision": {"repository": {"owner": "example", "name": "lithe-plugins"}, "ref": "refs/heads/release"}, "pinned": {"commit": "0123456789abcdef0123456789abcdef01234567", "indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/0123456789abcdef0123456789abcdef01234567/v1/indexes/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/0123456789abcdef0123456789abcdef01234567/v1/indexes/lithe-plugin-recommendations.json", "deltasURL": "https://raw.githubusercontent.com/example/lithe-plugins/0123456789abcdef0123456789abcdef01234567/v1/indexes/lithe-plugin-deltas.json"}}}, + {"input": "https://raw.githubusercontent.com/example/lithe-plugins/0123456789abcdef0123456789abcdef01234567/lithe-plugin-index.json", "commit": "0123456789abcdef0123456789abcdef01234567", "expected": {"indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/0123456789abcdef0123456789abcdef01234567/lithe-plugin-index.json", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/0123456789abcdef0123456789abcdef01234567/lithe-plugin-recommendations.json", "deltasURL": "https://raw.githubusercontent.com/example/lithe-plugins/0123456789abcdef0123456789abcdef01234567/lithe-plugin-deltas.json", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins", "revision": null, "pinned": null}}, + {"input": "https://raw.githubusercontent.com/example/lithe-plugins/main/lithe-plugin-index.json?token=abc", "commit": "0123456789abcdef0123456789abcdef01234567", "expected": {"indexURL": "https://raw.githubusercontent.com/example/lithe-plugins/main/lithe-plugin-index.json?token=abc", "recommendationsURL": "https://raw.githubusercontent.com/example/lithe-plugins/main/lithe-plugin-recommendations.json", "deltasURL": "", "repository": "https://github.com/example/lithe-plugins", "displayName": "example/lithe-plugins", "revision": null, "pinned": null}}, + {"input": "https://plugins.example.com/lithe/index.json", "commit": "0123456789abcdef0123456789abcdef01234567", "expected": {"indexURL": "https://plugins.example.com/lithe/index.json", "recommendationsURL": "https://plugins.example.com/lithe/lithe-plugin-recommendations.json", "deltasURL": "https://plugins.example.com/lithe/lithe-plugin-deltas.json", "repository": null, "displayName": "plugins.example.com", "revision": null, "pinned": null}}, {"input": "http://plugins.example.com/index.json", "expectedCode": "plugin.source.invalid"}, {"input": "https://token@github.com/example/lithe-plugins", "expectedCode": "plugin.source.invalid"}, {"input": "https://github.com/example", "expectedCode": "plugin.source.invalid"}, diff --git a/shared/plugins/contract/v1/plugin-delta-index.schema.json b/shared/plugins/contract/v1/plugin-delta-index.schema.json new file mode 100644 index 00000000..2dc457ed --- /dev/null +++ b/shared/plugins/contract/v1/plugin-delta-index.schema.json @@ -0,0 +1,34 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://raw.githubusercontent.com/Lithe-IDEA/Lithe-core-rust/main/shared/plugins/contract/v1/plugin-delta-index.schema.json", + "title": "Lithe plugin marketplace delta index", + "type": "object", + "additionalProperties": false, + "required": ["schemaVersion", "patches"], + "properties": { + "schemaVersion": { "const": 0 }, + "patches": { "type": "array", "maxItems": 20000, "items": { "$ref": "#/$defs/patch" } } + }, + "$defs": { + "sha256": { "type": "string", "pattern": "^[0-9a-f]{64}$" }, + "version": { "type": "string", "pattern": "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)$" }, + "patch": { + "type": "object", + "additionalProperties": false, + "required": ["pluginID", "platform", "fromVersion", "fromSHA256", "toVersion", "toSHA256", "toSize", "format", "downloadURL", "sha256", "size"], + "properties": { + "pluginID": { "type": "string", "pattern": "^[a-z0-9.-]+$" }, + "platform": { "type": "string", "pattern": "^[a-z0-9]+-[a-z0-9]+$" }, + "fromVersion": { "$ref": "#/$defs/version" }, + "fromSHA256": { "$ref": "#/$defs/sha256" }, + "toVersion": { "$ref": "#/$defs/version" }, + "toSHA256": { "$ref": "#/$defs/sha256" }, + "toSize": { "type": "integer", "minimum": 1, "maximum": 67108864 }, + "format": { "const": "zstd-prefix" }, + "downloadURL": { "type": "string", "format": "uri", "pattern": "^https://github\\.com/" }, + "sha256": { "$ref": "#/$defs/sha256" }, + "size": { "type": "integer", "minimum": 1, "maximum": 50331648 } + } + } + } +} diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index e573c6b2..d2bebb63 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -22,6 +22,7 @@ - [#190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190),[@xiaoyumuxi](https://github.com/xiaoyumuxi)(API-06,`pluginAPIVersion` 0 内补充):Core 新增 `workspace.readDirectory`、`workspace.stat`、`workspace.readFile` 三个执行命令;宿主方法保持原名和权限。路由前严格校验上下文、资源、未知字段与分页/读取上限。补齐 no-follow、Windows reparse point、稳定有界分页、磁盘 UTF-8/base64 和截断前缀 identity 的公开行为及共享 fixture;Node SDK 同步明确前缀 identity 类型与可空修改时间;其他 SDK 保留通用 JSON 返回值。没有新增协议版本、方法或通知。合入日期在合并时补齐。 - [#188](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/188),[@mirakyux](https://github.com/mirakyux),`pluginAPIVersion` 0 内补充(API-25):`editor/registerProviders` 新增 `colorDecorations`,注册普通后端函数和最多 64 个有稳定 ID 的明暗 `#RRGGBB` 颜色;结果为 UTF-16 单行范围与颜色 ID。Core 拒绝单源重叠、空范围、未知颜色 ID 和超限结果,并用 `plugins.editorProviders.decode` 的 `kind: "mergeColorDecorations"` 按 `/` 字典序合并,较早来源优先且裁切后续范围。没有新增宿主方法、通知、能力版本或 SDK 包装。 +- [#187](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/187),[@Mucheen](https://github.com/Mucheen),插件市场增量索引 `schemaVersion` **0**(—)。主索引格式不变,`resolveSource` 额外提供 `deltasURL`,新增桌面 Core 命令 `selectDelta` 和 `applyDelta`。增量补丁重建市场已记录摘要的完整 ZIP,继续使用既有安装审查。 - [#182](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/182)(关联 [1lck/Lithe-IDEA#2260](https://github.com/1lck/Lithe-IDEA/issues/2260)),`lithe-support[bot]`,**`toolchainProviders` 1 / `litheToolchains` 1**(API-23):权限和 authority 错误改用 `-32082`、`-32083`,稳定字符串码不变。Core 按重新校验的清单版本解码;版本 0 保留 `-32070`、`-32071`,不同版本的号码互不接受。Rust SDK 保留版本 0 默认语义,通过 `Backend::toolchain_provider_version(ToolchainProviderVersion::V1)` 显式选择新版本;没有匹配的协商版本就不启用提供者。四个 SDK 的 `plugin.function.*` 号码不变。 - [#184](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/184),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`pluginAPIVersion` 0 内的补充(API-11):`workspace/create` 的 `kind` 新增 `symlink`,配合新字段 `linkTarget`(1–4096 字节,不含 NUL)新建符号链接。链接原样保存目标,可以是绝对路径,也可以相对链接所在目录,可以指向根目录外或不存在的路径;新建链接不放宽任何检查,`workspace/readFile`、列表和 `editor/open` 仍做根目录检查,也不能穿过离开根目录的父目录新建任何东西;Windows 上目标里的 `/` 存成 `\`,目标是已存在的目录就建目录链接,否则建文件链接,系统拒绝建链接时返回 `failed`。API-11 七个方法的参数改为在路由前严格检查:`resource`、`target` 只能是 `{rootID,path}`,路径只有一种写法(`/` 分隔,没有空段、`.`、`..`,最长 4096 字节,Windows 上不能原样保存的名字也拒绝),移动的目标在同一根目录且不在源之内,`create` 的字段必须和 `kind` 一致,否则返回 `invalidParams`。fixture `backend/function-protocol.json` 新增 3 个用例,四个官方 SDK 的 `create` 注释写明 `symlink`,Node 类型按 `kind` 分成三种参数形状。Rust Core 新增内核命令 `workspace.createEntry`、`renameEntry`、`copyEntry`、`resolveEntry` 和错误码 `entry_not_found`、`entry_exists`,路径解析、不覆盖的重命名、符号链接和复制都在 Core 里完成,宿主只负责文档、视图和系统废纸篓。桌面端接入见 [1lck/Lithe-IDEA#2358](https://github.com/1lck/Lithe-IDEA/pull/2358)。没有新增能力版本、宿主方法、通知或 SDK 版本。 - [#183](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/183),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`pluginAPIVersion` 0 内的补充(API-11):新增宿主方法 `documents/save`、`documents/saveAs`、`documents/close`(新权限 `documents.save`)和 `workspace/create`、`workspace/rename`、`workspace/copy`、`workspace/trash`(新权限 `workspace.files.write`)。每个权限只授予自己的方法,原有权限(包括聚合的 `workspace` 授权和 `documents.read`)都不授予它们。宿主经文档所有者保存,保留版本、撤销记录和语言会话;`close` 先保存再关闭,从不丢弃修改;`saveAs`、`create`、`rename`、`copy` 的目标已存在时失败,从不覆盖;`trash` 只移到系统废纸篓,没有永久删除;`rename`、`trash` 先保存其下打开的文档,保存失败就不动。这些方法不弹询问:需要用户选择的情形(未命名文档、硬链接文件、文件在磁盘上已改变)直接拒绝。新增失败码 `plugin.host.alreadyExists`(`-32080`,目标已存在)和 `plugin.host.diskChanged`(`-32081`,文件在磁盘上被改动或删除,没有写入)。清单 schema 的权限枚举加上两个新权限,fixture `backend/function-protocol.json` 新增 4 个宿主请求用例和 2 个失败码用例,`rust/fixtures/plugins/host-api-v1.json` 新增 4 个授权用例。四个官方 SDK 新增 7 个方法的封装和两个失败码。桌面端实现见 [1lck/Lithe-IDEA#2358](https://github.com/1lck/Lithe-IDEA/pull/2358)。没有新增能力版本、通知或 SDK 版本。 @@ -51,6 +52,7 @@ | `litheSettingsSources`、`litheSettingsSourceEdit` | 0 | 2026-11-15 | [#57](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/57) | | 市场推荐索引 `schemaVersion` | 0 | 2026-11-20 | [#130](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/130) | +| 市场增量索引 `schemaVersion` | 0 | 待合入 | [#187](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/187) | ### 能力版本(`requires`) diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/host.rs b/shared/plugins/sdk/rust/plugin-sdk/src/host.rs index 10513127..5b19ebab 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/host.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/host.rs @@ -1511,109 +1511,6 @@ fn relay_params(call: Value, serving: Option<&str>) -> Result { Ok(Value::Object(relayed)) } -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn contexts_are_references_or_full_contexts() { - let full = json!({ "contextID": "w1", "generation": 2, "name": "orders" }); - let context = WorkspaceContext::from_value(&full).unwrap(); - assert_eq!( - context.to_value(), - json!({ "contextID": "w1", "generation": 2 }) - ); - assert_eq!(WorkspaceContext::new("w1", 2).unwrap(), context); - // An invocation's context is exactly a reference. - assert_eq!(WorkspaceContext::from_reference(&full), None); - assert_eq!( - WorkspaceContext::from_reference(&context.to_value()), - Some(context) - ); - for invalid in [ - json!({ "contextID": "w1" }), - json!({ "contextID": "w1", "generation": 0 }), - json!({ "contextID": "../w", "generation": 1 }), - json!(null), - ] { - let error = WorkspaceContext::from_value(&invalid).unwrap_err(); - assert_eq!(error.code(), "sdk.host.invalidContext", "{invalid}"); - } - assert!(WorkspaceContext::new("", 1).is_err()); - } - - #[test] - fn a_relayed_call_keeps_only_the_fields_the_method_defines() { - let call = json!({ - "pluginID": "dev.lithe.fixture.java", "functionID": "project.describe", - "params": { "caller": "data" }, "timeoutMilliseconds": 900000, - "parentOperationID": "17", "caller": { "pluginID": "forged" }, - "context": { "contextID": "x" }, "extra": true - }); - let expected = json!({ - "pluginID": "dev.lithe.fixture.java", "functionID": "project.describe", - "params": { "caller": "data" }, "timeoutMilliseconds": 900000, - "parentOperationID": "17" - }); - // Core passes a `caller` inside `params` unchanged; only a top-level one is refused. - assert_eq!(relay_params(call, Some("served")).unwrap(), expected); - } - - #[test] - fn optional_fields_stay_out_and_the_parent_defaults_to_the_call_being_served() { - let call = json!({ "pluginID": "a.b", "functionID": "x.y" }); - assert_eq!(relay_params(call.clone(), None).unwrap(), call); - let served = relay_params(call, Some("op-7")).unwrap(); - assert_eq!(served["parentOperationID"], "op-7"); - assert!(served.get("params").is_none()); - assert!(served.get("timeoutMilliseconds").is_none()); - let named = json!({ "pluginID": "a.b", "functionID": "x.y", "parentOperationID": "own" }); - let relayed = relay_params(named, Some("op-7")).unwrap(); - assert_eq!(relayed["parentOperationID"], "own"); - // The host caps the timeout; the SDK sends what the plugin chose. - let mut slow = json!({ "pluginID": "a.b", "functionID": "x.y" }); - slow["timeoutMilliseconds"] = json!(700000); - let relayed = relay_params(slow, None).unwrap(); - assert_eq!(relayed["timeoutMilliseconds"], 700000); - } - - #[test] - fn an_invalid_relayed_call_is_refused_before_anything_is_sent() { - let valid = json!({ "pluginID": "a.b", "functionID": "x.y" }); - let with = |key: &str, value: Value| { - let mut call = valid.clone(); - call[key] = value; - call - }; - let without = |key: &str| { - let mut call = valid.clone(); - call.as_object_mut().unwrap().remove(key); - call - }; - for invalid in [ - json!("x.y"), - json!(null), - without("pluginID"), - with("pluginID", json!("")), - with("pluginID", json!(7)), - without("functionID"), - with("functionID", json!("Not-Valid")), - with("params", json!([])), - with("params", json!(null)), - with("timeoutMilliseconds", json!(0)), - with("timeoutMilliseconds", json!(-1)), - with("timeoutMilliseconds", json!(1.5)), - with("timeoutMilliseconds", json!("5000")), - with("parentOperationID", json!("")), - with("parentOperationID", json!("p".repeat(129))), - with("parentOperationID", json!(12)), - ] { - let error = relay_params(invalid.clone(), Some("op-1")).unwrap_err(); - assert_eq!(error.code(), "sdk.functions.invalidCall", "{invalid}"); - } - } -} - /// Native views services with session-owned resources. pub struct Views { host: Host, @@ -1731,3 +1628,106 @@ impl Network { self.host.scoped(methods::NETWORK_REQUEST, context, params) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn contexts_are_references_or_full_contexts() { + let full = json!({ "contextID": "w1", "generation": 2, "name": "orders" }); + let context = WorkspaceContext::from_value(&full).unwrap(); + assert_eq!( + context.to_value(), + json!({ "contextID": "w1", "generation": 2 }) + ); + assert_eq!(WorkspaceContext::new("w1", 2).unwrap(), context); + // An invocation's context is exactly a reference. + assert_eq!(WorkspaceContext::from_reference(&full), None); + assert_eq!( + WorkspaceContext::from_reference(&context.to_value()), + Some(context) + ); + for invalid in [ + json!({ "contextID": "w1" }), + json!({ "contextID": "w1", "generation": 0 }), + json!({ "contextID": "../w", "generation": 1 }), + json!(null), + ] { + let error = WorkspaceContext::from_value(&invalid).unwrap_err(); + assert_eq!(error.code(), "sdk.host.invalidContext", "{invalid}"); + } + assert!(WorkspaceContext::new("", 1).is_err()); + } + + #[test] + fn a_relayed_call_keeps_only_the_fields_the_method_defines() { + let call = json!({ + "pluginID": "dev.lithe.fixture.java", "functionID": "project.describe", + "params": { "caller": "data" }, "timeoutMilliseconds": 900000, + "parentOperationID": "17", "caller": { "pluginID": "forged" }, + "context": { "contextID": "x" }, "extra": true + }); + let expected = json!({ + "pluginID": "dev.lithe.fixture.java", "functionID": "project.describe", + "params": { "caller": "data" }, "timeoutMilliseconds": 900000, + "parentOperationID": "17" + }); + // Core passes a `caller` inside `params` unchanged; only a top-level one is refused. + assert_eq!(relay_params(call, Some("served")).unwrap(), expected); + } + + #[test] + fn optional_fields_stay_out_and_the_parent_defaults_to_the_call_being_served() { + let call = json!({ "pluginID": "a.b", "functionID": "x.y" }); + assert_eq!(relay_params(call.clone(), None).unwrap(), call); + let served = relay_params(call, Some("op-7")).unwrap(); + assert_eq!(served["parentOperationID"], "op-7"); + assert!(served.get("params").is_none()); + assert!(served.get("timeoutMilliseconds").is_none()); + let named = json!({ "pluginID": "a.b", "functionID": "x.y", "parentOperationID": "own" }); + let relayed = relay_params(named, Some("op-7")).unwrap(); + assert_eq!(relayed["parentOperationID"], "own"); + // The host caps the timeout; the SDK sends what the plugin chose. + let mut slow = json!({ "pluginID": "a.b", "functionID": "x.y" }); + slow["timeoutMilliseconds"] = json!(700000); + let relayed = relay_params(slow, None).unwrap(); + assert_eq!(relayed["timeoutMilliseconds"], 700000); + } + + #[test] + fn an_invalid_relayed_call_is_refused_before_anything_is_sent() { + let valid = json!({ "pluginID": "a.b", "functionID": "x.y" }); + let with = |key: &str, value: Value| { + let mut call = valid.clone(); + call[key] = value; + call + }; + let without = |key: &str| { + let mut call = valid.clone(); + call.as_object_mut().unwrap().remove(key); + call + }; + for invalid in [ + json!("x.y"), + json!(null), + without("pluginID"), + with("pluginID", json!("")), + with("pluginID", json!(7)), + without("functionID"), + with("functionID", json!("Not-Valid")), + with("params", json!([])), + with("params", json!(null)), + with("timeoutMilliseconds", json!(0)), + with("timeoutMilliseconds", json!(-1)), + with("timeoutMilliseconds", json!(1.5)), + with("timeoutMilliseconds", json!("5000")), + with("parentOperationID", json!("")), + with("parentOperationID", json!("p".repeat(129))), + with("parentOperationID", json!(12)), + ] { + let error = relay_params(invalid.clone(), Some("op-1")).unwrap_err(); + assert_eq!(error.code(), "sdk.functions.invalidCall", "{invalid}"); + } + } +}