Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
211 changes: 210 additions & 1 deletion crates/plugin-manager/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ pub struct Manifest {
pub id: String,
pub name: String,
pub api_version: u32,
/// The oldest Buzz release the plugin runs on, as `MAJOR.MINOR.PATCH`. A Buzz
/// older than this refuses to install the plugin or update to it. A Buzz from
/// before this field rejects the manifest as an unknown field, so it refuses too.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub min_buzz_version: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
Expand Down Expand Up @@ -223,7 +228,51 @@ fn valid_program(program: &str, args: &[String]) -> bool {
.iter()
.all(|argument| argument.len() <= 1024 && !argument.contains('\0'))
}
/// A Buzz version, compared by its `MAJOR.MINOR.PATCH` core.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct BuzzVersion(u64, u64, u64);
impl BuzzVersion {
/// A release version as a manifest names it: `1.2.0`, with no prerelease or build.
pub fn release(text: &str) -> Option<Self> {
let mut parts = text.split('.').map(|part| {
let digits = !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit());
let canonical = part == "0" || !part.starts_with('0');
(digits && canonical && part.len() <= 9)
.then(|| part.parse().ok())
.flatten()
});
let version = Self(parts.next()??, parts.next()??, parts.next()??);
parts.next().is_none().then_some(version)
}
/// The running app's version, as Tauri reports it. A prerelease counts as its
/// release (`1.2.0-preview.3` as `1.2.0`), so the previews and betas of the
/// release that adds a feature can install plugins that need it.
pub fn app(text: &str) -> Option<Self> {
Self::release(text.split(['-', '+']).next()?)
}
}
impl std::fmt::Display for BuzzVersion {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}.{}.{}", self.0, self.1, self.2)
}
}
impl Manifest {
/// Refuses a plugin that needs a newer Buzz than `app`. This is separate from
/// `validate`, which also checks every installed plugin on each read: a plugin
/// installed before a downgrade must not stop the others from loading.
pub fn check_buzz_version(&self, app: Option<BuzzVersion>) -> Result<()> {
let required = self
.min_buzz_version
.as_deref()
.and_then(BuzzVersion::release);
match (app, required) {
(Some(app), Some(required)) if app < required => Err(format!(
"{} needs Buzz {required} or later, and this is Buzz {app}. Update Buzz to install it.",
self.name
)),
_ => Ok(()),
}
}
pub fn validate(&self) -> Result<()> {
valid_id(&self.id)?;
if self.name.trim().is_empty() || self.name.len() > 80 {
Expand All @@ -239,6 +288,13 @@ impl Manifest {
if self.api_version != 1 {
return Err("Only page plugin API version 1 is supported".into());
}
if self
.min_buzz_version
.as_deref()
.is_some_and(|version| BuzzVersion::release(version).is_none())
{
return Err("minBuzzVersion must be a release version such as 1.2.0".into());
}
if let Some(discovery) = &self.discovery {
if let Some(category) = &discovery.category {
valid_id(category)?;
Expand Down Expand Up @@ -1032,6 +1088,8 @@ pub struct Manager {
packaged_fetch: std::sync::Arc<std::sync::Mutex<managed::PackagedFetch>>,
automatic: automatic::Session,
policy_signer: Option<String>,
/// The running Buzz, for manifests' `minBuzzVersion`. `None` refuses nothing.
buzz_version: Option<BuzzVersion>,
}
impl Manager {
/// Host control-plane location that protected workers must not modify.
Expand Down Expand Up @@ -1062,8 +1120,17 @@ impl Manager {
automatic: Default::default(),
policy_signer: (!managed::PACKAGED_SIGNER.is_empty())
.then(|| managed::PACKAGED_SIGNER.to_owned()),
buzz_version: None,
})
}
/// Refuse to install a plugin, or update or reload one, when its manifest needs
/// a newer Buzz than `version`. The desktop passes its own version. Without
/// one, as in the `buzzodz` CLI, or with one that does not parse, nothing is
/// refused.
pub fn with_buzz_version(mut self, version: &str) -> Self {
self.buzz_version = BuzzVersion::app(version);
self
}
/// Opens the environment's plugin home, else `home`: the desktop passes its own app data folder.
pub fn from_env(home: Option<PathBuf>) -> Result<Self> {
Self::open(
Expand Down Expand Up @@ -1350,6 +1417,7 @@ impl Manager {
let bytes = &release.bytes;
let artifact = release.artifact()?;
let manifest = artifact.manifest.clone();
manifest.check_buzz_version(self.buzz_version)?;
let readme_revision = artifact.readme_revision();
let icon_png_revision = icon_revision(artifact.icon_png.as_deref());
let icon_jpg_revision = icon_revision(artifact.icon_jpg.as_deref());
Expand Down Expand Up @@ -1530,6 +1598,7 @@ impl Manager {
let release = prepare_reload_artifact(&snapshot.1)?;
let artifact = release.artifact()?;
let manifest = artifact.manifest.clone();
manifest.check_buzz_version(self.buzz_version)?;
let readme_revision = artifact.readme_revision();
let icon_png_revision = icon_revision(artifact.icon_png.as_deref());
let icon_jpg_revision = icon_revision(artifact.icon_jpg.as_deref());
Expand Down Expand Up @@ -1917,7 +1986,7 @@ fn atomic_write(path: &Path, bytes: &[u8]) -> Result<()> {
mod tests {
use super::{
artifact_from_text, bundled_manifests, enabled_by_default, validate_candidate_path,
Manager, Manifest, Release, MAX_HOST_COMMAND_OUTPUT_BYTES,
BuzzVersion, Manager, Manifest, Release, MAX_HOST_COMMAND_OUTPUT_BYTES,
};
use std::collections::BTreeMap;
use std::fs;
Expand Down Expand Up @@ -3163,6 +3232,146 @@ mod tests {
);
}

#[test]
fn min_buzz_version_is_a_release_version_and_absent_by_default() {
let old: Manifest =
serde_json::from_str(r#"{"id":"example.page","name":"Example","apiVersion":1}"#)
.unwrap();
assert_eq!(old.min_buzz_version, None);
assert!(old.check_buzz_version(BuzzVersion::app("0.0.1")).is_ok());
assert_eq!(
serde_json::to_value(&old).unwrap(),
serde_json::json!({"id":"example.page","name":"Example","apiVersion":1})
);
let with = |version: &str| {
serde_json::from_value::<Manifest>(serde_json::json!({
"id": "example.page", "name": "Example", "apiVersion": 1,
"minBuzzVersion": version
}))
.unwrap()
};
for valid in ["0.0.0", "1.2.0", "10.20.30"] {
assert!(with(valid).validate().is_ok(), "{valid}");
}
for invalid in [
"",
"1",
"1.2",
"1.2.3.4",
"01.2.3",
"1.02.3",
"1.2.3-beta.1",
"1.2.3+b",
">=1.2.3",
"^1.2.3",
"v1.2.3",
" 1.2.3",
"1.2.x",
"1..3",
"1234567890.0.0",
] {
assert!(with(invalid).validate().is_err(), "{invalid:?}");
}
}

#[test]
fn app_versions_compare_by_release_and_prereleases_count_as_their_release() {
assert_eq!(BuzzVersion::app("1.2.3"), BuzzVersion::release("1.2.3"));
assert_eq!(
BuzzVersion::app("1.2.3-preview.4"),
BuzzVersion::release("1.2.3")
);
assert_eq!(
BuzzVersion::app("1.2.3-beta.1+abc"),
BuzzVersion::release("1.2.3")
);
assert_eq!(BuzzVersion::app("not a version"), None);
let manifest: Manifest = serde_json::from_str(
r#"{"id":"example.page","name":"Example","apiVersion":1,"minBuzzVersion":"1.10.0"}"#,
)
.unwrap();
for (app, ok) in [
("1.9.9", false),
("1.10.0-preview.1", true),
("1.10.0", true),
("1.10.1", true),
("2.0.0", true),
("0.99.0", false),
] {
assert_eq!(
manifest.check_buzz_version(BuzzVersion::app(app)).is_ok(),
ok,
"{app}"
);
}
let error = manifest
.check_buzz_version(BuzzVersion::app("1.9.9"))
.unwrap_err();
assert!(error.contains("needs Buzz 1.10.0 or later"), "{error}");
assert!(error.contains("this is Buzz 1.9.9"), "{error}");
// A manager that does not know its Buzz version refuses nothing.
assert!(manifest.check_buzz_version(None).is_ok());
}

#[test]
fn a_plugin_that_needs_a_newer_buzz_is_not_installed_updated_or_reloaded() {
let temp = tempfile::tempdir().unwrap();
let manager = Manager::open(Some(temp.path().into()), "test", false)
.unwrap()
.with_buzz_version("1.4.0");
let source = temp.path().join("build");
fs::create_dir(&source).unwrap();
fs::write(source.join("plugin.js"), "export function apply() {}").unwrap();
let write = |min: &str| {
fs::write(
source.join("manifest.json"),
format!(
r#"{{"id":"example.page","name":"Example","apiVersion":1,"minBuzzVersion":"{min}"}}"#
),
)
.unwrap();
sign_source(&source);
};
let installed = |manager: &Manager| {
manager
.catalog()
.unwrap()
.plugins
.into_iter()
.find(|plugin| plugin.manifest.id == "example.page")
};

write("1.5.0");
let error = manager.install(&source).err().unwrap();
assert!(error.contains("needs Buzz 1.5.0 or later"), "{error}");
assert!(installed(&manager).is_none());

write("1.4.0");
manager.install(&source).unwrap();
let first = installed(&manager).unwrap().revision;

// An update or reload to a version that needs a newer Buzz keeps the current one.
write("1.5.0");
for error in [
manager.install(&source).err().unwrap(),
manager.reload("example.page").err().unwrap(),
] {
assert!(error.contains("needs Buzz 1.5.0 or later"), "{error}");
}
let current = installed(&manager).unwrap();
assert_eq!(current.revision, first);
assert_eq!(current.manifest.min_buzz_version.as_deref(), Some("1.4.0"));

// After an update to Buzz it installs, and a later downgrade still lists it:
// an installed manifest is not rechecked against the running Buzz.
let newer = Manager::open(Some(temp.path().into()), "test", false)
.unwrap()
.with_buzz_version("1.5.0-beta.2");
newer.install(&source).unwrap();
assert_ne!(installed(&newer).unwrap().revision, first);
assert!(installed(&manager).is_some());
}

#[test]
fn reload_rejects_changed_host_grants_before_enable() {
let temp = tempfile::tempdir().unwrap();
Expand Down
1 change: 1 addition & 0 deletions crates/plugin-manager/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,7 @@ fn init(directory: &Path, id: &str, name: &str) -> Result<()> {
id: id.into(),
name: name.into(),
api_version: 1,
min_buzz_version: None,
description: None,
discovery: None,
updates: None,
Expand Down
1 change: 1 addition & 0 deletions crates/plugin-manager/src/managed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -683,6 +683,7 @@ pub(crate) mod tests {
id: id.into(),
name: id.into(),
api_version: 1,
min_buzz_version: None,
description: None,
discovery: None,
updates: None,
Expand Down
5 changes: 5 additions & 0 deletions docs/managed-plugins.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,11 @@ one. Otherwise the person gets the update to review. The pin wins over the perso
choice of version. A plugin installed from a folder or bundled with Buzz is never
replaced.

A pinned version whose manifest sets a `minBuzzVersion` newer than the running Buzz is
not installed. An installed copy stays at its current version, and an automatic entry is
tried again on the next run. Pin such a version only once the people it reaches can have
that Buzz.

### Signed policies

A build that should honor automatic entries names the key allowed to sign its policy:
Expand Down
1 change: 1 addition & 0 deletions docs/plugin-authoring-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ export function apply(ctx) {
## Contract rules

- **Manifest:** `id`, `name`, `apiVersion` (`1`), and optional `description`, `discovery` and `host`. Unknown keys reject the whole folder.
- **Minimum Buzz:** optional `"minBuzzVersion": "1.2.0"` names the oldest Buzz release the plugin runs on, as `MAJOR.MINOR.PATCH`. An older Buzz refuses to install the plugin, or to update or reload it to that version, and keeps the installed copy. Previews and betas count as their release. A Buzz from before the field rejects it as an unknown key, so it refuses too, with a less helpful message. Set it when a release starts using host features that older Buzz lacks, instead of feature-detecting them.
- **Plugin id:** lowercase letters, digits, `.` and `-`, starting with a letter, at most 80 bytes, no empty segments, no underscores. Bundled plugins' ids are reserved. Updates match on `id`.
- **Contribution ids** (pages, panels, shortcuts and so on) match `/^[a-z0-9][a-z0-9._-]*$/` and are unique within the plugin.
- **No work at module top level.** Do everything in `apply`. Enabled plugins activate even when their page is never opened.
Expand Down
4 changes: 4 additions & 0 deletions docs/plugins.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ version, nothing is promised across versions, and the author types are versioned
[`src/plugins/author.ts`](../src/plugins/author.ts) and the bundled plugins in
`src/bundled/`.

A plugin that needs a newer host can say so: a manifest's `minBuzzVersion` stops
an older Buzz from installing it or updating to it (see the
[authoring guide](plugin-authoring-guide.md#contract-rules)).

Some parts change less often than others:

- **Steadier:** the envelope (manifest, `inject`/`apply`, `ctx.effect`), owning a
Expand Down
8 changes: 5 additions & 3 deletions src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1040,6 +1040,7 @@ pub fn run() {
.unwrap_or_else(|message| sign_out::exit_with(&message));
let identity = IdentityHost::default();
let identifier = context.config().identifier.clone();
let buzz_version = context.package_info().version.to_string();
let builder = tauri::Builder::default();
let builder = if !tauri::is_dev() {
// Single instance comes first, as its documentation requires. Its deep-link
Expand Down Expand Up @@ -1333,9 +1334,10 @@ pub fn run() {
.manage(DeepLinks::default())
// Plugin storage lives in this identifier's app data, so development
// builds keep theirs apart from the installed app.
.manage(PluginManager(Manager::from_env(
dirs::data_dir().map(|dir| dir.join(&identifier)),
)))
.manage(PluginManager(
Manager::from_env(dirs::data_dir().map(|dir| dir.join(&identifier)))
.map(|manager| manager.with_buzz_version(&buzz_version)),
))
.invoke_handler({
let application_commands = commands::<tauri::Wry>();
let browser_commands: fn(tauri::ipc::Invoke<tauri::Wry>) -> bool = tauri::generate_handler![
Expand Down
3 changes: 3 additions & 0 deletions src/plugins/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ export type PluginManifest = Readonly<{
id: string;
name: string;
apiVersion: 1;
/** Oldest Buzz release the plugin runs on, as `MAJOR.MINOR.PATCH`. An older
* Buzz refuses to install the plugin or update to it. */
minBuzzVersion?: string;
description?: string;
/** Support Git update notices. The user's saved choice overrides this default. */
updates?: Readonly<{ defaultEnabled: boolean }>;
Expand Down
Loading