diff --git a/docs/plugin-development.md b/docs/plugin-development.md index c0ea822..7d07ff4 100644 --- a/docs/plugin-development.md +++ b/docs/plugin-development.md @@ -9,6 +9,10 @@ This reference gives the package contract, the build procedure, and the API for - [Build examples](#build-examples) - [Versions and releases](#versions-and-releases) - [Plugin API](#plugin-api) +- [Use the SDK instead of native calls](#use-the-sdk-instead-of-native-calls) +- [Terminal API](#terminal-api) +- [Folder grants](#folder-grants) +- [Plugin services](#plugin-services) - [Git API](#git-api) - [Background API](#background-api) @@ -227,6 +231,9 @@ Older hosts ignore unknown fields in objects that you pass to the host, such as | `ui.showActionMenu(options)` | yes | Open the shared RuneStone action menu. See [Menus](#menus). | | `completion` | yes | Autocomplete fields and providers. See the [completion API](completion.md). | | `git` | yes | Git operations for the active workspace. See [Git API](#git-api). | +| `pty` | yes | Terminal sessions. See [Terminal API](#terminal-api). | +| `files` | yes | Folders outside the workspace that the user granted to the plugin. See [Folder grants](#folder-grants). | +| `services` | yes | Data that one plugin offers to other plugins. See [Plugin services](#plugin-services). | | `backgrounds` | yes | Background image frames. See [Background API](#background-api). | ### Commands @@ -351,6 +358,92 @@ Only one enabled plugin can own each key. The host removes contributions before A terminal contribution must stop its controls and native sessions before its cleanup finishes. +## Use the SDK instead of native calls + +Do not call `invoke`, `listen`, or other `@tauri-apps/api` functions from a plugin. Do not read the private files of other plugins. +Use the `api` members below. They check plugin shutdown, and they will stay available when a later host runs each plugin in its own isolated context. +Make sure that an optional member exists before you use it. Keep the native call only as a fallback for older hosts. + +The host still accepts the native calls of released plugins. A later host can remove them. + +| Plugin | Current call | Purpose | Use instead | +| --- | --- | --- | --- | +| Terminal | `invoke("pty_open")`, `listen("pty-data")`, `listen("pty-exit")` | Start a shell and receive its output and exit code | `api.pty.open({ ..., onData, onExit })` | +| Terminal | `invoke("pty_write")`, `invoke("pty_resize")`, `invoke("pty_close")` | Send input, change the size, stop the shell | `write`, `resize`, and `close` of the session from `api.pty.open` | +| Terminal | `invoke("pty_profiles")` | List the installed shells | `api.pty.profiles()` | +| Terminal | `invoke("pty_new_window")` | Open a terminal window | `api.pty.openWindow()` | +| Terminal | `invoke("pty_dictation")` | Start Windows voice typing | `api.pty.dictation()` | +| Terminal | `invoke("workspace_read", { rel: ".runestone/tasks.json" })` | Read the task list of the workspace | `api.workspace.read(path)` | +| Background Slideshow | `api.backgrounds.chooseFolder`, `list`, `read`, `defaultFolder`, `readImageSettings`, `writeImageSettings` | Read images and per-image settings from a folder outside the workspace | `api.files` with a folder grant | +| Background Slideshow | `api.workspace.readOptional(".runestone/pm/workspace.json")` | Read the board names of Project Management | A service of Project Management through `api.services` | + +The Git, Project Management, Local Autocomplete, PDF Viewer, and CSV Viewer plugins make no native calls. +Their test scripts replace `window.__TAURI_INTERNALS__` with a test double. That is test code and does not go into the package. + +## Terminal API + +`api.pty` (`version: 1`) starts shells in pseudo terminals. The types are `PtyApi` and `PtySession` in `src/lib/plugins/sdk.ts`. + +| Member | Contract | +| --- | --- | +| `profiles()` | Returns the installed shells as `{ id, title, kind }`. | +| `open(options)` | Starts a shell and returns a session. See the options below. | +| `openWindow()` | Opens a terminal window for the workspace of the current window. | +| `dictation()` | Starts Windows voice typing. Focus the terminal first. Fails on other systems. | + +| Option | Rule | +| --- | --- | +| `cwd` | Required. The workspace root of the window. The start fails when the workspace changed. | +| `cols`, `rows` | Required. Positive integers. | +| `profile` | A profile `id` from `profiles()`. Without it, the host uses the first installed shell. | +| `directory` | A start folder other than the workspace root. | +| `onData(data)` | Required. Receives the output as a `Uint8Array`. A UTF-8 character can be split between two calls. | +| `onExit(code)` | Receives the exit code, or `null`. | + +A session has `id`, `write(text)`, `resize(cols, rows)`, and `close()`. `close()` stops the shell, and more calls return the same promise. +Output goes only to the session that started the shell, as raw bytes. +When the plugin stops, the host stops the output, runs the plugin cleanup, and then closes the sessions that are still open. + +## Folder grants + +`api.files` (`version: 1`) gives access to folders outside the workspace. The user selects each folder. The plugin cannot supply a path. +A grant is `{ id, path, name }`. `id` is opaque. `path` and `name` are for display only. + +| Member | Contract | +| --- | --- | +| `chooseFolder({ title? })` | Opens the folder picker. Returns a grant, or `null` on cancel. The same folder gives the same grant again. | +| `pictureFolder(name)` | Creates `RuneStone ` in the Pictures folder of the user if necessary, and returns a grant for it. `name` has letters, digits, spaces, hyphens, and underscores, at most 64 characters. | +| `grants()` | Returns the grants of this plugin. | +| `revoke(grant)` | Removes a grant. Returns `false` when the plugin has no such grant. | +| `list(grant)` | Returns `{ name, size }` for the ordinary files directly in the folder. Skips folders and links. | +| `readBytes(grant, name)` | Reads one file of at most 64 MiB as a `Uint8Array`. | +| `readSidecar(grant, name)` | Reads a sidecar file as text, or returns `null` when it does not exist. | +| `writeSidecar(grant, name, contents, expected)` | Saves a sidecar file only if it still contains `expected`. Use `null` when the file does not exist. | + +Each plugin has its own grants. The host keeps them with the retained data of the plugin, so they stay after a restart, an update, or a removal. +A file name is one name without folder parts. The host rejects `..`, links, and files that resolve outside the granted folder. +When the granted folder is removed or becomes a link, its grant stops working. Ask the user to choose the folder again. + +A sidecar is a small JSON file that the plugin keeps beside the files of the user. Its name has the form `.runestone-.json`, where `` has letters, digits, hyphens, and underscores. +A sidecar holds valid JSON of at most 1 MiB. The host writes no other files in a granted folder. + +Store the grant `id` in the plugin settings. Before you use a saved grant, look for it in `grants()`. + +## Plugin services + +`api.services` (`version: 1`) lets a plugin offer data to other plugins in the same window. The host passes the calls, so no plugin reads the private files of another plugin. + +| Member | Contract | +| --- | --- | +| `provide(name, methods)` | Offers an object of functions under a name. Returns `{ notify(), dispose() }`. One plugin can offer each name once. | +| `get(plugin, name)` | Returns the methods of a service of another plugin, or `null` when it is not available. | +| `subscribe(listener)` | Calls `listener(plugin, name)` when a service starts, stops, or calls `notify()`. Returns a cleanup function. | + +A service name uses lowercase letters, digits, dots, and hyphens, and starts with a letter. +Each method call returns a promise. The host copies the arguments and the result with `structuredClone`. Use only data that this function can copy, not functions or DOM nodes. +When the provider stops, the host removes its services and notifies the subscribers. Calls through an old service object then fail. Call `get` again after a notification. +Make the data of a service a documented contract of the provider. Give its name, methods, and result shapes in the documentation of the provider plugin. + ## Git API `api.git` gives Git operations for the active workspace of the window. The host runs the `git` command, one operation at a time. @@ -378,14 +471,17 @@ For its native service and test setup, see the [Git plugin development guide](ht `api.backgrounds` (`version: 1`) lets a plugin show image frames behind the RuneStone interface. Frames stay in the current window and do not change the saved appearance settings. +The folder methods are deprecated. They accept a folder path from the plugin. Use [folder grants](#folder-grants) in new code. +The host keeps them for released versions of Background Slideshow. + | Method | Optional | Contract | | --- | --- | --- | -| `chooseFolder()` | | Open the folder picker. Returns an absolute path, or `null` on cancel. | -| `defaultFolder()` | yes | Create `RuneStone Backgrounds` in the Pictures folder of the user and return its path. | -| `list(folder)` | | Return `{ name }` for PNG, JPEG, GIF, and WebP files directly in the folder. | -| `read(folder, name)` | | Read one image as bytes, at most 50 MiB. | -| `readImageSettings(folder)` | yes | Read the per-image settings file text, or `null`. | -| `writeImageSettings(folder, contents, expected)` | yes | Save the per-image settings file. See [Per-image settings](#per-image-settings). | +| `chooseFolder()` | | Deprecated. Use `files.chooseFolder()`. Open the folder picker. Returns an absolute path, or `null` on cancel. | +| `defaultFolder()` | yes | Deprecated. Use `files.pictureFolder("Backgrounds")`. Create `RuneStone Backgrounds` in the Pictures folder of the user and return its path. | +| `list(folder)` | | Deprecated. Use `files.list(grant)`. Return `{ name }` for PNG, JPEG, GIF, and WebP files directly in the folder. | +| `read(folder, name)` | | Deprecated. Use `files.readBytes(grant, name)`. Read one image as bytes, at most 50 MiB. | +| `readImageSettings(folder)` | yes | Deprecated. Use `files.readSidecar(grant, ".runestone-backgrounds.json")`. Read the per-image settings file text, or `null`. | +| `writeImageSettings(folder, contents, expected)` | yes | Deprecated. Use `files.writeSidecar`. Save the per-image settings file. See [Per-image settings](#per-image-settings). | | `set(target, frame)` | | Show a frame for a target. `null` removes the frame of this plugin. | | `get(target)` | | Return the active frame for a target, or `null`. | | `subscribe(listener)` | | Receive the target name when a frame changes. Returns a cleanup function. | @@ -426,4 +522,5 @@ Example: [Project Management](https://git.knottywyvern.com/kwyvern/RuneStone_PM/ The per-image settings file is `.runestone-backgrounds.json` in the image folder. It must be JSON with `"schema": 1` and an `images` object, at most 1 MiB. `writeImageSettings` compares the current file to `expected` (`null` when the file does not exist). It fails when the file changed, so external edits are not lost. +`files.writeSidecar` does the same comparison on the same file, but the host checks only that the text is JSON. The plugin checks the schema. Example: the [Background Slideshow image settings](https://git.knottywyvern.com/kwyvern/RuneStone_BG_Slideshow/src/branch/main/docs/development.md#per-image-settings) give the storage format and the rendering behavior. diff --git a/src-tauri/build.rs b/src-tauri/build.rs index 7a4af12..53672f6 100644 --- a/src-tauri/build.rs +++ b/src-tauri/build.rs @@ -12,6 +12,14 @@ fn main() { "backgrounds_read", "backgrounds_read_image_settings", "backgrounds_write_image_settings", + "folders_choose", + "folders_picture", + "folders_grants", + "folders_revoke", + "folders_list", + "folders_read", + "folders_read_sidecar", + "folders_write_sidecar", "spelling_suggestions", "spelling_menu_install", "spelling_menu_select", diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index b9c691d..1f40cf5 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -96,6 +96,14 @@ "allow-backgrounds-list", "allow-backgrounds-read", "allow-backgrounds-read-image-settings", - "allow-backgrounds-write-image-settings" + "allow-backgrounds-write-image-settings", + "allow-folders-choose", + "allow-folders-picture", + "allow-folders-grants", + "allow-folders-revoke", + "allow-folders-list", + "allow-folders-read", + "allow-folders-read-sidecar", + "allow-folders-write-sidecar" ] } diff --git a/src-tauri/capabilities/settings.json b/src-tauri/capabilities/settings.json index d7b478b..3b6cb16 100644 --- a/src-tauri/capabilities/settings.json +++ b/src-tauri/capabilities/settings.json @@ -41,6 +41,14 @@ "allow-backgrounds-list", "allow-backgrounds-read", "allow-backgrounds-read-image-settings", - "allow-backgrounds-write-image-settings" + "allow-backgrounds-write-image-settings", + "allow-folders-choose", + "allow-folders-picture", + "allow-folders-grants", + "allow-folders-revoke", + "allow-folders-list", + "allow-folders-read", + "allow-folders-read-sidecar", + "allow-folders-write-sidecar" ] } diff --git a/src-tauri/permissions/autogenerated/folders_choose.toml b/src-tauri/permissions/autogenerated/folders_choose.toml new file mode 100644 index 0000000..c7e2b45 --- /dev/null +++ b/src-tauri/permissions/autogenerated/folders_choose.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-folders-choose" +description = "Enables the folders_choose command without any pre-configured scope." +commands.allow = ["folders_choose"] + +[[permission]] +identifier = "deny-folders-choose" +description = "Denies the folders_choose command without any pre-configured scope." +commands.deny = ["folders_choose"] diff --git a/src-tauri/permissions/autogenerated/folders_grants.toml b/src-tauri/permissions/autogenerated/folders_grants.toml new file mode 100644 index 0000000..bdda57e --- /dev/null +++ b/src-tauri/permissions/autogenerated/folders_grants.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-folders-grants" +description = "Enables the folders_grants command without any pre-configured scope." +commands.allow = ["folders_grants"] + +[[permission]] +identifier = "deny-folders-grants" +description = "Denies the folders_grants command without any pre-configured scope." +commands.deny = ["folders_grants"] diff --git a/src-tauri/permissions/autogenerated/folders_list.toml b/src-tauri/permissions/autogenerated/folders_list.toml new file mode 100644 index 0000000..c223f8b --- /dev/null +++ b/src-tauri/permissions/autogenerated/folders_list.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-folders-list" +description = "Enables the folders_list command without any pre-configured scope." +commands.allow = ["folders_list"] + +[[permission]] +identifier = "deny-folders-list" +description = "Denies the folders_list command without any pre-configured scope." +commands.deny = ["folders_list"] diff --git a/src-tauri/permissions/autogenerated/folders_picture.toml b/src-tauri/permissions/autogenerated/folders_picture.toml new file mode 100644 index 0000000..6b3787f --- /dev/null +++ b/src-tauri/permissions/autogenerated/folders_picture.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-folders-picture" +description = "Enables the folders_picture command without any pre-configured scope." +commands.allow = ["folders_picture"] + +[[permission]] +identifier = "deny-folders-picture" +description = "Denies the folders_picture command without any pre-configured scope." +commands.deny = ["folders_picture"] diff --git a/src-tauri/permissions/autogenerated/folders_read.toml b/src-tauri/permissions/autogenerated/folders_read.toml new file mode 100644 index 0000000..79b3990 --- /dev/null +++ b/src-tauri/permissions/autogenerated/folders_read.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-folders-read" +description = "Enables the folders_read command without any pre-configured scope." +commands.allow = ["folders_read"] + +[[permission]] +identifier = "deny-folders-read" +description = "Denies the folders_read command without any pre-configured scope." +commands.deny = ["folders_read"] diff --git a/src-tauri/permissions/autogenerated/folders_read_sidecar.toml b/src-tauri/permissions/autogenerated/folders_read_sidecar.toml new file mode 100644 index 0000000..60a012b --- /dev/null +++ b/src-tauri/permissions/autogenerated/folders_read_sidecar.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-folders-read-sidecar" +description = "Enables the folders_read_sidecar command without any pre-configured scope." +commands.allow = ["folders_read_sidecar"] + +[[permission]] +identifier = "deny-folders-read-sidecar" +description = "Denies the folders_read_sidecar command without any pre-configured scope." +commands.deny = ["folders_read_sidecar"] diff --git a/src-tauri/permissions/autogenerated/folders_revoke.toml b/src-tauri/permissions/autogenerated/folders_revoke.toml new file mode 100644 index 0000000..dac94cd --- /dev/null +++ b/src-tauri/permissions/autogenerated/folders_revoke.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-folders-revoke" +description = "Enables the folders_revoke command without any pre-configured scope." +commands.allow = ["folders_revoke"] + +[[permission]] +identifier = "deny-folders-revoke" +description = "Denies the folders_revoke command without any pre-configured scope." +commands.deny = ["folders_revoke"] diff --git a/src-tauri/permissions/autogenerated/folders_write_sidecar.toml b/src-tauri/permissions/autogenerated/folders_write_sidecar.toml new file mode 100644 index 0000000..cb08189 --- /dev/null +++ b/src-tauri/permissions/autogenerated/folders_write_sidecar.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-folders-write-sidecar" +description = "Enables the folders_write_sidecar command without any pre-configured scope." +commands.allow = ["folders_write_sidecar"] + +[[permission]] +identifier = "deny-folders-write-sidecar" +description = "Denies the folders_write_sidecar command without any pre-configured scope." +commands.deny = ["folders_write_sidecar"] diff --git a/src-tauri/src/folders.rs b/src-tauri/src/folders.rs new file mode 100644 index 0000000..64c5ca9 --- /dev/null +++ b/src-tauri/src/folders.rs @@ -0,0 +1,554 @@ +//! Folder grants for plugins. +//! +//! A plugin gets access to a folder outside the workspace only through a grant. The user makes a +//! grant with the folder picker, or the host makes one for a `RuneStone ` folder in Pictures. +//! Each plugin has its own grant list in its retained data (`plugin-data//folder-grants.json`). +//! A grant gives access to the ordinary files directly in its folder. Names with folder parts, +//! links, and files that resolve outside the folder are rejected. The plugin cannot supply a path. + +use crate::error::{Error, Result}; +use crate::fsutil::{self, is_link}; +use crate::plugins::PluginState; +use serde::{Deserialize, Serialize}; +use std::fs; +use std::path::{Component, Path, PathBuf}; +use std::sync::Mutex; +use tauri::{AppHandle, Manager, Window}; +use tauri_plugin_dialog::DialogExt; + +const GRANTS_FILE: &str = "folder-grants.json"; +const GRANT_LIMIT: usize = 64; +const READ_LIMIT: u64 = 64 * 1024 * 1024; +const SIDECAR_LIMIT: u64 = 1024 * 1024; +const LIST_LIMIT: usize = 10_000; + +/// Serializes changes to grant files and sidecar files. +static LOCK: Mutex<()> = Mutex::new(()); + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +struct StoredGrant { + id: String, + path: PathBuf, +} + +#[derive(Debug, Default, Serialize, Deserialize)] +struct GrantFile { + schema: u32, + grants: Vec, +} + +/// What a plugin receives: an opaque ID and the folder path for display. +#[derive(Clone, Debug, Serialize, PartialEq)] +pub struct FolderGrant { + id: String, + path: String, + name: String, +} + +#[derive(Debug, Serialize, PartialEq)] +pub struct FolderEntry { + name: String, + size: u64, +} + +impl From<&StoredGrant> for FolderGrant { + fn from(grant: &StoredGrant) -> Self { + Self { + id: grant.id.clone(), + path: grant.path.to_string_lossy().into_owned(), + name: grant + .path + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_else(|| grant.path.to_string_lossy().into_owned()), + } + } +} + +/// The grant lists of all plugins, in the folder that holds the retained plugin data. +struct Grants { + data: PathBuf, +} + +impl Grants { + fn plugin_folder(&self, plugin: &str, create: bool) -> Result { + if plugin.is_empty() + || plugin.len() > 128 + || !plugin.bytes().all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'.' || byte == b'-') + || !fsutil::is_plain_component(plugin) + { + return Err("Invalid plugin ID.".into()); + } + let folder = self.data.join(plugin); + match fs::symlink_metadata(&folder) { + Ok(metadata) if metadata.is_dir() && !is_link(&metadata) => Ok(folder), + Ok(_) => Err("The plugin data folder must be an ordinary folder.".into()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound && create => { + fs::create_dir(&folder)?; + Ok(folder) + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(folder), + Err(error) => Err(error.into()), + } + } + + fn load(&self, plugin: &str) -> Result> { + let path = self.plugin_folder(plugin, false)?.join(GRANTS_FILE); + let metadata = match fs::symlink_metadata(&path) { + Ok(metadata) => metadata, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(error) => return Err(error.into()), + }; + if !metadata.is_file() || is_link(&metadata) { + return Err("The folder grant list must be an ordinary file.".into()); + } + let Some(bytes) = fsutil::read_to_limit(fsutil::open_entry(&path)?, SIDECAR_LIMIT)? else { + return Err("The folder grant list exceeds 1 MiB.".into()); + }; + let file: GrantFile = serde_json::from_slice(&bytes)?; + if file.schema != 1 { + return Err("Unknown folder grant list schema.".into()); + } + Ok(file.grants) + } + + fn save(&self, plugin: &str, grants: Vec) -> Result<()> { + let folder = self.plugin_folder(plugin, true)?; + let bytes = serde_json::to_vec_pretty(&GrantFile { schema: 1, grants })?; + let temp = folder.join(format!("{GRANTS_FILE}.{}.tmp", uuid::Uuid::new_v4())); + Ok(fsutil::replace_file(&folder.join(GRANTS_FILE), &temp, &bytes)?) + } + + /// Grant `folder` to `plugin`. Return the existing grant when the plugin already has the folder. + fn add(&self, plugin: &str, folder: &Path) -> Result { + let path = granted_root(folder)?; + let _lock = LOCK.lock()?; + let mut grants = self.load(plugin)?; + if let Some(existing) = grants.iter().find(|grant| grant.path == path) { + return Ok(existing.into()); + } + if grants.len() >= GRANT_LIMIT { + return Err(format!("A plugin can keep at most {GRANT_LIMIT} folder grants. Remove a grant first.").into()); + } + let grant = StoredGrant { id: uuid::Uuid::new_v4().to_string(), path }; + let result = FolderGrant::from(&grant); + grants.push(grant); + self.save(plugin, grants)?; + Ok(result) + } + + fn list(&self, plugin: &str) -> Result> { + Ok(self.load(plugin)?.iter().map(FolderGrant::from).collect()) + } + + fn revoke(&self, plugin: &str, id: &str) -> Result { + let _lock = LOCK.lock()?; + let mut grants = self.load(plugin)?; + let count = grants.len(); + grants.retain(|grant| grant.id != id); + if grants.len() == count { + return Ok(false); + } + self.save(plugin, grants)?; + Ok(true) + } + + /// Return the folder of a grant of this plugin. The folder must still be an ordinary folder + /// at the same resolved path, so a folder that became a link does not redirect access. + fn resolve(&self, plugin: &str, id: &str) -> Result { + uuid::Uuid::parse_str(id).map_err(|_| Error::new("Invalid folder grant."))?; + let grant = self + .load(plugin)? + .into_iter() + .find(|grant| grant.id == id) + .ok_or_else(|| Error::new("This plugin has no grant for the folder. Choose the folder again."))?; + let metadata = fs::symlink_metadata(&grant.path) + .map_err(|_| Error::new("The granted folder is missing. Choose the folder again."))?; + if !metadata.is_dir() || is_link(&metadata) || dunce::canonicalize(&grant.path)? != grant.path { + return Err("The granted folder changed into a link or a file. Choose the folder again.".into()); + } + Ok(grant.path) + } +} + +/// Resolve a chosen folder. Reject relative paths, parent segments, files, and whole drives. +fn granted_root(folder: &Path) -> Result { + if !folder.is_absolute() || folder.components().any(|part| matches!(part, Component::ParentDir)) { + return Err("Supply an absolute folder path without parent segments.".into()); + } + let root = dunce::canonicalize(folder)?; + if !root.is_dir() { + return Err("The folder does not exist.".into()); + } + if root.parent().is_none() { + return Err("Choose a folder, not a whole drive.".into()); + } + Ok(root) +} + +/// The path of one ordinary file directly in `root`. +fn file_path(root: &Path, name: &str) -> Result { + if !fsutil::is_plain_component(name) + || name.contains(['/', '\\', ':']) + || name.ends_with(' ') + || Path::new(name).components().count() != 1 + || !matches!(Path::new(name).components().next(), Some(Component::Normal(_))) + { + return Err("Supply one file name without folder parts.".into()); + } + Ok(root.join(name)) +} + +/// Open one ordinary file. Reject links, also a link that replaces the file after the check. +fn open_plain(root: &Path, path: &Path) -> Result<(fs::File, u64)> { + let metadata = fs::symlink_metadata(path)?; + if !metadata.is_file() || is_link(&metadata) { + return Err("Granted folder access is limited to ordinary files, not links or folders.".into()); + } + let file = fsutil::open_entry(path)?; + let opened = file.metadata()?; + if !opened.is_file() || is_link(&opened) || dunce::canonicalize(path)?.parent() != Some(root) { + return Err("Granted folder access is limited to ordinary files, not links or folders.".into()); + } + Ok((file, opened.len())) +} + +fn list_files(root: &Path) -> Result> { + let mut entries = Vec::new(); + for entry in fs::read_dir(root)? { + let entry = entry?; + let Some(name) = entry.file_name().to_str().map(str::to_owned) else { continue }; + let Ok(metadata) = entry.metadata() else { continue }; + // `DirEntry::metadata` does not follow links. + if !metadata.is_file() || is_link(&metadata) || file_path(root, &name).is_err() { + continue; + } + entries.push(FolderEntry { name, size: metadata.len() }); + if entries.len() > LIST_LIMIT { + return Err(format!("The folder has more than {LIST_LIMIT} files.").into()); + } + } + entries.sort_by(|a, b| a.name.cmp(&b.name)); + Ok(entries) +} + +fn read_file(root: &Path, name: &str) -> Result> { + let path = file_path(root, name)?; + let (file, size) = open_plain(root, &path)?; + if size > READ_LIMIT { + return Err("The file exceeds 64 MiB.".into()); + } + fsutil::read_to_limit(file, READ_LIMIT)?.ok_or_else(|| Error::new("The file exceeds 64 MiB.")) +} + +/// A sidecar is a small JSON file that a plugin keeps beside the user's files, such as +/// `.runestone-backgrounds.json`. Its name starts with `.runestone-` and ends with `.json`. +fn sidecar_path(root: &Path, name: &str) -> Result { + let stem = name.strip_prefix(".runestone-").and_then(|rest| rest.strip_suffix(".json")); + if !stem.is_some_and(|stem| !stem.is_empty() && stem.len() <= 64 && stem.bytes().all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_')) { + return Err("A sidecar file name has the form .runestone-.json.".into()); + } + file_path(root, name) +} + +fn read_sidecar(root: &Path, name: &str) -> Result> { + let path = sidecar_path(root, name)?; + match fs::symlink_metadata(&path) { + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(error.into()), + Ok(_) => {} + } + let (file, size) = open_plain(root, &path)?; + if size > SIDECAR_LIMIT { + return Err("The sidecar file exceeds 1 MiB.".into()); + } + let bytes = fsutil::read_to_limit(file, SIDECAR_LIMIT)?.ok_or_else(|| Error::new("The sidecar file exceeds 1 MiB."))?; + String::from_utf8(bytes).map(Some).map_err(Error::from) +} + +/// Save a sidecar only if it still holds `expected` (`None` when the file does not exist). +fn write_sidecar(root: &Path, name: &str, contents: &str, expected: Option<&str>) -> Result<()> { + let path = sidecar_path(root, name)?; + if contents.len() as u64 > SIDECAR_LIMIT { + return Err("The sidecar file exceeds 1 MiB.".into()); + } + serde_json::from_str::(contents)?; + let _lock = LOCK.lock()?; + if read_sidecar(root, name)?.as_deref() != expected { + return Err("The sidecar file changed. Read it again before you save.".into()); + } + if expected.is_some() { + fsutil::write_text(&path, contents, expected) + } else { + let temp = root.join(format!(".runestone-sidecar-{}.tmp", uuid::Uuid::new_v4())); + Ok(fsutil::create_file(&path, &temp, contents.as_bytes())?) + } +} + +fn grants(app: &AppHandle) -> Result { + Ok(Grants { data: app.path().app_data_dir()?.join("plugin-data") }) +} + +/// Accept only a plugin that is enabled and loaded in the calling window. +/// Check the lease on a blocking worker, because the plugin lock can wait for package work. +async fn check(app: &AppHandle, window: &Window, plugin: &str) -> Result<()> { + let (app, label, plugin) = (app.clone(), window.label().to_owned(), plugin.to_owned()); + tauri::async_runtime::spawn_blocking(move || app.state::().require_lease(&app, &label, &plugin)).await? +} + +/// Check the lease, run `work` on a blocking worker, and check the lease again, +/// so that a plugin that stopped during the work receives no result. +async fn run( + app: &AppHandle, + window: &Window, + plugin: &str, + work: impl FnOnce(Grants) -> Result + Send + 'static, +) -> Result { + check(app, window, plugin).await?; + let store = grants(app)?; + let result = tauri::async_runtime::spawn_blocking(move || work(store)).await??; + check(app, window, plugin).await?; + Ok(result) +} + +#[tauri::command] +pub async fn folders_choose(app: AppHandle, window: Window, plugin: String, title: Option) -> Result> { + check(&app, &window, &plugin).await?; + let (picker_app, picker_window) = (app.clone(), window.clone()); + let title = title.filter(|title| !title.trim().is_empty() && title.len() <= 200).unwrap_or_else(|| "Choose a folder".into()); + let selected = tauri::async_runtime::spawn_blocking(move || { + picker_app.dialog().file().set_parent(&picker_window).set_title(title).blocking_pick_folder() + }) + .await?; + let Some(selected) = selected else { return Ok(None) }; + let folder = selected.into_path().map_err(Error::from_display)?; + let id = plugin.clone(); + run(&app, &window, &plugin, move |store| store.add(&id, &folder)).await.map(Some) +} + +/// Grant `RuneStone ` in the Pictures folder of the user. Create the folder if necessary. +#[tauri::command] +pub async fn folders_picture(app: AppHandle, window: Window, plugin: String, name: String) -> Result { + if name.is_empty() || name.len() > 64 || name.starts_with([' ', '-', '_']) || !name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, ' ' | '-' | '_')) || name.ends_with(' ') { + return Err("Supply a folder name with letters, digits, spaces, hyphens, or underscores.".into()); + } + let folder = app.path().picture_dir()?.join(format!("RuneStone {name}")); + let id = plugin.clone(); + run(&app, &window, &plugin, move |store| { + fs::create_dir_all(&folder)?; + let metadata = fs::symlink_metadata(&folder)?; + if !metadata.is_dir() || is_link(&metadata) { + return Err("The Pictures folder entry must be an ordinary folder.".into()); + } + store.add(&id, &folder) + }) + .await +} + +#[tauri::command] +pub async fn folders_grants(app: AppHandle, window: Window, plugin: String) -> Result> { + let id = plugin.clone(); + run(&app, &window, &plugin, move |store| store.list(&id)).await +} + +#[tauri::command] +pub async fn folders_revoke(app: AppHandle, window: Window, plugin: String, grant: String) -> Result { + let id = plugin.clone(); + run(&app, &window, &plugin, move |store| store.revoke(&id, &grant)).await +} + +#[tauri::command] +pub async fn folders_list(app: AppHandle, window: Window, plugin: String, grant: String) -> Result> { + let id = plugin.clone(); + run(&app, &window, &plugin, move |store| list_files(&store.resolve(&id, &grant)?)).await +} + +/// Return the bytes as an `ArrayBuffer`, not as JSON or base64 text. +#[tauri::command] +pub async fn folders_read(app: AppHandle, window: Window, plugin: String, grant: String, name: String) -> Result { + let id = plugin.clone(); + let bytes = run(&app, &window, &plugin, move |store| read_file(&store.resolve(&id, &grant)?, &name)).await?; + Ok(tauri::ipc::Response::new(bytes)) +} + +#[tauri::command] +pub async fn folders_read_sidecar(app: AppHandle, window: Window, plugin: String, grant: String, name: String) -> Result> { + let id = plugin.clone(); + run(&app, &window, &plugin, move |store| read_sidecar(&store.resolve(&id, &grant)?, &name)).await +} + +#[tauri::command] +pub async fn folders_write_sidecar(app: AppHandle, window: Window, plugin: String, grant: String, name: String, contents: String, expected: Option) -> Result<()> { + check(&app, &window, &plugin).await?; + let store = grants(&app)?; + // Check the lease again immediately before the write, on the blocking worker. + tauri::async_runtime::spawn_blocking(move || { + app.state::().require_lease(&app, window.label(), &plugin)?; + write_sidecar(&store.resolve(&plugin, &grant)?, &name, &contents, expected.as_deref()) + }) + .await? +} + +#[cfg(test)] +mod tests { + use super::*; + + struct Fixture(PathBuf); + impl Fixture { + fn new() -> Self { + let root = std::env::temp_dir().join(format!("runestone-folders-{}", uuid::Uuid::new_v4())); + fs::create_dir(&root).unwrap(); + Self(dunce::canonicalize(root).unwrap()) + } + fn folder(&self, name: &str) -> PathBuf { + let path = self.0.join(name); + fs::create_dir_all(&path).unwrap(); + path + } + fn store(&self) -> Grants { + Grants { data: self.folder("plugin-data") } + } + } + impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + /// Make a link, or return `false` when Windows does not allow links for this user. + fn link(original: &Path, link: &Path, folder: bool) -> bool { + #[cfg(unix)] + { + let _ = folder; + std::os::unix::fs::symlink(original, link).unwrap(); + true + } + #[cfg(windows)] + { + let result = if folder { + std::os::windows::fs::symlink_dir(original, link) + } else { + std::os::windows::fs::symlink_file(original, link) + }; + match result { + Ok(()) => true, + Err(error) if error.raw_os_error() == Some(windows_sys::Win32::Foundation::ERROR_PRIVILEGE_NOT_HELD as i32) => { + eprintln!("The link check requires Windows Developer Mode or the symbolic-link privilege."); + false + } + Err(error) => panic!("{error}"), + } + } + } + + #[test] + fn grants_persist_per_plugin_and_can_be_revoked() { + let fixture = Fixture::new(); + let images = fixture.folder("images"); + fs::write(images.join("a.png"), b"png").unwrap(); + let store = fixture.store(); + let grant = store.add("org.test.one", &images).unwrap(); + assert_eq!(grant.path, images.to_string_lossy()); + assert_eq!(grant.name, "images"); + // The same folder gives the same grant. + assert_eq!(store.add("org.test.one", &images).unwrap().id, grant.id); + // A new store reads the saved grants, as after a restart. + let reopened = fixture.store(); + assert_eq!(reopened.list("org.test.one").unwrap(), vec![grant.clone()]); + assert_eq!(read_file(&reopened.resolve("org.test.one", &grant.id).unwrap(), "a.png").unwrap(), b"png"); + // Another plugin cannot use the grant ID of the first plugin. + assert!(reopened.resolve("org.test.two", &grant.id).is_err()); + assert!(reopened.list("org.test.two").unwrap().is_empty()); + assert!(!reopened.revoke("org.test.two", &grant.id).unwrap()); + assert!(reopened.resolve("org.test.one", &grant.id).is_ok()); + assert!(reopened.revoke("org.test.one", &grant.id).unwrap()); + assert!(reopened.resolve("org.test.one", &grant.id).is_err()); + assert!(reopened.list("org.test.one").unwrap().is_empty()); + } + + #[test] + fn grants_reject_invalid_plugins_ids_and_folders() { + let fixture = Fixture::new(); + let store = fixture.store(); + let folder = fixture.folder("images"); + for plugin in ["", "..", "../escape", "Upper", "a/b", "a\\b", "con"] { + assert!(store.add(plugin, &folder).is_err(), "{plugin}"); + } + assert!(store.add("org.test.one", Path::new("relative")).is_err()); + assert!(store.add("org.test.one", &folder.join("..").join("images")).is_err()); + assert!(store.add("org.test.one", &fixture.0.join("missing")).is_err()); + fs::write(fixture.0.join("file.txt"), "x").unwrap(); + assert!(store.add("org.test.one", &fixture.0.join("file.txt")).is_err()); + let drive = folder.ancestors().last().unwrap().to_path_buf(); + assert!(store.add("org.test.one", &drive).is_err()); + assert!(store.resolve("org.test.one", "not-a-uuid").is_err()); + assert!(store.resolve("org.test.one", &uuid::Uuid::new_v4().to_string()).is_err()); + } + + #[test] + fn names_cannot_leave_the_granted_folder() { + let fixture = Fixture::new(); + let root = fixture.folder("images"); + fs::write(fixture.0.join("secret.txt"), "secret").unwrap(); + fixture.folder("images/nested"); + fs::write(root.join("nested/inner.png"), "inner").unwrap(); + for name in ["../secret.txt", "..", ".", "nested/inner.png", "nested\\inner.png", "C:\\secret.txt", "/secret.txt", "a.png:stream", "", "nul", "trailing."] { + assert!(read_file(&root, name).is_err(), "{name}"); + } + assert!(read_file(&root, "nested").is_err(), "a folder is not a file"); + fs::write(root.join("b.txt"), "b").unwrap(); + fs::write(root.join("a.png"), "a").unwrap(); + assert_eq!(list_files(&root).unwrap(), vec![FolderEntry { name: "a.png".into(), size: 1 }, FolderEntry { name: "b.txt".into(), size: 1 }]); + } + + #[test] + fn links_are_rejected() { + let fixture = Fixture::new(); + let root = fixture.folder("images"); + let outside = fixture.folder("outside"); + fs::write(outside.join("secret.png"), "secret").unwrap(); + if !link(&outside.join("secret.png"), &root.join("link.png"), false) { + return; + } + assert!(list_files(&root).unwrap().is_empty(), "the listing skips links"); + assert!(read_file(&root, "link.png").is_err()); + // A granted folder that is replaced by a link loses its access. + let store = fixture.store(); + let moved = fixture.folder("moved"); + let grant = store.add("org.test.one", &moved).unwrap(); + fs::remove_dir(&moved).unwrap(); + assert!(link(&outside, &moved, true)); + assert!(store.resolve("org.test.one", &grant.id).is_err()); + } + + #[test] + fn reads_have_a_size_limit() { + let fixture = Fixture::new(); + let root = fixture.folder("images"); + fs::File::create(root.join("large.bin")).unwrap().set_len(READ_LIMIT + 1).unwrap(); + assert!(read_file(&root, "large.bin").unwrap_err().to_string().contains("64 MiB")); + fs::File::create(root.join(".runestone-large.json")).unwrap().set_len(SIDECAR_LIMIT + 1).unwrap(); + assert!(read_sidecar(&root, ".runestone-large.json").is_err()); + } + + #[test] + fn sidecars_keep_external_changes_and_accept_only_sidecar_names() { + let fixture = Fixture::new(); + let root = fixture.folder("images"); + let name = ".runestone-backgrounds.json"; + let first = r#"{"schema":1,"images":{}}"#; + let next = r#"{"schema":1,"images":{"a.png":{}}}"#; + assert_eq!(read_sidecar(&root, name).unwrap(), None); + write_sidecar(&root, name, first, None).unwrap(); + assert!(write_sidecar(&root, name, next, None).is_err()); + assert!(write_sidecar(&root, name, next, Some("stale")).is_err()); + write_sidecar(&root, name, next, Some(first)).unwrap(); + assert_eq!(read_sidecar(&root, name).unwrap().as_deref(), Some(next)); + assert!(write_sidecar(&root, name, "not json", Some(next)).is_err()); + assert!(write_sidecar(&root, name, &format!("\"{}\"", "x".repeat(SIDECAR_LIMIT as usize)), Some(next)).is_err()); + for bad in ["a.png", "settings.json", ".runestone-.json", ".runestone-a/b.json", ".runestone-a.json.png", "../.runestone-a.json"] { + assert!(write_sidecar(&root, bad, "{}", None).is_err(), "{bad}"); + assert!(read_sidecar(&root, bad).is_err(), "{bad}"); + } + } +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index b7c2bfe..5362f36 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -14,6 +14,7 @@ mod tab_transfer; mod spelling; mod theme; mod backgrounds; +mod folders; use pty::PtyState; use tauri::Manager; @@ -39,6 +40,14 @@ pub fn run() { backgrounds::backgrounds_read, backgrounds::backgrounds_read_image_settings, backgrounds::backgrounds_write_image_settings, + folders::folders_choose, + folders::folders_picture, + folders::folders_grants, + folders::folders_revoke, + folders::folders_list, + folders::folders_read, + folders::folders_read_sidecar, + folders::folders_write_sidecar, theme::theme_export, spelling::spelling_menu_install, spelling::spelling_suggestions, diff --git a/src-tauri/src/pty.rs b/src-tauri/src/pty.rs index df079dd..1f66be7 100644 --- a/src-tauri/src/pty.rs +++ b/src-tauri/src/pty.rs @@ -6,6 +6,7 @@ use std::path::{Path, PathBuf}; use portable_pty::{native_pty_system, CommandBuilder, MasterPty, PtySize}; use serde::Serialize; +use tauri::ipc::{Channel, InvokeResponseBody, JavaScriptChannelId}; use tauri::{AppHandle, Emitter, Manager, State}; use crate::error::{Error, Result}; @@ -72,6 +73,63 @@ pub struct PtyExit { pub code: Option, } +/// The destination of the output and the exit status of one terminal session. +trait PtyOutput: Send { + fn data(&self, bytes: &[u8]); + fn exit(&self, code: Option); +} + +/// Window events for the released Terminal plugin, which listens for `pty-data` and `pty-exit`. +/// The events go to the window that opened the session. A global `listen` in that window +/// receives them. Tauri 2 also delivers an addressed event to a global `listen` in other windows. +struct EventOutput { + app: AppHandle, + owner: String, + id: String, +} + +impl PtyOutput for EventOutput { + fn data(&self, bytes: &[u8]) { + let _ = self.app.emit_to(self.owner.as_str(), "pty-data", PtyData { id: self.id.clone(), data: bytes.to_vec() }); + } + fn exit(&self, code: Option) { + let _ = self.app.emit_to(self.owner.as_str(), "pty-exit", PtyExit { id: self.id.clone(), code }); + } +} + +/// A channel to the webview that opened the session. Output goes as raw bytes (an +/// `ArrayBuffer` in JavaScript). The exit status goes as `{ "exit": code }`. +struct ChannelOutput(Channel); + +impl PtyOutput for ChannelOutput { + fn data(&self, bytes: &[u8]) { + let _ = self.0.send(InvokeResponseBody::Raw(bytes.to_vec())); + } + fn exit(&self, code: Option) { + let _ = self.0.send(InvokeResponseBody::Json(serde_json::json!({ "exit": code }).to_string())); + } +} + +/// Use the channel when the caller supplies one. Without a channel, use window events. +fn output(channel: Option>, events: impl FnOnce() -> Box) -> Box { + match channel { + Some(channel) => Box::new(ChannelOutput(channel)), + None => events(), + } +} + +/// Send the output until the reader reaches EOF. Then send the exit status. +fn pump(mut reader: impl Read, exit: std::sync::mpsc::Receiver>, output: &dyn PtyOutput) { + let mut buf = [0u8; 4096]; + loop { + match reader.read(&mut buf) { + Ok(0) | Err(_) => break, + Ok(n) => output.data(&buf[..n]), + } + } + output.exit(exit.recv().ok().flatten()); +} + type ShellProcess = ( OpenPty, Box, @@ -223,6 +281,7 @@ fn spawn_shell(root: &Path, cols: u16, rows: u16, profile: Option<&str>, owner: pub async fn pty_open( app: AppHandle, window: tauri::Window, + webview: tauri::Webview, workspace: State<'_, WorkspaceState>, id: String, cols: u16, @@ -230,13 +289,16 @@ pub async fn pty_open( cwd: String, profile: Option, directory: Option, + channel: Option, ) -> Result<()> { let root = current_root(&workspace, window.label())?; if root.to_string_lossy() != cwd { return Err(Error::new("workspace changed before the terminal started")); } let owner = window.label().to_owned(); - tauri::async_runtime::spawn_blocking(move || open(app, owner, root, id, cols, rows, profile, directory)).await? + // A session with a channel sends no `pty-data` or `pty-exit` events. + let channel = channel.map(|channel| channel.channel_on(webview)); + tauri::async_runtime::spawn_blocking(move || open(app, owner, root, id, cols, rows, profile, directory, channel)).await? } #[allow(clippy::too_many_arguments)] @@ -249,6 +311,7 @@ fn open( rows: u16, profile: Option, directory: Option, + channel: Option>, ) -> Result<()> { let pty = app.state::(); let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?; @@ -257,7 +320,7 @@ fn open( } let directory = directory.map(PathBuf::from).unwrap_or(root); if !directory.is_dir() { return Err(Error::new("Terminal working directory does not exist")); } - let (session, mut reader, mut child) = spawn_shell(&directory, cols, rows, profile.as_deref(), &owner)?; + let (session, reader, mut child) = spawn_shell(&directory, cols, rows, profile.as_deref(), &owner)?; guard.insert(id.clone(), session); drop(guard); let (exit_tx, exit_rx) = std::sync::mpsc::channel(); @@ -275,41 +338,8 @@ fn open( drop(session); let _ = exit_tx.send(code); }); - let app_reader = app.clone(); - let reader_id = id.clone(); - thread::spawn(move || { - let mut buf = [0u8; 4096]; - // Address the terminal events to the window that opened the session. - // A global `listen` in that window receives them. Tauri 2 also delivers an addressed - // event to a global `listen` in other windows. A listener with a window target does not - // receive the events of other windows. - loop { - match reader.read(&mut buf) { - Ok(0) => break, - Ok(n) => { - let data = buf[..n].to_vec(); - let _ = app_reader.emit_to( - owner.as_str(), - "pty-data", - PtyData { - id: reader_id.clone(), - data, - }, - ); - } - Err(_) => break, - } - } - let code = exit_rx.recv().ok().flatten(); - let _ = app_reader.emit_to( - owner.as_str(), - "pty-exit", - PtyExit { - id: reader_id, - code, - }, - ); - }); + let output = output(channel, || Box::new(EventOutput { app: app.clone(), owner, id })); + thread::spawn(move || pump(reader, exit_rx, output.as_ref())); Ok(()) } @@ -403,8 +433,50 @@ pub fn pty_dictation() -> Result<()> { #[cfg(test)] mod tests { use super::*; + use std::sync::Arc; use std::time::{Duration, Instant}; + /// Records the window events that a session would send. + struct FakeEvents(Arc>>); + impl PtyOutput for FakeEvents { + fn data(&self, bytes: &[u8]) { self.0.lock().unwrap().push(format!("pty-data {}", String::from_utf8_lossy(bytes))); } + fn exit(&self, code: Option) { self.0.lock().unwrap().push(format!("pty-exit {code:?}")); } + } + + fn run_pump(channel: Option>, events: Arc>>) { + let (exit_tx, exit_rx) = std::sync::mpsc::channel(); + exit_tx.send(Some(3)).unwrap(); + let output = output(channel, move || Box::new(FakeEvents(events))); + pump(std::io::Cursor::new(b"hello \xce\xbb".to_vec()), exit_rx, output.as_ref()); + } + + #[test] + fn a_channel_session_sends_raw_bytes_and_no_window_events() { + let events = Arc::new(Mutex::new(Vec::new())); + let received = Arc::new(Mutex::new(Vec::new())); + let sink = received.clone(); + let channel = Channel::new(move |body| { sink.lock().unwrap().push(body); Ok(()) }); + run_pump(Some(channel), events.clone()); + assert!(events.lock().unwrap().is_empty(), "a channel session must not send pty-data or pty-exit events"); + let received = received.lock().unwrap(); + assert_eq!(received.len(), 2); + match &received[0] { + InvokeResponseBody::Raw(bytes) => assert_eq!(bytes, b"hello \xce\xbb"), + InvokeResponseBody::Json(json) => panic!("output must be raw bytes, not JSON: {json}"), + } + match &received[1] { + InvokeResponseBody::Json(json) => assert_eq!(serde_json::from_str::(json).unwrap(), serde_json::json!({ "exit": 3 })), + InvokeResponseBody::Raw(_) => panic!("the exit status must be JSON"), + } + } + + #[test] + fn a_session_without_a_channel_keeps_the_window_events() { + let events = Arc::new(Mutex::new(Vec::new())); + run_pump(None, events.clone()); + assert_eq!(*events.lock().unwrap(), vec!["pty-data hello λ".to_owned(), "pty-exit Some(3)".to_owned()]); + } + #[test] fn installed_profiles_start_and_report_shell_prompts() { let root = dunce::canonicalize(std::env::current_dir().unwrap()).unwrap(); diff --git a/src/lib/plugins/externalSession.ts b/src/lib/plugins/externalSession.ts index 9b740ec..c6be584 100644 --- a/src/lib/plugins/externalSession.ts +++ b/src/lib/plugins/externalSession.ts @@ -3,8 +3,16 @@ import { completionHub } from "../completion/hub.ts"; import { registerCompletionInput } from "../completion/input.ts"; import { showActionMenu } from "../ui/managedActionMenu.ts"; import { backgroundHub } from "./backgrounds.ts"; +import { serviceHub as defaultServiceHub, type ServiceHub } from "./services.ts"; import type { BackgroundFiles } from "./backgroundContracts.ts"; -import type { Dispose, PluginApi, PluginCommand, PluginModule, PluginView, PluginDocumentType, PluginDocumentContext } from "./sdk.ts"; +import type { Dispose, FilesApi, FilesTransport, PluginApi, PluginCommand, PluginModule, PluginView, PluginDocumentType, PluginDocumentContext, PtyApi, PtyOpenOptions, PtySession, PtyTransport } from "./sdk.ts"; + +/** The host services that a session gives to its plugin. The host binds them to the plugin ID. */ +export type SessionServices = Pick & { + openFile?: PluginApi["openFile"]; git?: PluginApi["git"]; backgrounds?: BackgroundFiles; + completionTransport?: NonNullable["transport"]; + pty?: PtyTransport; files?: FilesTransport; serviceHub?: ServiceHub; +}; export function deadline(work: Promise, milliseconds = 5000): Promise { let timer: ReturnType; @@ -27,8 +35,11 @@ export class ExternalSession { private registry: ContributionRegistry; private backgroundOwner = Symbol('plugin backgrounds'); private backgroundSubscriptions = new Set<() => void>(); + private serviceOwner = Symbol('plugin services'); + private serviceSubscriptions = new Set<() => void>(); + private ptySessions = new Map Promise>(); readonly id: string; - private services: Pick & { openFile?: PluginApi["openFile"]; git?: PluginApi["git"]; backgrounds?: BackgroundFiles; completionTransport?: NonNullable["transport"] }; + private services: SessionServices; private changed: () => void; private show: PluginApi["openView"]; private close?: PluginApi["closeView"]; @@ -37,7 +48,7 @@ export class ExternalSession { private receiveTab?: (data: string) => void | Promise; private openDocument: (path: string) => Promise; private renameDocument?: PluginApi["renameDocument"]; - constructor(id: string, services: Pick & { openFile?: PluginApi["openFile"]; git?: PluginApi["git"]; backgrounds?: BackgroundFiles; completionTransport?: NonNullable["transport"] }, changed: () => void, show: PluginApi["openView"], registry: ContributionRegistry = pluginHost, openDocument: (path: string) => Promise = async () => { throw new Error("Document views are unavailable."); }, renameDocument?: PluginApi["renameDocument"], close?: PluginApi["closeView"], replace?: PluginApi["replaceView"], replaceDocument?: PluginApi["replaceDocumentWithView"]) { + constructor(id: string, services: SessionServices, changed: () => void, show: PluginApi["openView"], registry: ContributionRegistry = pluginHost, openDocument: (path: string) => Promise = async () => { throw new Error("Document views are unavailable."); }, renameDocument?: PluginApi["renameDocument"], close?: PluginApi["closeView"], replace?: PluginApi["replaceView"], replaceDocument?: PluginApi["replaceDocumentWithView"]) { this.openDocument = openDocument; this.renameDocument = renameDocument; this.close = close; @@ -54,6 +65,9 @@ export class ExternalSession { }; const api: PluginApi = { id: this.id, signal: this.controller.signal, + ...(this.services.pty ? { pty: this.ptyApi(this.services.pty) } : {}), + ...(this.services.files ? { files: this.filesApi(this.services.files) } : {}), + services: this.servicesApi(this.services.serviceHub ?? defaultServiceHub), ...(this.services.backgrounds ? { backgrounds: { version: 1 as const, chooseFolder: () => this.backgroundRequest(() => this.services.backgrounds!.chooseFolder()), @@ -180,6 +194,85 @@ export class ExternalSession { this.check(); return request().then(value => { this.check(); return value; }); } + private ptyApi(pty: PtyTransport): PtyApi { + const size = (cols: unknown, rows: unknown) => { + if (![cols, rows].every(value => Number.isInteger(value) && (value as number) > 0 && (value as number) <= 10_000)) throw new Error("Terminal columns and rows must be positive integers."); + }; + const validate = (options: PtyOpenOptions) => { + this.check(); + if (!options || typeof options.onData !== "function" || (options.onExit !== undefined && typeof options.onExit !== "function")) throw new Error("A terminal session needs an onData function."); + if (typeof options.cwd !== "string") throw new Error("Supply the workspace folder as cwd."); + size(options.cols, options.rows); + }; + const open = async (options: PtyOpenOptions): Promise => { + const id = crypto.randomUUID(); + let closed = false, exited = false, closing: Promise | undefined; + const exit = (code: number | null) => { + if (exited) return; + exited = true; this.ptySessions.delete(id); + if (!closed && !this.stopped) options.onExit?.(code); + }; + const opening = pty.open({ id, cwd: options.cwd, cols: options.cols, rows: options.rows, ...(options.profile === undefined ? {} : { profile: options.profile }), ...(options.directory === undefined ? {} : { directory: options.directory }) }, + data => { if (!closed && !this.stopped) options.onData(data); }, exit); + // Wait for the start, so that a close cannot leave a late shell running. + const close = () => closing ??= (async () => { + closed = true; + try { await opening; } catch { this.ptySessions.delete(id); return; } + this.ptySessions.delete(id); + await pty.close(id); + })(); + this.ptySessions.set(id, close); + try { await opening; } catch (error) { this.ptySessions.delete(id); closed = true; throw error; } + if (this.stopped) { await close(); this.check(); } + const live = () => { this.check(); if (closed) throw new Error("This terminal is closed."); }; + return { + id, + write: data => { live(); if (typeof data !== "string") throw new Error("Terminal input must be text."); return pty.write(id, data); }, + resize: (cols, rows) => { live(); size(cols, rows); return pty.resize(id, cols, rows); }, + close, + }; + }; + return { + version: 1, + profiles: () => this.backgroundRequest(() => pty.profiles()), + open: options => { validate(options); return open(options); }, + openWindow: () => { this.check(); return pty.openWindow(); }, + dictation: () => { this.check(); return pty.dictation(); }, + }; + } + private filesApi(files: FilesTransport): FilesApi { + const text = (value: unknown, label: string) => { if (typeof value !== "string" || !value) throw new Error(`Supply the ${label} as text.`); }; + return { + version: 1, + chooseFolder: options => this.backgroundRequest(() => files.chooseFolder(options?.title === undefined ? undefined : { title: String(options.title) })), + pictureFolder: name => { text(name, "folder name"); return this.backgroundRequest(() => files.pictureFolder(name)); }, + grants: () => this.backgroundRequest(() => files.grants()), + revoke: grant => { text(grant, "grant ID"); return this.backgroundRequest(() => files.revoke(grant)); }, + list: grant => { text(grant, "grant ID"); return this.backgroundRequest(() => files.list(grant)); }, + readBytes: (grant, name) => { text(grant, "grant ID"); text(name, "file name"); return this.backgroundRequest(() => files.readBytes(grant, name)); }, + readSidecar: (grant, name) => { text(grant, "grant ID"); text(name, "file name"); return this.backgroundRequest(() => files.readSidecar(grant, name)); }, + writeSidecar: (grant, name, contents, expected) => { + text(grant, "grant ID"); text(name, "file name"); + if (typeof contents !== "string" || (expected !== null && typeof expected !== "string")) throw new Error("Supply the sidecar text and the expected text or null."); + return this.backgroundRequest(() => files.writeSidecar(grant, name, contents, expected)); + }, + }; + } + private servicesApi(hub: ServiceHub): NonNullable { + return { + version: 1, + provide: (name, methods) => { this.check(); return hub.provide(this.serviceOwner, this.id, name, methods); }, + get: (plugin, name) => { this.check(); return hub.get(plugin, name, () => !this.stopped); }, + subscribe: listener => { + this.check(); + if (typeof listener !== "function") throw new Error("A service listener must be a function."); + const off = hub.subscribe((plugin, name) => { if (!this.stopped) listener(plugin, name); }); + const cleanup = () => { off(); this.serviceSubscriptions.delete(cleanup); }; + this.serviceSubscriptions.add(cleanup); + return cleanup; + }, + }; + } async dropTab(data: string) { this.check(); if (!this.receiveTab) throw new Error("This plugin cannot receive tabs."); @@ -207,6 +300,8 @@ export class ExternalSession { this.stopped = true; this.controller.abort(); this.commands.clear(); this.views.clear(); this.documentTypes.clear(); this.receiveTab = undefined; this.changed(); for (const off of this.backgroundSubscriptions) off(); backgroundHub.removeOwner(this.backgroundOwner); + for (const off of this.serviceSubscriptions) off(); + (this.services.serviceHub ?? defaultServiceHub).removeOwner(this.serviceOwner); for (const remove of this.contributions.splice(0)) remove(); this.stopping = (async () => { const errors: unknown[] = []; @@ -217,6 +312,10 @@ export class ExternalSession { try { await deadline(Promise.resolve().then(cleanup)); } catch (error) { errors.push(error); } } this.cleanups = []; + // Stop the terminal sessions that the plugin cleanup left open. + for (const close of [...this.ptySessions.values()]) { + try { await deadline(close()); } catch (error) { errors.push(error); } + } if (errors.length) throw new Error(errors.map(String).join("\n")); })(); return this.stopping; diff --git a/src/lib/plugins/nativeServices.ts b/src/lib/plugins/nativeServices.ts new file mode 100644 index 0000000..519ba4b --- /dev/null +++ b/src/lib/plugins/nativeServices.ts @@ -0,0 +1,37 @@ +import { Channel, invoke } from "@tauri-apps/api/core"; +import type { FilesTransport, FolderEntry, FolderGrant, PtyProfile, PtyTransport } from "./sdk.ts"; + +/** + * Terminal sessions over a channel to this webview. The output arrives as raw bytes, and no + * `pty-data` or `pty-exit` event goes to other windows. The released Terminal plugin uses the + * events instead, and the host keeps them for sessions without a channel. + */ +export const ptyTransport: PtyTransport = { + open: (request, onData, onExit) => { + const channel = new Channel(message => { + if (message instanceof ArrayBuffer) onData(new Uint8Array(message)); + else if (message && typeof message === "object" && "exit" in message) onExit(message.exit); + }); + return invoke("pty_open", { ...request, channel }); + }, + write: (id, data) => invoke("pty_write", { id, data }), + resize: (id, cols, rows) => invoke("pty_resize", { id, cols, rows }), + close: id => invoke("pty_close", { id }), + profiles: () => invoke("pty_profiles"), + openWindow: () => invoke("pty_new_window", { id: crypto.randomUUID() }), + dictation: () => invoke("pty_dictation"), +}; + +/** Folder grants of one plugin. The plugin ID comes from the host, not from the plugin. */ +export function filesTransport(plugin: string): FilesTransport { + return { + chooseFolder: options => invoke("folders_choose", { plugin, title: options?.title ?? null }), + pictureFolder: name => invoke("folders_picture", { plugin, name }), + grants: () => invoke("folders_grants", { plugin }), + revoke: grant => invoke("folders_revoke", { plugin, grant }), + list: grant => invoke("folders_list", { plugin, grant }), + readBytes: async (grant, name) => new Uint8Array(await invoke("folders_read", { plugin, grant, name })), + readSidecar: (grant, name) => invoke("folders_read_sidecar", { plugin, grant, name }), + writeSidecar: (grant, name, contents, expected) => invoke("folders_write_sidecar", { plugin, grant, name, contents, expected }), + }; +} diff --git a/src/lib/plugins/sdk.ts b/src/lib/plugins/sdk.ts index 3d74d30..dd60af8 100644 --- a/src/lib/plugins/sdk.ts +++ b/src/lib/plugins/sdk.ts @@ -19,7 +19,72 @@ export interface PluginDocumentType { create?: { label: string; defaultName: string; extension: string; contents(): string }; mount(container: HTMLElement, document: PluginDocumentContext): void | Dispose | Promise; } +export interface PtyProfile { id: string; title: string; kind: string } +export interface PtyOpenOptions { + /** The workspace root of the window. The host rejects the request when the workspace changed. */ + cwd: string; + cols: number; + rows: number; + profile?: string; + /** A start folder other than the workspace root. */ + directory?: string; + /** Receives raw terminal output. UTF-8 characters can be split between two calls. */ + onData(data: Uint8Array): void; + onExit?(code: number | null): void; +} +export interface PtySession { + readonly id: string; + write(data: string): Promise; + resize(cols: number, rows: number): Promise; + /** Stops the shell. Repeated calls return the same promise. */ + close(): Promise; +} +/** Terminal sessions. The host closes the sessions of a plugin when the plugin stops. */ +export interface PtyApi { + readonly version: 1; + profiles(): Promise; + open(options: PtyOpenOptions): Promise; + openWindow(): Promise; + dictation(): Promise; +} +/** The native side of `PtyApi`. `onData` and `onExit` receive the output of this session only. */ +export interface PtyTransport { + open(request: { id: string; cwd: string; cols: number; rows: number; profile?: string; directory?: string }, onData: (data: Uint8Array) => void, onExit: (code: number | null) => void): Promise; + write(id: string, data: string): Promise; + resize(id: string, cols: number, rows: number): Promise; + close(id: string): Promise; + profiles(): Promise; + openWindow(): Promise; + dictation(): Promise; +} +export interface FolderGrant { id: string; path: string; name: string } +export interface FolderEntry { name: string; size: number } +/** Folders outside the workspace that the user granted to this plugin. */ +export interface FilesApi { + readonly version: 1; + chooseFolder(options?: { title?: string }): Promise; + pictureFolder(name: string): Promise; + grants(): Promise; + revoke(grant: string): Promise; + list(grant: string): Promise; + readBytes(grant: string, name: string): Promise; + readSidecar(grant: string, name: string): Promise; + writeSidecar(grant: string, name: string, contents: string, expected: string | null): Promise; +} +/** The native side of `FilesApi`, bound to one plugin ID by the host. */ +export type FilesTransport = Omit; +export type ServiceMethods = Record unknown>; +/** Data that one plugin offers to other plugins in the same window. */ +export interface ServicesApi { + readonly version: 1; + provide(name: string, methods: ServiceMethods): { notify(): void; dispose(): void }; + get(plugin: string, name: string): Record Promise> | null; + subscribe(listener: (plugin: string, name: string) => void): Dispose; +} export interface PluginApi { + pty?: PtyApi; + files?: FilesApi; + services?: ServicesApi; backgrounds?: import("./backgroundContracts.ts").BackgroundApi; ui?: { showActionMenu(options: import("../ui/managedActionMenu.ts").MenuOptions): { close(): void } }; git?: import("../git/contracts.ts").GitApi; diff --git a/src/lib/plugins/services.ts b/src/lib/plugins/services.ts new file mode 100644 index 0000000..496fb23 --- /dev/null +++ b/src/lib/plugins/services.ts @@ -0,0 +1,76 @@ +import type { ServiceMethods } from "./sdk.ts"; + +const namePattern = /^[a-z][a-z0-9.-]{0,63}$/; + +/** + * Plugin services in one window. A provider plugin offers named methods, and other plugins call + * them through the host. Arguments and results are copied with `structuredClone`, so a later + * message-based SDK can keep the same contract. Calls always return promises. + */ +export class ServiceHub { + private services = new Map(); + private listeners = new Set<(plugin: string, name: string) => void>(); + + provide(owner: symbol, plugin: string, name: string, methods: ServiceMethods): { notify(): void; dispose(): void } { + if (!namePattern.test(name)) throw new Error("A service name uses lowercase letters, digits, dots, and hyphens, and starts with a letter."); + if (!methods || typeof methods !== "object" || !Object.keys(methods).length || Object.values(methods).some(method => typeof method !== "function")) { + throw new Error("A service needs an object of functions."); + } + const key = plugin + "/" + name; + if (this.services.has(key)) throw new Error("This plugin already provides the service."); + const entry = { owner, methods: { ...methods } }; + this.services.set(key, entry); + this.changed(plugin, name); + let active = true; + return { + notify: () => { if (active) this.changed(plugin, name); }, + dispose: () => { + if (!active) return; + active = false; + if (this.services.get(key) === entry) { this.services.delete(key); this.changed(plugin, name); } + }, + }; + } + + /** Return callable copies of the methods, or `null` when the service is not available. */ + get(plugin: string, name: string, alive: () => boolean): Record Promise> | null { + const key = plugin + "/" + name; + const entry = this.services.get(key); + if (!entry) return null; + const result: Record Promise> = {}; + for (const method of Object.keys(entry.methods)) { + result[method] = async (...args: unknown[]) => { + const current = this.services.get(key); + if (!alive()) throw new Error("This plugin is disabled."); + if (current !== entry) throw new Error("The service is no longer available."); + const value = await (entry.methods[method] as (...values: unknown[]) => unknown)(...structuredClone(args)); + if (!alive()) throw new Error("This plugin is disabled."); + if (this.services.get(key) !== entry) throw new Error("The service is no longer available."); + return structuredClone(value); + }; + } + return result; + } + + subscribe(listener: (plugin: string, name: string) => void): () => void { + this.listeners.add(listener); + return () => { this.listeners.delete(listener); }; + } + + removeOwner(owner: symbol) { + for (const [key, entry] of [...this.services]) { + if (entry.owner !== owner) continue; + this.services.delete(key); + const [plugin, name] = key.split("/"); + this.changed(plugin, name); + } + } + + private changed(plugin: string, name: string) { + for (const listener of [...this.listeners]) { + try { listener(plugin, name); } catch { /* One subscriber must not stop the others. */ } + } + } +} + +export const serviceHub = new ServiceHub(); diff --git a/tests/unit/plugins/pluginNativeApis.spec.ts b/tests/unit/plugins/pluginNativeApis.spec.ts new file mode 100644 index 0000000..7467e3f --- /dev/null +++ b/tests/unit/plugins/pluginNativeApis.spec.ts @@ -0,0 +1,156 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { ExternalSession, type SessionServices } from "../../../src/lib/plugins/externalSession.ts"; +import { ContributionRegistry } from "../../../src/lib/plugins/registry.ts"; +import { ServiceHub } from "../../../src/lib/plugins/services.ts"; +import type { FilesTransport, PluginApi, PtyTransport } from "../../../src/lib/plugins/sdk.ts"; + +const base: SessionServices = { + workspace: { list: async () => [], read: async () => "", write: async () => {} }, + settings: { read: async () => null, write: async () => {} }, assets: { read: async () => new Uint8Array() }, +}; + +async function start(id: string, services: Partial) { + let api!: PluginApi; + const session = new ExternalSession(id, { ...base, ...services }, () => {}, () => {}, new ContributionRegistry()); + await session.start({ activate(value) { api = value; } }); + return { api, session }; +} + +function fakePty() { + const calls: unknown[][] = []; + const outputs = new Map void; exit: (code: number | null) => void }>(); + let release: (() => void) | undefined; + const transport: PtyTransport & { hold(): void } = { + hold() { let done!: () => void; const wait = new Promise(resolve => { done = resolve; }); release = done; holding = wait; }, + open: async (request, data, exit) => { calls.push(["open", request]); outputs.set(request.id, { data, exit }); await holding; }, + write: async (id, data) => { calls.push(["write", id, data]); }, + resize: async (id, cols, rows) => { calls.push(["resize", id, cols, rows]); }, + close: async id => { calls.push(["close", id]); }, + profiles: async () => [{ id: "pwsh", title: "PowerShell 7", kind: "powershell" }], + openWindow: async () => { calls.push(["window"]); }, + dictation: async () => { calls.push(["dictation"]); }, + }; + let holding: Promise = Promise.resolve(); + return { transport, calls, outputs, release: () => release?.() }; +} + +test("terminal sessions deliver their own output and close when the plugin stops", async () => { + const pty = fakePty(); + const { api, session } = await start("org.test.terminal", { pty: pty.transport }); + assert.equal(api.pty!.version, 1); + assert.deepEqual(await api.pty!.profiles(), [{ id: "pwsh", title: "PowerShell 7", kind: "powershell" }]); + const received: string[] = []; + const exits: (number | null)[] = []; + const first = await api.pty!.open({ cwd: "C:/work", cols: 80, rows: 24, profile: "pwsh", onData: data => received.push(new TextDecoder().decode(data)), onExit: code => exits.push(code) }); + const second = await api.pty!.open({ cwd: "C:/work", cols: 80, rows: 24, onData: () => {} }); + assert.notEqual(first.id, second.id); + assert.deepEqual(pty.calls[0], ["open", { id: first.id, cwd: "C:/work", cols: 80, rows: 24, profile: "pwsh" }]); + pty.outputs.get(first.id)!.data(new TextEncoder().encode("ready")); + await first.write("dir\r"); + await first.resize(100, 30); + assert.deepEqual(received, ["ready"]); + assert.deepEqual(pty.calls.slice(-2), [["write", first.id, "dir\r"], ["resize", first.id, 100, 30]]); + assert.throws(() => first.resize(0, 30), /positive integers/); + // An exited session needs no close at shutdown. + pty.outputs.get(first.id)!.exit(0); + assert.deepEqual(exits, [0]); + await session.stop(); + assert.deepEqual(pty.calls.filter(call => call[0] === "close"), [["close", second.id]]); + pty.outputs.get(second.id)!.data(new TextEncoder().encode("late")); + assert.deepEqual(received, ["ready"]); + assert.throws(() => api.pty!.open({ cwd: "C:/work", cols: 80, rows: 24, onData: () => {} }), /disabled/); + assert.throws(() => api.pty!.openWindow(), /disabled/); + assert.throws(() => second.write("x"), /disabled/); + // Close stays safe after shutdown and is not repeated. + await second.close(); + assert.equal(pty.calls.filter(call => call[0] === "close").length, 1); +}); + +test("a terminal session that starts after shutdown is closed", async () => { + const pty = fakePty(); + const { api, session } = await start("org.test.terminal", { pty: pty.transport }); + pty.transport.hold(); + const opening = api.pty!.open({ cwd: "C:/work", cols: 80, rows: 24, onData: () => {} }); + const stopping = session.stop(); + pty.release(); + await assert.rejects(opening, /disabled/); + await stopping; + const id = (pty.calls[0][1] as { id: string }).id; + assert.deepEqual(pty.calls.filter(call => call[0] === "close"), [["close", id]]); +}); + +test("a closed terminal session rejects input and closes once", async () => { + const pty = fakePty(); + const { api } = await start("org.test.terminal", { pty: pty.transport }); + const output: string[] = []; + const terminal = await api.pty!.open({ cwd: "C:/work", cols: 80, rows: 24, onData: data => output.push(String(data.length)) }); + await Promise.all([terminal.close(), terminal.close()]); + assert.equal(pty.calls.filter(call => call[0] === "close").length, 1); + assert.throws(() => terminal.write("x"), /closed/); + pty.outputs.get(terminal.id)!.data(new Uint8Array([1])); + assert.deepEqual(output, []); + await assert.rejects(Promise.resolve().then(() => api.pty!.open({ cwd: "C:/work", cols: 80, rows: 24 } as never)), /onData/); +}); + +test("folder grant calls check shutdown before and after the native request", async () => { + const calls: unknown[][] = []; + let finish: ((value: unknown) => void) | undefined; + const grant = { id: "7f1b6f6e-3c39-4b55-9f3e-4a3a6d1d7c11", path: "C:/Pictures/RuneStone Backgrounds", name: "RuneStone Backgrounds" }; + const files: FilesTransport = { + chooseFolder: async options => { calls.push(["choose", options]); return grant; }, + pictureFolder: async name => { calls.push(["picture", name]); return grant; }, + grants: async () => [grant], + revoke: async id => { calls.push(["revoke", id]); return true; }, + list: () => new Promise(resolve => { finish = resolve as (value: unknown) => void; }), + readBytes: async (id, name) => { calls.push(["read", id, name]); return new Uint8Array([1, 2]); }, + readSidecar: async () => null, + writeSidecar: async (id, name, contents, expected) => { calls.push(["write", id, name, contents, expected]); }, + }; + const { api, session } = await start("org.test.slides", { files }); + assert.deepEqual(await api.files!.chooseFolder({ title: "Images" }), grant); + assert.deepEqual(await api.files!.pictureFolder("Backgrounds"), grant); + assert.deepEqual(await api.files!.readBytes(grant.id, "a.png"), new Uint8Array([1, 2])); + await api.files!.writeSidecar(grant.id, ".runestone-backgrounds.json", "{}", null); + assert.equal(await api.files!.revoke(grant.id), true); + assert.deepEqual(calls, [["choose", { title: "Images" }], ["picture", "Backgrounds"], ["read", grant.id, "a.png"], ["write", grant.id, ".runestone-backgrounds.json", "{}", null], ["revoke", grant.id]]); + assert.throws(() => api.files!.readBytes("", "a.png"), /grant ID/); + assert.throws(() => api.files!.writeSidecar(grant.id, ".runestone-a.json", "{}", undefined as never), /expected/); + const pending = api.files!.list(grant.id); + await session.stop(); + finish!([{ name: "a.png", size: 2 }]); + await assert.rejects(pending, /disabled/); + assert.throws(() => api.files!.grants(), /disabled/); +}); + +test("plugin services copy data, stop with their provider, and stop for a stopped consumer", async () => { + const serviceHub = new ServiceHub(); + const boards = [{ id: "b1", name: "Roadmap" }]; + const provider = await start("org.test.boards", { serviceHub }); + const consumer = await start("org.test.slides", { serviceHub }); + const changes: string[] = []; + consumer.api.services!.subscribe((plugin, name) => changes.push(`${plugin}/${name}`)); + assert.equal(consumer.api.services!.get("org.test.boards", "boards"), null); + const handle = provider.api.services!.provide("boards", { list: () => boards }); + assert.throws(() => provider.api.services!.provide("boards", { list: () => boards }), /already/); + assert.throws(() => provider.api.services!.provide("Bad Name", { list: () => boards }), /service name/); + const service = consumer.api.services!.get("org.test.boards", "boards")!; + const result = await service.list() as typeof boards; + assert.deepEqual(result, boards); + result[0].name = "Changed"; + assert.equal(boards[0].name, "Roadmap", "the consumer receives a copy"); + handle.notify(); + assert.deepEqual(changes, ["org.test.boards/boards", "org.test.boards/boards"]); + await provider.session.stop(); + assert.deepEqual(changes.at(-1), "org.test.boards/boards"); + await assert.rejects(service.list(), /no longer available/); + assert.equal(consumer.api.services!.get("org.test.boards", "boards"), null); + const again = await start("org.test.boards", { serviceHub }); + again.api.services!.provide("boards", { list: () => boards }); + const fresh = consumer.api.services!.get("org.test.boards", "boards")!; + await consumer.session.stop(); + await assert.rejects(fresh.list(), /disabled/); + const count = changes.length; + await again.session.stop(); + assert.equal(changes.length, count, "a stopped consumer receives no notifications"); +});