feat(plugins): add API 1.4 host services and window events

Цей коміт міститься в:
l0ng-ai committed 2026-11-09 07:47:23 +08:00
1 джерело 8dd29bad41
коміт d7edf8bded
165 files changed
+4014 -335

No files matched your search

Створено
+1
Переглянути файл
@@ -4598,6 +4598,7 @@ dependencies = [
"thiserror 2.0.21",
"tokio",
"tracing",
"url",
"wasmtime",
"wasmtime-wasi",
"wat",
+137 -5
Переглянути файл
@@ -32,8 +32,12 @@ pub enum Capability {
InputEvents,
/// The system clipboard, from the plugin's web views.
Clipboard,
/// HTTP(S) to one host (`*.example.com` matches subdomains).
/// HTTPS (and loopback HTTP) to one host (`*.example.com` matches subdomains).
Net(String),
/// Unencrypted HTTP to one host.
NetHttp(String),
/// A local socket or named pipe on the project machine.
Ipc(String),
/// Run one external program. Full code execution: never fine-grained.
Process(String),
/// Read files outside the project under one path.
@@ -62,10 +66,11 @@ impl Capability {
| Self::ProjectWrite
| Self::VcsWrite
| Self::Net(_)
| Self::NetHttp(_)
| Self::Secrets
| Self::InputEvents
| Self::Clipboard => Risk::Medium,
Self::Process(_) | Self::FsRead(_) | Self::FsWrite(_) => Risk::High,
Self::Ipc(_) | Self::Process(_) | Self::FsRead(_) | Self::FsWrite(_) => Risk::High,
}
}
@@ -92,6 +97,12 @@ impl Capability {
"Copy to the clipboard from its commands, and read and write it from its web views".into()
}
Self::Net(host) => format!("Connect to {host} (from the machine the project is on)"),
Self::NetHttp(host) => {
format!("Connect to {host} over unencrypted HTTP (from the machine the project is on)")
}
Self::Ipc(path) => {
format!("Connect to local socket {path} — equivalent to running arbitrary code on the project machine")
}
Self::Process(bin) => format!("Run {bin} — equivalent to running arbitrary code on this machine"),
Self::FsRead(path) => format!("Read files under {path}, outside the project"),
Self::FsWrite(path) => format!("Change files under {path}, outside the project"),
@@ -100,8 +111,14 @@ impl Capability {
/// Whether `self`, granted, also covers `wanted` (`net:*.x.com` covers `net:a.x.com`).
pub fn covers(&self, wanted: &Capability) -> bool {
if self == wanted {
return true;
}
match (self, wanted) {
(Self::Net(pattern), Self::Net(host)) => host_matches(pattern, host),
(Self::Ipc(pattern), Self::Ipc(path)) => ipc_matches(pattern, path),
(Self::Net(pattern), Self::Net(host)) | (Self::NetHttp(pattern), Self::NetHttp(host)) => {
host_matches(pattern, host)
}
(Self::FsRead(base), Self::FsRead(path)) | (Self::FsWrite(base), Self::FsWrite(path)) => {
std::path::Path::new(path).starts_with(std::path::Path::new(base))
}
@@ -120,6 +137,75 @@ pub fn host_matches(pattern: &str, host: &str) -> bool {
}
}
/// Validates a socket path; a grant may use `*` in its last segment only.
pub fn validate_ipc_name(name: &str, pattern: bool) -> Result<(), String> {
let pipe = name.starts_with(r"\\.\pipe\");
let unix = name.starts_with('/')
|| name.starts_with("~/")
|| name.starts_with("$TMPDIR/")
|| name.starts_with("$XDG_RUNTIME_DIR/");
let parts: Vec<_> = name.strip_prefix(r"\\.\pipe\").unwrap_or(name).split(if pipe { '\\' } else { '/' }).collect();
if !(pipe || unix)
|| name.contains(['\0', '?'])
|| name.len() > 4096
|| parts.last().is_none_or(|p| p.is_empty())
|| parts.iter().any(|p| matches!(*p, "." | ".."))
|| parts[..parts.len().saturating_sub(1)].iter().any(|p| p.contains('*'))
|| (!pattern && name.contains('*'))
{
return Err(
"ipc: use an absolute socket path or \\\\.\\pipe\\name; only the last grant segment may contain '*'".into(),
);
}
Ok(())
}
/// Expands the three supported host-local prefixes; no shell is involved.
pub fn expand_ipc_name(name: &str) -> Result<String, String> {
validate_ipc_name(name, true)?;
for (prefix, key) in [("~/", "HOME"), ("$TMPDIR/", "TMPDIR"), ("$XDG_RUNTIME_DIR/", "XDG_RUNTIME_DIR")] {
if let Some(rest) = name.strip_prefix(prefix) {
let base = std::env::var(key).map_err(|_| format!("{key} is not set"))?;
let expanded = format!("{}/{rest}", base.trim_end_matches('/'));
validate_ipc_name(&expanded, true)?;
return Ok(expanded);
}
}
Ok(name.into())
}
fn ipc_matches(pattern: &str, name: &str) -> bool {
let (Ok(pattern), Ok(name)) = (expand_ipc_name(pattern), expand_ipc_name(name)) else { return false };
if validate_ipc_name(&name, false).is_err() {
return false;
}
let separator = if pattern.starts_with(r"\\.\pipe\") { '\\' } else { '/' };
let (Some((parent, pattern)), Some((other, name))) = (pattern.rsplit_once(separator), name.rsplit_once(separator))
else {
return false;
};
if parent != other {
return false;
}
let mut rest = name;
let mut pieces = pattern.split('*');
let first = pieces.next().unwrap_or_default();
let Some(tail) = rest.strip_prefix(first) else { return false };
rest = tail;
let pieces: Vec<_> = pieces.collect();
if pieces.is_empty() {
return rest.is_empty();
}
for (i, piece) in pieces.iter().enumerate() {
if i + 1 == pieces.len() {
return rest.ends_with(piece);
}
let Some(at) = rest.find(piece) else { return false };
rest = &rest[at + piece.len()..];
}
true
}
impl fmt::Display for Capability {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
@@ -135,6 +221,8 @@ impl fmt::Display for Capability {
Self::InputEvents => f.write_str("events.input"),
Self::Clipboard => f.write_str("clipboard"),
Self::Net(h) => write!(f, "net:{h}"),
Self::NetHttp(h) => write!(f, "net.http:{h}"),
Self::Ipc(p) => write!(f, "ipc:{p}"),
Self::Process(b) => write!(f, "process:{b}"),
Self::FsRead(p) => write!(f, "fs.read:{p}"),
Self::FsWrite(p) => write!(f, "fs.write:{p}"),
@@ -153,7 +241,7 @@ impl FromStr for Capability {
return Err(format!("capability {s:?} needs a value after ':'"));
}
return match kind {
"net" => {
"net" | "net.http" => {
let host = arg.strip_prefix("*.").unwrap_or(arg);
let valid = !host.is_empty()
&& host.len() <= 253
@@ -162,7 +250,19 @@ impl FromStr for Capability {
&& label.len() <= 63
&& label.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
});
if valid { Ok(Self::Net(arg.to_ascii_lowercase())) } else { Err(format!("invalid host in {s:?}")) }
if valid {
Ok(if kind == "net" {
Self::Net(arg.to_ascii_lowercase())
} else {
Self::NetHttp(arg.to_ascii_lowercase())
})
} else {
Err(format!("invalid host in {s:?}"))
}
}
"ipc" => {
validate_ipc_name(arg, true)?;
Ok(Self::Ipc(arg.to_owned()))
}
"process" => {
if arg.contains(['/', '\\']) && !std::path::Path::new(arg).is_absolute() {
@@ -292,3 +392,35 @@ mod tests {
assert!(!Capability::FsRead("/etc".into()).covers(&Capability::FsRead("/etcx".into())));
}
}
#[cfg(test)]
mod api14_tests {
use super::*;
#[test]
fn http_grants_do_not_imply_https_and_socket_patterns_stay_in_one_directory() {
let http: Capability = "net.http:*.example.com".parse().unwrap();
assert_eq!(http.to_string(), "net.http:*.example.com");
assert_eq!(http.risk(), Risk::Medium);
assert!(http.describe().contains("unencrypted"));
assert!(http.covers(&"net.http:a.example.com".parse().unwrap()));
assert!(!http.covers(&"net:a.example.com".parse().unwrap()));
assert!(!"net:*.example.com".parse::<Capability>().unwrap().covers(&"net.http:a.example.com".parse().unwrap()));
let socket: Capability = "ipc:/tmp/discord-ipc-*-socket".parse().unwrap();
assert_eq!(socket.risk(), Risk::High);
assert!(socket.covers(&Capability::Ipc("/tmp/discord-ipc-42-socket".into())));
assert!(!socket.covers(&Capability::Ipc("/tmp/discord-ipc-dir/evil-socket".into())));
assert!(!socket.covers(&Capability::Ipc("/tmp/../tmp/discord-ipc-42-socket".into())));
assert_eq!("ipc:$TMPDIR/discord-ipc-*".parse::<Capability>().unwrap().to_string(), "ipc:$TMPDIR/discord-ipc-*");
assert!(
r"ipc:\\.\pipe\discord-*"
.parse::<Capability>()
.unwrap()
.covers(&Capability::Ipc(r"\\.\pipe\discord-0".into()))
);
for invalid in
["ipc:relative", "ipc:/tmp/*/socket", "ipc:/tmp/../socket", "ipc:/tmp/", "ipc:/tmp/socket?", "net.http:a b"]
{
assert!(invalid.parse::<Capability>().is_err(), "{invalid}");
}
}
}
+71
Переглянути файл
@@ -59,6 +59,12 @@ pub struct Grant {
/// `process:<program>` → the program confirmed for it.
#[serde(default)]
pub binaries: BTreeMap<String, BinaryGrant>,
/// Project root → process grant → the executable approved for that project.
#[serde(default)]
pub project_binaries: BTreeMap<PathBuf, BTreeMap<String, BinaryGrant>>,
/// Explicit global executable choices, retained for the next re-approval.
#[serde(default)]
pub program_choices: BTreeMap<String, PathBuf>,
/// Migrated from 0.1: capabilities not granted yet are asked for on first
/// use instead of blocking the plugin from loading.
#[serde(default)]
@@ -248,6 +254,9 @@ impl Ledger {
} else {
if let Capability::Process(_) = cap {
grant.binaries.remove(&s);
for binaries in grant.project_binaries.values_mut() {
binaries.remove(&s);
}
}
grant.granted.remove(&s)
}
@@ -260,6 +269,58 @@ impl Ledger {
}
}
/// The user's explicit global executable choice, if any.
pub fn program_choice(&self, subject: &Subject, cap: &Capability) -> Option<&Path> {
self.grants.get(subject)?.program_choices.get(&cap.to_string()).map(PathBuf::as_path)
}
/// Remembers or resets an explicit global executable choice after confirmation.
pub fn set_program_choice(&mut self, subject: &Subject, cap: &Capability, path: Option<&Path>) {
if let Some(grant) = self.grants.get_mut(subject) {
if let Some(path) = path {
grant.program_choices.insert(cap.to_string(), path.into());
} else {
grant.program_choices.remove(&cap.to_string());
}
}
}
/// Updates a project-specific program choice after user confirmation.
pub fn set_project_binary(
&mut self,
subject: &Subject,
cap: &Capability,
root: &Path,
binary: Option<BinaryGrant>,
) {
if let Some(grant) = self.grants.get_mut(subject) {
if let Some(binary) = binary {
grant.project_binaries.entry(root.into()).or_default().insert(cap.to_string(), binary);
} else if let Some(binaries) = grant.project_binaries.get_mut(root) {
binaries.remove(&cap.to_string());
}
}
}
/// The project override when present, otherwise the global approved program.
pub fn check_binary_in_project(
&self,
subject: &Subject,
cap: &Capability,
root: Option<&Path>,
) -> Result<PathBuf, String> {
let grant = self.grants.get(subject).ok_or_else(|| format!("{cap} was not granted"))?;
if !grant.has(cap) {
return Err(format!("{cap} was not granted"));
}
if let Some(bin) = root.and_then(|root| grant.project_binaries.get(root)).and_then(|b| b.get(&cap.to_string()))
{
return match file_hash(&bin.path) {
Ok(hash) if hash == bin.hash => Ok(bin.path.clone()),
_ => Err(format!("{} changed or is missing; confirm {cap} again", bin.path.display())),
};
}
self.check_binary(subject, cap)
}
/// Checks a `process:` grant at call time: the program confirmed for it,
/// unchanged since. Errors name what to do.
pub fn check_binary(&self, subject: &Subject, cap: &Capability) -> Result<PathBuf, String> {
@@ -306,6 +367,16 @@ pub fn by_risk(caps: &[Capability]) -> Vec<(Risk, Vec<Capability>)> {
groups.into_iter().map(|(r, v)| (r.0, v)).collect()
}
/// Pins an explicitly selected executable, retaining a multicall shim's filename.
pub fn approve_program(path: &Path) -> Result<BinaryGrant, String> {
if !path.is_absolute() || !is_executable(path) {
return Err("choose an absolute executable file".into());
}
let path = canonical_dir(path);
let hash = file_hash(&path).map_err(|e| e.to_string())?;
Ok(BinaryGrant { path, hash })
}
/// Resolves a `process:` program to an absolute path once, at grant time:
/// absolute names are taken as is, others are looked up in `path_var`.
/// The directory is canonicalized but the file name kept as found: `cargo`,
+1 -1
Переглянути файл
@@ -24,7 +24,7 @@ mod registry;
mod ui;
mod when;
pub use capability::{Capability, CapabilityInfo, Risk, host_matches};
pub use capability::{Capability, CapabilityInfo, Risk, expand_ipc_name, host_matches, validate_ipc_name};
pub use index::ContributionIndex;
pub use manifest::{
ActivationEvent, CATEGORIES, Capabilities, ENGINE_VERSION, EVENT_KINDS, LEGACY_API, MANIFEST_FILE, MAX_CATEGORIES,
+46 -3
Переглянути файл
@@ -32,7 +32,7 @@ use std::path::{Component, Path, PathBuf};
pub const MANIFEST_FILE: &str = "plugin.toml";
/// The plugin API (engine) version this host implements.
pub const ENGINE_VERSION: &str = "1.3.0";
pub const ENGINE_VERSION: &str = "1.4.0";
/// The 0.1 API, still accepted for contribution-only packages and 0.1 components.
pub const LEGACY_API: &str = "0.1";
/// Marketplace categories, in the order they are shown.
@@ -144,8 +144,17 @@ impl ActivationEvent {
/// Workbench event kinds (`on-event:<kind>`, WIT `events.event-kind`).
/// `scheduled` comes from `on-schedule` instead.
pub const EVENT_KINDS: &[&str] =
&["file-opened", "file-saved", "files-changed", "editor-focused", "action-performed", "vcs-changed"];
pub const EVENT_KINDS: &[&str] = &[
"file-closed",
"settings-changed",
"input-mode-changed",
"file-opened",
"file-saved",
"files-changed",
"editor-focused",
"action-performed",
"vcs-changed",
];
impl std::fmt::Display for ActivationEvent {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
@@ -317,6 +326,9 @@ impl Manifest {
check_relative(icon, "icon")?;
}
for cap in self.capabilities.required.iter().chain(&self.capabilities.optional) {
if matches!(cap, Capability::NetHttp(_) | Capability::Ipc(_)) {
self.needs_api(&format!("capability `{cap}`"), 4)?;
}
if matches!(cap, Capability::ProjectWrite | Capability::FsWrite(_)) {
self.needs_api(&format!("capability `{cap}`"), 3)?;
}
@@ -332,6 +344,10 @@ impl Manifest {
}
let mut seen = BTreeSet::new();
for event in &self.activation {
if matches!(event, ActivationEvent::Event(kind) if matches!(kind.as_str(), "file-closed" | "settings-changed" | "input-mode-changed"))
{
self.needs_api(&format!("`{event}`"), 4)?;
}
if matches!(event, ActivationEvent::Event(kind) if kind == "files-changed") {
self.needs_api("`on-event:files-changed`", 3)?;
}
@@ -655,3 +671,30 @@ mod tests {
assert!(!engine_compatible("0.10", true));
}
}
#[cfg(test)]
mod api14_tests {
use super::*;
#[test]
fn new_capabilities_and_activations_require_api_1_4() {
for declaration in [
"[capabilities]\nrequired = [\"net.http:example.com\"]",
"[capabilities]\noptional = [\"ipc:$TMPDIR/test-*\"]",
"activation = [\"on-event:file-closed\"]",
"activation = [\"on-event:settings-changed\"]",
"activation = [\"on-event:input-mode-changed\"]",
] {
for engine in ["^1.0", "^1.3", "^1.4"] {
let manifest = format!(
"id = 'test'\nname = 'Test'\nversion = '0.1.0'\nwasm = 'plugin.wasm'\nengines.openidea = '{engine}'\n{declaration}\n"
);
let parsed = Manifest::parse(&manifest);
if engine == "^1.4" {
parsed.unwrap();
} else {
assert!(parsed.unwrap_err().contains("new in plugin API 1.4"));
}
}
}
}
}
+397 -17
Переглянути файл
@@ -4,6 +4,7 @@
use super::{CommitAnswer, CommitRequest, CommitSelection, PluginContextKey, PluginEvent, PluginEventSink};
use ide_core::ipc_path::to_ipc;
use ide_core::{CancellationToken, TextEdit};
use ide_extension::Capability;
use ide_extension::Package;
use ide_language::ProgramPin;
use ide_plugin::{
@@ -157,6 +158,34 @@ pub(super) fn net_runtime() -> &'static tokio::runtime::Runtime {
})
}
#[derive(Debug)]
struct RedirectDenied(String);
impl std::fmt::Display for RedirectDenied {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} is not granted for this redirect", self.0)
}
}
impl std::error::Error for RedirectDenied {}
fn network_error(error: reqwest::Error) -> HostError {
let mut source: Option<&(dyn std::error::Error + 'static)> = Some(&error);
while let Some(e) = source {
if let Some(denied) = e.downcast_ref::<RedirectDenied>() {
return HostError::Denied(denied.0.clone());
}
source = e.source();
}
HostError::Failed(error.to_string())
}
fn redirect_capability(from: &reqwest::Url, to: &reqwest::Url) -> Result<Capability, String> {
if from.scheme() == "https" && to.scheme() == "http" {
ide_plugin::net_host(to.as_str()).map(Capability::NetHttp)
} else {
ide_plugin::net_capability(to.as_str())
}
}
/// Replaces `{{secret:<name>}}` in `value` with the plugin's secrets.
fn fill_secrets(value: &str, lookup: impl Fn(&str) -> Option<String>) -> Result<String, HostError> {
let mut out = String::with_capacity(value.len());
@@ -191,6 +220,7 @@ struct PromptEntry {
enum Waiter {
Prompt(std::sync::mpsc::SyncSender<Option<Vec<String>>>),
Commit(std::sync::mpsc::SyncSender<CommitAnswer>),
Command(std::sync::mpsc::SyncSender<super::CommandAnswer>),
}
/// A process a plugin started and has not released (API 1.3 `process.start`).
@@ -405,6 +435,11 @@ fn append_process_env(command: &mut StdCommand, env: &[(String, String)]) -> Res
Ok(())
}
/// Approved project-specific programs.
pub(super) type ProjectPins = Arc<RwLock<HashMap<(String, String, PathBuf), ProgramPin>>>;
type SettingSnapshots = BTreeMap<(Option<String>, String), BTreeMap<String, String>>;
/// State shared by the host and every plugin's [`PluginApi`].
pub(super) struct Shared {
pub sink: Arc<dyn PluginEventSink>,
@@ -416,13 +451,18 @@ pub(super) struct Shared {
/// (plugin, handle id) → the processes it started and has not released.
processes: Mutex<HashMap<(String, u64), Arc<Proc>>>,
next_process: AtomicU64,
connections: super::ipc::Connections,
pub loopbacks: RwLock<Arc<dyn super::auth::Service>>,
process_shutdowns: Mutex<Vec<std::thread::JoinHandle<()>>>,
prompts: Mutex<HashMap<u64, PromptEntry>>,
/// Plugins being stopped: their calls may not open new prompts (taken before `prompts`).
prompts_blocked: Mutex<BTreeSet<String>>,
next_prompt: AtomicU64,
/// (plugin, item id) → item, for windows opened later.
output: Mutex<BTreeMap<(String, String), String>>,
status: Mutex<BTreeMap<(String, String), StatusItem>>,
setting_snapshots: Mutex<SettingSnapshots>,
window_status: Mutex<BTreeMap<(String, String, String), StatusItem>>,
/// (scope, plugin, key) → JSON value.
contexts: Mutex<BTreeMap<ContextKey, String>>,
closed_clients: Mutex<BTreeSet<String>>,
@@ -433,6 +473,8 @@ pub(super) struct Shared {
pub secrets: RwLock<Arc<dyn SecretStore>>,
/// (plugin, `process:` capability) → the approved program.
pub pins: Arc<RwLock<HashMap<(String, String), ProgramPin>>>,
pub project_pins: ProjectPins,
pub event_editors: RwLock<HashMap<String, ide_plugin::EditorContext>>,
/// Validated UI declarations (settings schemas, declared views).
pub ui: Arc<ide_extension::UiStore>,
/// The UI language the windows report (BCP 47).
@@ -463,16 +505,23 @@ impl Shared {
workspace: RwLock::new(None),
secrets: RwLock::new(Arc::new(FileSecretStore { dir: data_dir.clone() })),
pins,
project_pins: Arc::default(),
event_editors: RwLock::default(),
data_dir,
tasks: Mutex::default(),
next_task: AtomicU64::new(1),
processes: Mutex::default(),
next_process: AtomicU64::new(1),
connections: super::ipc::Connections::default(),
loopbacks: RwLock::new(Arc::new(super::auth::Loopbacks::default())),
process_shutdowns: Mutex::default(),
prompts: Mutex::default(),
prompts_blocked: Mutex::default(),
next_prompt: AtomicU64::new(1),
status: Mutex::default(),
output: Mutex::default(),
window_status: Mutex::default(),
setting_snapshots: Mutex::default(),
contexts: Mutex::default(),
closed_clients: Mutex::default(),
subscriptions: Mutex::default(),
@@ -518,6 +567,45 @@ impl Shared {
self.status.lock().iter().map(|((p, id), item)| (p.clone(), id.clone(), item.clone())).collect()
}
pub fn changed_settings(self: &Arc<Self>, pkg: &Package, client: Option<&str>) -> Vec<String> {
let root = client.and_then(|c| self.project_of(c));
let api = PluginApi { pkg: pkg.clone(), shared: self.clone() };
let mut current = BTreeMap::new();
for item in self.ui.items(super::ui_points::SETTINGS, Some(pkg.id())) {
if let Some(properties) = item.decl.get("properties").and_then(|p| p.as_array()) {
for property in properties {
if let Some(key) = property.get("key").and_then(|k| k.as_str())
&& let Some(value) = api.setting(root.as_deref(), key)
{
current.insert(key.into(), value);
}
}
}
}
let previous =
self.setting_snapshots.lock().insert((client.map(str::to_owned), pkg.id().into()), current.clone());
previous
.map(|old| current.into_iter().filter(|(k, v)| old.get(k) != Some(v)).map(|(k, _)| k).collect())
.unwrap_or_default()
}
pub fn status_snapshot(&self, client: &str) -> Vec<super::PluginStatusItem> {
let mut items: Vec<_> = self
.status_items()
.into_iter()
.map(|(plugin_id, id, item)| super::PluginStatusItem { plugin_id, id, item, window: false })
.collect();
items.extend(self.window_status.lock().iter().filter(|((w, ..), _)| w == client).map(
|((_, plugin_id, id), item)| super::PluginStatusItem {
plugin_id: plugin_id.clone(),
id: id.clone(),
item: item.clone(),
window: true,
},
));
items
}
pub fn context_keys(&self, client: Option<&str>) -> Vec<PluginContextKey> {
let contexts = self.contexts.lock();
let mut keys: BTreeMap<(&str, &str), &str> = BTreeMap::new();
@@ -542,6 +630,10 @@ impl Shared {
self.prompts.lock().retain(|_, entry| entry.client != client);
drop(closed);
self.contexts.lock().retain(|(scope, ..), _| scope.as_deref() != Some(client));
self.loopbacks.read().forget_window(client);
self.window_status.lock().retain(|(window, ..), _| window != client);
self.event_editors.write().remove(client);
self.setting_snapshots.lock().retain(|(window, _), _| window.as_deref() != Some(client));
let mine: Vec<_> = {
let mut processes = self.processes.lock();
let keys: Vec<_> = processes
@@ -598,6 +690,21 @@ impl Shared {
/// subscriptions go only with `subscriptions`, as they survive restarts.
pub fn clear_plugin(&self, plugin: &str, subscriptions: bool) {
self.kill_processes(plugin);
self.connections.clear(plugin);
self.setting_snapshots.lock().retain(|(_, p), _| p != plugin);
let channels: Vec<_> = {
let mut output = self.output.lock();
let keys: Vec<_> = output.keys().filter(|(p, _)| p == plugin).cloned().collect();
for key in &keys {
output.remove(key);
}
keys
};
for (_, channel) in channels {
self.sink.emit(None, PluginEvent::OutputChanged { plugin_id: plugin.into(), channel, text: None });
}
self.loopbacks.read().clear(plugin);
let removed: Vec<String> = {
let mut status = self.status.lock();
let ids: Vec<String> = status.keys().filter(|(p, _)| p == plugin).map(|(_, id)| id.clone()).collect();
@@ -609,6 +716,18 @@ impl Shared {
for id in removed {
self.sink.emit(None, PluginEvent::StatusItemChanged { plugin_id: plugin.to_owned(), id, item: None });
}
let removed: Vec<_> = {
let mut items = self.window_status.lock();
let keys: Vec<_> = items.keys().filter(|(_, p, _)| p == plugin).cloned().collect();
for key in &keys {
items.remove(key);
}
keys
};
for (window, _, id) in removed {
self.sink
.emit(Some(&window), PluginEvent::WindowStatusItemChanged { plugin_id: plugin.into(), id, item: None });
}
self.withdraw_prompts(plugin);
let removed: Vec<(Option<String>, String)> = {
let mut contexts = self.contexts.lock();
@@ -699,6 +818,16 @@ impl Shared {
}
/// A window answered a [`CommitRequest`].
pub fn answer_command(&self, client: &str, id: u64, answer: super::CommandAnswer) -> bool {
let mut prompts = self.prompts.lock();
if !matches!(prompts.get(&id), Some(PromptEntry { client: window, answer: Waiter::Command(_), .. }) if window == client)
{
return false;
}
let Some(PromptEntry { answer: Waiter::Command(tx), .. }) = prompts.remove(&id) else { return false };
tx.try_send(answer).is_ok()
}
pub fn answer_commit(&self, id: u64, answer: CommitAnswer) -> bool {
let mut prompts = self.prompts.lock();
if !matches!(prompts.get(&id), Some(PromptEntry { answer: Waiter::Commit(_), .. })) {
@@ -802,7 +931,17 @@ impl PluginApi {
/// The program approved for the (already checked) `process:` grant,
/// verified right before it starts.
#[cfg(test)]
fn approved_program(&self, program: &str) -> Result<PathBuf, HostError> {
self.approved_program_in_project(program, None)
}
fn approved_program_in_project(&self, program: &str, root: Option<&Path>) -> Result<PathBuf, HostError> {
if let Some(pin) = root.and_then(|root| {
self.shared.project_pins.read().get(&(self.id().into(), format!("process:{program}"), root.into())).cloned()
}) {
return pin.verify().map(Path::to_path_buf).map_err(|e| HostError::Denied(e.to_string()));
}
let cap = format!("process:{program}");
// Granted without a pinned file: the program wasn't found when it was
// allowed, and installing it later approves nothing by itself.
@@ -828,7 +967,7 @@ impl PluginApi {
cancel: &CancellationToken,
on_line: &dyn Fn(super::PluginOutputLine),
) -> Result<Option<i32>, HostError> {
let binary = self.approved_program(program)?;
let binary = self.approved_program_in_project(program, cwd)?;
let cwd = cwd.map(Path::to_path_buf).unwrap_or_else(|| self.shared.data_dir.join(self.id()));
let _ = std::fs::create_dir_all(&cwd);
let mut cmd = std::process::Command::new(&binary);
@@ -1051,6 +1190,108 @@ fn failed(e: impl std::fmt::Display) -> HostError {
}
impl HostApi for PluginApi {
fn execute_command(
&self,
invocation: &ide_plugin::Invocation,
id: &str,
arg: Option<String>,
cancel: &CancellationToken,
timeout: Duration,
) -> Result<Option<String>, HostError> {
let client = from_window(invocation.client.as_deref(), "execute commands")?;
let mut chain = invocation.command_chain.clone();
chain.push(self.id().into());
if chain.len() > 8 {
return Err(HostError::Invalid("command nesting limit (8)".into()));
}
for command in self.shared.ui.items(super::COMMANDS, None) {
if id == format!("plugin.{}.{}", command.plugin_id, command.key) && chain.contains(&command.plugin_id) {
return Err(HostError::Invalid("recursive plugin command".into()));
}
}
let request = self.shared.next_prompt.fetch_add(1, Ordering::Relaxed);
let (tx, rx) = std::sync::mpsc::sync_channel(1);
{
let closed = self.shared.closed_clients.lock();
let blocked = self.shared.prompts_blocked.lock();
if closed.contains(client) || blocked.contains(self.id()) {
return Err(HostError::Cancelled);
}
self.shared.prompts.lock().insert(
request,
PromptEntry { plugin: self.id().into(), client: client.into(), answer: Waiter::Command(tx) },
);
}
self.shared.sink.emit(
Some(client),
PluginEvent::ExecuteCommand { request_id: request.to_string(), id: id.into(), arg, chain },
);
let deadline = Instant::now() + timeout;
loop {
match rx.recv_timeout(Duration::from_millis(20)) {
Ok(super::CommandAnswer::Value(value)) => return Ok(value),
Ok(super::CommandAnswer::NotFound) => return Err(HostError::NotFound(id.into())),
Ok(super::CommandAnswer::Failed(error)) => return Err(HostError::Failed(error)),
Err(std::sync::mpsc::RecvTimeoutError::Timeout)
if !cancel.is_cancelled() && Instant::now() < deadline => {}
Err(_) => {
self.shared.prompts.lock().remove(&request);
return Err(HostError::Cancelled);
}
}
}
}
fn output_write(&self, channel: &str, text: Option<&str>) -> Result<(), HostError> {
if channel.is_empty() || channel.len() > 128 || channel.chars().any(char::is_control) {
return Err(HostError::Invalid("output channel must be 1-128 bytes without control characters".into()));
}
let key = (self.id().to_owned(), channel.to_owned());
let mut channels = self.shared.output.lock();
if !channels.contains_key(&key) && channels.keys().filter(|(p, _)| p == self.id()).count() >= 32 {
return Err(HostError::Invalid("at most 32 output channels".into()));
}
let buffer = channels.entry(key).or_default();
if let Some(text) = text {
let mut start = text.len().saturating_sub(1 << 20);
while !text.is_char_boundary(start) {
start += 1;
}
buffer.push_str(&text[start..]);
} else {
buffer.clear();
}
let mut remove = buffer.len().saturating_sub(1 << 20);
while !buffer.is_char_boundary(remove) {
remove += 1;
}
buffer.drain(..remove);
let text = buffer.clone();
drop(channels);
self.shared.sink.emit(
None,
PluginEvent::OutputChanged { plugin_id: self.id().into(), channel: channel.into(), text: Some(text) },
);
Ok(())
}
fn output_reveal(&self, client: &str, channel: &str) -> Result<(), HostError> {
let key = (self.id().to_owned(), channel.to_owned());
if !self.shared.output.lock().contains_key(&key) {
self.output_write(channel, None)?;
}
if self.shared.client_closed(client) {
return Err(HostError::Cancelled);
}
let text = self.shared.output.lock().get(&key).cloned().unwrap_or_default();
self.shared.sink.emit(
Some(client),
PluginEvent::RevealOutput { plugin_id: self.id().into(), channel: channel.into(), text },
);
Ok(())
}
fn require_api(&self, what: &str, minor: u64) -> Result<(), HostError> {
self.pkg.manifest.needs_api(what, minor).map_err(HostError::Invalid)
}
fn notify(
&self,
client: Option<&str>,
@@ -1202,6 +1443,32 @@ impl HostApi for PluginApi {
.emit(None, PluginEvent::StatusItemChanged { plugin_id: self.id().to_owned(), id: id.to_owned(), item });
}
fn window_status_item(&self, client: &str, id: &str, item: Option<StatusItem>) -> Result<(), HostError> {
let closed = self.shared.closed_clients.lock();
let blocked = self.shared.prompts_blocked.lock();
if closed.contains(client) || blocked.contains(self.id()) {
return Err(HostError::Cancelled);
}
let key = (client.to_owned(), self.id().to_owned(), id.to_owned());
let mut items = self.shared.window_status.lock();
if let Some(item) = &item {
if !items.contains_key(&key)
&& items.keys().filter(|(w, p, _)| w == client && p == self.id()).count() >= MAX_STATUS_ITEMS
{
return Err(HostError::Invalid("too many window status items".into()));
}
items.insert(key, item.clone());
} else {
items.remove(&key);
}
drop(items);
self.shared.sink.emit(
Some(client),
PluginEvent::WindowStatusItemChanged { plugin_id: self.id().into(), id: id.into(), item },
);
Ok(())
}
fn set_context(&self, client: Option<&str>, key: &str, value: Option<String>) -> Result<(), HostError> {
let map_key = (client.map(str::to_owned), self.id().to_owned(), key.to_owned());
{
@@ -1419,25 +1686,32 @@ impl HostApi for PluginApi {
}
let method = reqwest::Method::from_bytes(request.method.to_ascii_uppercase().as_bytes())
.map_err(|_| HostError::Invalid(format!("method {:?}", request.method)))?;
let client = ide_http::client::shared().map_err(|e| HostError::Failed(e.message))?;
// A redirect to another host is refused after the fact (the shared
// client follows redirects).
let grants = request.grants.clone();
let policy = reqwest::redirect::Policy::custom(move |attempt| {
if attempt.previous().len() >= 10 {
return attempt.error("too many redirects");
}
let wanted = attempt.previous().last().map_or_else(
|| ide_plugin::net_capability(attempt.url().as_str()),
|from| redirect_capability(from, attempt.url()),
);
match wanted {
Ok(wanted) if grants.iter().any(|g| g.covers(&wanted)) => attempt.follow(),
Ok(wanted) => attempt.error(RedirectDenied(wanted.to_string())),
Err(error) => attempt.error(error),
}
});
let client = ide_http::client::build_with_redirect(&ide_core::proxy_settings::proxy(), policy)
.map_err(|e| HostError::Failed(e.message))?;
let builder = client.request(method, &request.url).headers(headers).timeout(request.timeout);
let builder = match request.body {
Some(body) => builder.body(body),
None => builder,
};
let cancel = cancel.clone();
let host = ide_plugin::net_host(&request.url).map_err(HostError::Invalid)?;
net_runtime().block_on(async move {
let send = async {
let response = builder.send().await.map_err(|e| HostError::Failed(e.to_string()))?;
if ide_plugin::net_host(response.url().as_str()).ok().as_deref() != Some(host.as_str()) {
return Err(HostError::Denied(format!(
"net:{} (redirected)",
response.url().host_str().unwrap_or("?")
)));
}
let response = builder.send().await.map_err(network_error)?;
let status = response.status().as_u16();
let headers = response
.headers()
@@ -1465,6 +1739,55 @@ impl HostApi for PluginApi {
self.shared.secrets.read().get(self.id(), name).is_some()
}
fn secret_set(&self, name: &str, value: Option<&str>) -> Result<(), HostError> {
if !self.shared.ui.items(super::providers::SECRETS_POINT, Some(self.id())).iter().any(|s| s.key == name) {
return Err(HostError::NotFound(format!("undeclared secret {name:?}")));
}
self.shared.secrets.read().set(self.id(), name, value).map_err(HostError::Failed)
}
fn begin_loopback(&self, client: &str, path: &str) -> Result<(u64, String), HostError> {
let closed = self.shared.closed_clients.lock();
let blocked = self.shared.prompts_blocked.lock();
if closed.contains(client) || blocked.contains(self.id()) {
return Err(HostError::Cancelled);
}
self.shared.loopbacks.read().begin(self.id(), client, path)
}
fn wait_loopback(
&self,
id: u64,
timeout: Duration,
cancel: &CancellationToken,
) -> Result<Option<String>, HostError> {
self.shared.loopbacks.read().clone().wait(self.id(), id, timeout, cancel)
}
fn close_loopback(&self, id: u64) {
self.shared.loopbacks.read().close(self.id(), id);
}
fn ipc_connect(&self, name: &str, cancel: &CancellationToken, timeout: Duration) -> Result<u64, HostError> {
self.shared.connections.connect(self.id(), name, cancel, timeout)
}
fn ipc_write(
&self,
id: u64,
bytes: Vec<u8>,
cancel: &CancellationToken,
timeout: Duration,
) -> Result<(), HostError> {
self.shared.connections.write(self.id(), id, bytes, cancel, timeout)
}
fn ipc_read(
&self,
id: u64,
max: usize,
timeout: Duration,
cancel: &CancellationToken,
) -> Result<Vec<u8>, HostError> {
self.shared.connections.read(self.id(), id, max, timeout, cancel)
}
fn ipc_close(&self, id: u64) {
self.shared.connections.close(self.id(), id);
}
fn run_process(
&self,
cmd: ProcessCommand,
@@ -1473,7 +1796,7 @@ impl HostApi for PluginApi {
cancel: &CancellationToken,
timeout: Duration,
) -> Result<ProcessOutput, HostError> {
let binary = self.approved_program(&cmd.program)?;
let binary = self.approved_program_in_project(&cmd.program, cwd.or(cmd.approval_root.as_deref()))?;
let cwd = self.spawn_dir(cwd);
let mut command = StdCommand::new(&binary);
ide_core::process::prepare(&mut command);
@@ -1554,7 +1877,7 @@ impl HostApi for PluginApi {
}
}
fn start_process(&self, cmd: ProcessCommand, cwd: Option<&Path>, client: Option<&str>) -> Result<u64, HostError> {
let binary = self.approved_program(&cmd.program)?;
let binary = self.approved_program_in_project(&cmd.program, cwd.or(cmd.approval_root.as_deref()))?;
let cwd = self.spawn_dir(cwd);
if client.is_some_and(|c| self.shared.closed_clients.lock().contains(c)) {
return Err(HostError::Cancelled);
@@ -1777,7 +2100,7 @@ impl HostApi for PluginApi {
args: Vec<String>,
cwd: Option<&Path>,
) -> Result<(), HostError> {
let binary = self.approved_program(program)?;
let binary = self.approved_program_in_project(program, cwd)?;
let cwd = cwd.map(Path::to_path_buf).unwrap_or_else(|| self.shared.data_dir.join(self.id()));
let _ = std::fs::create_dir_all(&cwd);
let event = PluginEvent::OpenTerminal {
@@ -1810,7 +2133,7 @@ impl HostApi for PluginApi {
log: ide_plugin::ServiceLog,
) -> Result<(), HostError> {
// Fails now, rather than in the tab, when the approved file is gone or changed.
self.approved_program(&log.program)?;
self.approved_program_in_project(&log.program, self.shared.project_of(client).as_deref())?;
{
let mut all = self.shared.log_tabs.lock();
let tabs = all.entry((self.id().to_owned(), client.to_owned())).or_default();
@@ -2338,7 +2661,12 @@ mod tests {
#[cfg(unix)]
fn shell(script: &str) -> ProcessCommand {
ProcessCommand { program: "sh".into(), args: vec!["-c".into(), script.into()], env: Vec::new() }
ProcessCommand {
program: "sh".into(),
args: vec!["-c".into(), script.into()],
env: Vec::new(),
approval_root: None,
}
}
#[cfg(unix)]
@@ -2451,6 +2779,58 @@ mod tests {
matches!(api.approved_program("lint"), Err(HostError::Denied(e)) if e.contains("changed since it was approved"))
);
}
#[test]
fn redirects_check_grants_before_connecting_and_downgrades_require_http() {
assert_eq!(
redirect_capability(&"https://localhost/start".parse().unwrap(), &"http://localhost/end".parse().unwrap())
.unwrap(),
Capability::NetHttp("localhost".into())
);
let source = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let target = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
target.set_nonblocking(true).unwrap();
let source_port = source.local_addr().unwrap().port();
let target_port = target.local_addr().unwrap().port();
let worker = std::thread::spawn(move || {
use std::io::{Read, Write};
let (mut stream, _) = source.accept().unwrap();
let mut buf = [0; 4096];
let _ = stream.read(&mut buf);
write!(stream, "HTTP/1.1 302 Found\r\nLocation: http://127.0.0.1:{target_port}/\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").unwrap();
});
let dir = tempfile::tempdir().unwrap();
let api = api(dir.path(), Arc::default());
let result = api.fetch(
HttpRequest {
method: "GET".into(),
url: format!("http://localhost:{source_port}/"),
headers: Vec::new(),
body: None,
timeout: Duration::from_secs(2),
grants: vec![Capability::Net("localhost".into())],
},
&CancellationToken::new(),
);
assert!(matches!(result, Err(HostError::Denied(cap)) if cap == "net:127.0.0.1"));
assert!(target.accept().is_err(), "ungranted target must never receive a connection");
worker.join().unwrap();
}
#[test]
fn output_ring_keeps_utf8_and_is_withdrawn_on_stop() {
let dir = tempfile::tempdir().unwrap();
let api = api(dir.path(), Arc::default());
api.output_write("build", Some(&"😀".repeat(300_000))).unwrap();
let buffer = api.shared.output.lock().get(&(api.id().into(), "build".into())).cloned().unwrap();
assert_eq!(buffer.len(), 1 << 20);
api.output_write("build", Some("x")).unwrap();
let buffer = api.shared.output.lock().get(&(api.id().into(), "build".into())).cloned().unwrap();
assert!(buffer.len() <= 1 << 20 && buffer.ends_with('x'));
api.output_write("build", None).unwrap();
assert!(api.shared.output.lock().get(&(api.id().into(), "build".into())).unwrap().is_empty());
api.shared.clear_plugin(api.id(), true);
assert!(api.shared.output.lock().is_empty());
}
}
/// The window a user action invoked the plugin from: browser tabs and clipboard writes
+205
Переглянути файл
@@ -0,0 +1,205 @@
//! One-shot OAuth redirects, always bound on the desktop's IPv4 loopback.
use ide_core::CancellationToken;
use ide_plugin::HostError;
use parking_lot::Mutex;
use std::collections::HashMap;
use std::io::{Read, Write};
use std::net::{Ipv4Addr, TcpListener, TcpStream};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
pub(super) trait Service: Send + Sync {
fn begin(&self, plugin: &str, window: &str, path: &str) -> Result<(u64, String), HostError>;
fn wait(
&self,
plugin: &str,
id: u64,
timeout: Duration,
cancel: &CancellationToken,
) -> Result<Option<String>, HostError>;
fn close(&self, plugin: &str, id: u64);
fn clear(&self, plugin: &str);
fn forget_window(&self, window: &str);
}
struct Entry {
window: String,
path: String,
listener: Mutex<Option<TcpListener>>,
cancel: CancellationToken,
}
#[derive(Default)]
pub(super) struct Loopbacks {
next: AtomicU64,
entries: Mutex<HashMap<(String, u64), Arc<Entry>>>,
}
fn failed(e: impl std::fmt::Display) -> HostError {
HostError::Failed(e.to_string())
}
fn respond(stream: &mut TcpStream, ok: bool) {
let body = if ok { "You can close this tab." } else { "Not found." };
let status = if ok { "200 OK" } else { "404 Not Found" };
let _ = write!(
stream,
"HTTP/1.1 {status}\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\nCache-Control: no-store\r\n\r\n{body}",
body.len()
);
}
impl Loopbacks {
fn remove_where(&self, predicate: impl Fn(&str, &Entry) -> bool) {
self.entries.lock().retain(|(p, _), entry| {
if !predicate(p, entry) {
return true;
}
entry.cancel.cancel();
entry.listener.lock().take();
false
});
}
}
impl Service for Loopbacks {
fn begin(&self, plugin: &str, window: &str, path: &str) -> Result<(u64, String), HostError> {
let path = path.trim_start_matches('/');
if path.len() > 1024
|| path.bytes().any(|b| !(b.is_ascii_alphanumeric() || b"/-._~".contains(&b)))
|| path.split('/').any(|s| matches!(s, "." | ".."))
{
return Err(HostError::Invalid("loopback path must be a URL path without query or fragment".into()));
}
let mut entries = self.entries.lock();
if entries.keys().filter(|(p, _)| p == plugin).count() >= 2 {
return Err(HostError::Invalid("at most two open loopbacks per plugin".into()));
}
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).map_err(failed)?;
listener.set_nonblocking(true).map_err(failed)?;
let uri = format!("http://127.0.0.1:{}/{path}", listener.local_addr().map_err(failed)?.port());
let id = self.next.fetch_add(1, Ordering::Relaxed);
entries.insert(
(plugin.into(), id),
Arc::new(Entry {
window: window.into(),
path: format!("/{path}"),
listener: Mutex::new(Some(listener)),
cancel: CancellationToken::new(),
}),
);
Ok((id, uri))
}
fn wait(
&self,
plugin: &str,
id: u64,
timeout: Duration,
cancel: &CancellationToken,
) -> Result<Option<String>, HostError> {
let entry = self
.entries
.lock()
.get(&(plugin.into(), id))
.cloned()
.ok_or_else(|| HostError::NotFound("loopback".into()))?;
let listener =
entry.listener.lock().take().ok_or_else(|| HostError::Invalid("loopback already awaited".into()))?;
let deadline = Instant::now() + timeout;
let result = (|| loop {
if cancel.is_cancelled() || entry.cancel.is_cancelled() {
return Err(HostError::Cancelled);
}
match listener.accept() {
Ok((mut stream, address)) => {
if !address.ip().is_loopback() {
continue;
}
stream.set_nonblocking(true).map_err(failed)?;
let mut head = Vec::new();
loop {
if cancel.is_cancelled() || entry.cancel.is_cancelled() {
return Err(HostError::Cancelled);
}
if Instant::now() >= deadline {
return Ok(None);
}
let mut buf = [0; 1024];
match stream.read(&mut buf) {
Ok(0) => break,
Ok(n) => {
head.extend_from_slice(&buf[..n]);
if head.windows(4).any(|w| w == b"\r\n\r\n") || head.len() > 8192 {
break;
}
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
std::thread::sleep(Duration::from_millis(5))
}
Err(e) => return Err(failed(e)),
}
}
let line = std::str::from_utf8(&head).unwrap_or_default().lines().next().unwrap_or_default();
let target = line.strip_prefix("GET ").and_then(|s| s.split_once(' ')).map(|(target, _)| target);
let query = target.and_then(|target| {
let (path, query) = target.split_once('?').unwrap_or((target, ""));
(path == entry.path && head.len() <= 8192).then(|| query.to_owned())
});
stream.set_nonblocking(false).map_err(failed)?;
stream.set_write_timeout(Some(Duration::from_millis(100))).map_err(failed)?;
respond(&mut stream, query.is_some());
if query.is_some() {
return Ok(query);
}
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
Err(e) => return Err(failed(e)),
}
if Instant::now() >= deadline {
return Ok(None);
}
std::thread::sleep(Duration::from_millis(5));
})();
self.close(plugin, id);
result
}
fn close(&self, plugin: &str, id: u64) {
let entry = self.entries.lock().remove(&(plugin.into(), id));
if let Some(entry) = entry {
entry.cancel.cancel();
entry.listener.lock().take();
}
}
fn clear(&self, plugin: &str) {
self.remove_where(|p, _| p == plugin || p.starts_with("remote:") && p.ends_with(&format!(":{plugin}")));
}
fn forget_window(&self, window: &str) {
self.remove_where(|_, entry| entry.window == window);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn one_shot_raw_query_limits_timeout_and_cleanup() {
let service = Arc::new(Loopbacks::default());
let (id, uri) = service.begin("a", "main", "oauth/callback").unwrap();
assert!(uri.starts_with("http://127.0.0.1:"));
let (other, _) = service.begin("a", "main", "").unwrap();
assert!(service.begin("a", "main", "third").is_err());
assert_eq!(service.wait("a", other, Duration::ZERO, &CancellationToken::new()).unwrap(), None);
let host = uri.strip_prefix("http://").unwrap().split('/').next().unwrap().to_owned();
let worker = std::thread::spawn(move || {
let mut stream = TcpStream::connect(host).unwrap();
stream.write_all(b"GET /oauth/callback?code=a%2Bb&state=x HTTP/1.1\r\nHost: localhost\r\n\r\n").unwrap();
let mut answer = String::new();
stream.read_to_string(&mut answer).unwrap();
assert!(answer.contains("You can close this tab"));
});
assert_eq!(
service.wait("a", id, Duration::from_secs(2), &CancellationToken::new()).unwrap(),
Some("code=a%2Bb&state=x".into())
);
worker.join().unwrap();
assert!(service.wait("a", id, Duration::ZERO, &CancellationToken::new()).is_err());
let (id, _) = service.begin("a", "main", "callback").unwrap();
service.forget_window("main");
assert!(service.wait("a", id, Duration::ZERO, &CancellationToken::new()).is_err());
}
}
+1
Переглянути файл
@@ -113,6 +113,7 @@ pub async fn plugin_navigation_index(
&project.root,
crate::plugins::navigation::Snapshot { path: &path, version, text: &text, symbols: &symbols, scope },
Invocation {
command_chain: Vec::new(),
client: Some(client.clone()),
workspace_root: Some(project.root.clone()),
editor: None,
+174
Переглянути файл
@@ -0,0 +1,174 @@
//! Plugin-owned local byte streams, closed on resource drop and plugin shutdown.
use super::api::net_runtime;
use ide_core::CancellationToken;
use ide_plugin::HostError;
use parking_lot::Mutex;
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
trait Stream: AsyncRead + AsyncWrite + Unpin + Send {}
impl<T: AsyncRead + AsyncWrite + Unpin + Send> Stream for T {}
struct Connection {
stream: tokio::sync::Mutex<Box<dyn Stream>>,
closed: CancellationToken,
}
impl Drop for Connection {
fn drop(&mut self) {
self.closed.cancel();
}
}
#[derive(Default)]
pub(super) struct Connections {
next: AtomicU64,
entries: Mutex<HashMap<(String, u64), Arc<Connection>>>,
}
fn failed(e: impl std::fmt::Display) -> HostError {
HostError::Failed(e.to_string())
}
impl Connections {
pub fn connect(
&self,
plugin: &str,
name: &str,
cancel: &CancellationToken,
timeout: Duration,
) -> Result<u64, HostError> {
let check = |entries: &HashMap<(String, u64), Arc<Connection>>| {
if entries.keys().filter(|(p, _)| p == plugin).count() >= 8 {
Err(HostError::Invalid("at most eight IPC connections per plugin".into()))
} else {
Ok(())
}
};
check(&self.entries.lock())?;
let stream: Box<dyn Stream> = net_runtime().block_on(async {
let connect = async {
#[cfg(unix)]
{ Ok::<Box<dyn Stream>, HostError>(Box::new(tokio::net::UnixStream::connect(name).await.map_err(failed)?)) }
#[cfg(windows)]
{ Ok::<Box<dyn Stream>, HostError>(Box::new(tokio::net::windows::named_pipe::ClientOptions::new().open(name).map_err(failed)?)) }
#[cfg(not(any(unix, windows)))]
{ let _ = name; Err(HostError::Failed("local IPC unavailable".into())) }
};
tokio::select! {
r = tokio::time::timeout(timeout, connect) => r.map_err(|_| HostError::Failed("IPC connection timed out".into()))?,
() = cancel.cancelled() => Err(HostError::Cancelled),
}
})?;
let mut entries = self.entries.lock();
check(&entries)?;
if cancel.is_cancelled() {
return Err(HostError::Cancelled);
}
let id = self.next.fetch_add(1, Ordering::Relaxed);
entries.insert(
(plugin.into(), id),
Arc::new(Connection { stream: tokio::sync::Mutex::new(stream), closed: CancellationToken::new() }),
);
Ok(id)
}
fn get(&self, plugin: &str, id: u64) -> Result<Arc<Connection>, HostError> {
self.entries
.lock()
.get(&(plugin.into(), id))
.cloned()
.ok_or_else(|| HostError::NotFound("IPC connection".into()))
}
pub fn write(
&self,
plugin: &str,
id: u64,
bytes: Vec<u8>,
cancel: &CancellationToken,
timeout: Duration,
) -> Result<(), HostError> {
let entry = self.get(plugin, id)?;
net_runtime().block_on(async {
tokio::select! {
r = tokio::time::timeout(timeout, async { entry.stream.lock().await.write_all(&bytes).await.map_err(failed) }) => r.map_err(|_| HostError::Failed("IPC write timed out".into()))?,
() = cancel.cancelled() => Err(HostError::Cancelled),
() = entry.closed.cancelled() => Err(HostError::Cancelled),
}
})
}
pub fn read(
&self,
plugin: &str,
id: u64,
max: usize,
timeout: Duration,
cancel: &CancellationToken,
) -> Result<Vec<u8>, HostError> {
let entry = self.get(plugin, id)?;
net_runtime().block_on(async {
let read = async {
let mut bytes = vec![0; max.min(1 << 20)];
let count = entry.stream.lock().await.read(&mut bytes).await.map_err(failed)?;
bytes.truncate(count);
Ok(bytes)
};
tokio::select! {
biased;
() = cancel.cancelled() => Err(HostError::Cancelled),
() = entry.closed.cancelled() => Err(HostError::Cancelled),
r = read => r,
() = tokio::time::sleep(timeout) => Ok(Vec::new()),
}
})
}
pub fn close(&self, plugin: &str, id: u64) {
if let Some(entry) = self.entries.lock().remove(&(plugin.into(), id)) {
entry.closed.cancel();
}
}
pub fn clear(&self, plugin: &str) {
self.entries.lock().retain(|(p, _), entry| {
if p != plugin {
return true;
}
entry.closed.cancel();
false
});
}
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use std::io::{Read, Write};
use std::os::unix::net::UnixListener;
#[test]
fn echo_limit_and_shutdown() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("echo.sock");
let listener = UnixListener::bind(&path).unwrap();
let worker = std::thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
let mut bytes = [0; 4];
stream.read_exact(&mut bytes).unwrap();
stream.write_all(&bytes).unwrap();
// Accept the remaining seven connections before shutdown.
for _ in 1..8 {
listener.accept().unwrap();
}
});
let pool = Connections::default();
let token = CancellationToken::new();
let timeout = Duration::from_secs(2);
let id = pool.connect("a", path.to_str().unwrap(), &token, timeout).unwrap();
pool.write("a", id, b"echo".to_vec(), &token, timeout).unwrap();
assert_eq!(pool.read("a", id, 4, timeout, &token).unwrap(), b"echo");
for _ in 1..8 {
pool.connect("a", path.to_str().unwrap(), &token, timeout).unwrap();
}
assert!(matches!(pool.connect("a", path.to_str().unwrap(), &token, timeout), Err(HostError::Invalid(_))));
assert!(pool.read("b", id, 4, timeout, &token).is_err());
pool.clear("a");
assert!(pool.read("a", id, 4, timeout, &token).is_err());
worker.join().unwrap();
}
}
+129 -7
Переглянути файл
@@ -16,6 +16,7 @@
//! projects) and folders linked with `openidea-plugin link` (`links.json`).
mod api;
mod auth;
pub mod commit;
pub(crate) mod diagnostics;
pub mod endpoints;
@@ -30,6 +31,7 @@ pub mod index_ops;
mod inlay_hints;
mod install;
pub mod intellij;
mod ipc;
mod market;
pub mod navigation;
mod points;
@@ -1080,7 +1082,9 @@ impl PluginHost {
ledger.set(&subject, &cap, granted);
if granted
&& let Capability::Process(program) = &cap
&& let Some(bin) = self.resolve_binary(program)
&& let Some(bin) = ledger
.program_choice(&subject, &cap)
.map_or_else(|| self.resolve_binary(program), |path| ledger::approve_program(path).ok())
{
ledger.set_binary(&subject, &cap, bin);
}
@@ -1097,14 +1101,74 @@ impl PluginHost {
/// The program a `process:` grant allows, checked against the file
/// approved for it. Errors ask the user to confirm again.
pub fn program_for(&self, id: &str, program: &str) -> IdeResult<PathBuf> {
self.program_for_project(id, program, None)
}
/// Resolves the approved executable for the invoking project, verifying its pinned content.
pub fn program_for_project(&self, id: &str, program: &str, root: Option<&Path>) -> IdeResult<PathBuf> {
let plugin = self.get(id)?;
let cap = Capability::Process(program.to_owned());
self.ledger
.lock()
.check_binary(&plugin.subject(), &cap)
.check_binary_in_project(&plugin.subject(), &Capability::Process(program.into()), root)
.map_err(|e| IdeError::new(ide_core::error::ErrorKind::PermissionDenied, e))
}
/// Records a user-approved executable choice; removing it revalidates the fallback or revokes the grant.
pub fn choose_program(
&self,
id: &str,
capability: &str,
root: Option<&Path>,
path: Option<&Path>,
) -> IdeResult<PluginInfo> {
let _guard = self.lifecycle.lock();
let plugin = self.get(id)?;
self.check_not_uninstalling(&plugin)?;
let cap: Capability = capability.parse().map_err(IdeError::invalid)?;
let Capability::Process(program) = &cap else {
return Err(IdeError::invalid("expected a process capability"));
};
if !plugin.manifest().declares(&cap) && !plugin.meta.lock().declared_extra.contains(&cap) {
return Err(IdeError::invalid("undeclared process capability"));
}
let binary = if let Some(path) = path {
Some(ledger::approve_program(path).map_err(IdeError::invalid)?)
} else if root.is_none() {
self.resolve_binary(program)
} else {
None
};
{
let mut ledger = self.ledger.lock();
let subject = plugin.subject();
if ledger.get(&subject).is_none() {
return Err(IdeError::invalid("confirm this plugin's permissions first"));
}
if let Some(root) = root {
ledger.set_project_binary(&subject, &cap, root, binary);
if path.is_some() {
ledger.set(&subject, &cap, true);
} else if ledger.check_binary(&subject, &cap).is_err() {
ledger.set(&subject, &cap, false);
}
} else if let Some(binary) = binary {
ledger.set_program_choice(&subject, &cap, path);
ledger.set(&subject, &cap, true);
ledger.set_binary(&subject, &cap, binary);
} else {
ledger.set_program_choice(&subject, &cap, None);
ledger.set(&subject, &cap, false);
}
self.save_ledger(&ledger);
}
self.stop(&plugin);
if !self.state.lock().disabled.contains(id) {
self.start(&plugin);
}
self.changed();
self.info_of(id)
}
fn check_uninstall_pending(&self, id: &str) -> IdeResult<()> {
if install::uninstall_pending(&self.plugins_dir, id)? {
return Err(IdeError::unavailable(std::io::Error::from(std::io::ErrorKind::ResourceBusy).to_string()));
@@ -1457,7 +1521,11 @@ impl PluginHost {
/// Plugins' `runDetectors`, for [`ide_run::set_external_detection`].
pub fn run_detection(&self) -> Arc<dyn ide_run::ExternalDetection> {
Arc::new(run_detectors::PluginRunDetection { store: self.run_detectors.clone(), pins: self.pins.clone() })
Arc::new(run_detectors::PluginRunDetection {
store: self.run_detectors.clone(),
pins: self.pins.clone(),
project_pins: self.shared.project_pins.clone(),
})
}
/// The syntax of plugin languages, for [`ide_language::set_external_syntax`].
@@ -1513,6 +1581,10 @@ impl PluginHost {
}
/// Plugin context keys in effect for window `client`: global keys overlaid with its own.
pub fn status_snapshot(&self, client: &str) -> Vec<PluginStatusItem> {
self.shared.status_snapshot(client)
}
pub fn context_keys(&self, client: Option<&str>) -> Vec<PluginContextKey> {
self.shared.context_keys(client)
}
@@ -1543,6 +1615,10 @@ impl PluginHost {
/// A window answered a plugin's `CommitRequested`; false when the call no
/// longer waits.
pub fn answer_command(&self, client: &str, request: &str, answer: CommandAnswer) -> bool {
request.parse().is_ok_and(|id| self.shared.answer_command(client, id, answer))
}
pub fn answer_commit(&self, request_id: &str, answer: CommitAnswer) -> bool {
request_id.parse().is_ok_and(|id| self.shared.answer_commit(id, answer))
}
@@ -1632,6 +1708,17 @@ impl PluginHost {
/// Queues workbench events from window `client` for the plugins that want
/// them; [`flush_events`](Self::flush_events) delivers them in batches.
pub fn post_window_events(&self, client: &str, events: Vec<WorkbenchEvent>, editor: Option<PluginEditor>) {
let mut editors = self.shared.event_editors.write();
if let Some(editor) = editor {
editors.insert(client.into(), editor.context());
} else {
editors.remove(client);
}
drop(editors);
self.post_events(Some(client), events);
}
pub fn post_events(&self, client: Option<&str>, events: Vec<WorkbenchEvent>) {
self.post_events_from(client, events, None);
}
@@ -1661,7 +1748,13 @@ impl PluginHost {
.as_ref()
.is_none_or(|root| client.and_then(|c| self.shared.project_of(c)).as_ref() == Some(root))
})
.cloned()
.filter_map(|e| match e {
WorkbenchEvent::SettingsChanged(_) => {
let keys = self.shared.changed_settings(&p.pkg, client);
(!keys.is_empty()).then_some(WorkbenchEvent::SettingsChanged(keys))
}
_ => Some(e.clone()),
})
.collect();
let wanted = Self::filter_path_events(&self.shared, &p, client, &wanted, &subs);
if wanted.is_empty() {
@@ -1809,9 +1902,10 @@ impl PluginHost {
let invocation = Invocation {
workspace_root: client.as_deref().and_then(|c| self.shared.project_of(c)),
client: client.clone(),
editor: None,
editor: client.as_deref().and_then(|c| self.shared.event_editors.read().get(c).cloned()),
selected_paths: Vec::new(),
global_settings: false,
command_chain: Vec::new(),
};
let kinds: BTreeSet<EventKind> = queue.events.iter().map(WorkbenchEvent::kind).collect();
let filesystem = kinds.contains(&EventKind::FilesChanged);
@@ -2599,8 +2693,21 @@ impl PluginHost {
/// pick up a change on their next lookup.
fn refresh_pins(&self, ledger: &Ledger) {
let mut pins = HashMap::new();
let mut project_pins = HashMap::new();
for plugin in self.plugins.read().values() {
let subject = plugin.subject();
if let Some(grant) = ledger.get(&subject) {
for (root, binaries) in &grant.project_binaries {
for (cap, bin) in binaries {
if grant.granted.contains(cap) {
project_pins.insert(
(plugin.id().to_owned(), cap.clone(), root.clone()),
ProgramPin { path: bin.path.clone(), hash: bin.hash.clone() },
);
}
}
}
}
let declared =
plugin.manifest().capabilities.all().cloned().chain(plugin.meta.lock().declared_extra.clone());
for cap in declared.filter(|c| matches!(c, Capability::Process(_))) {
@@ -2612,6 +2719,7 @@ impl PluginHost {
}
}
}
*self.shared.project_pins.write() = project_pins;
let mut current = self.pins.write();
if *current != pins {
*current = pins;
@@ -2665,12 +2773,26 @@ impl PluginHost {
fn record_consent(&self, request: &Request<'_>, consent: &Consent) {
let accepted: Vec<Capability> = request.optional.iter().filter(|c| consent.accepts(c)).cloned().collect();
let choices: BTreeMap<_, _> = {
let ledger = self.ledger.lock();
request
.required
.iter()
.chain(&accepted)
.filter_map(|cap| {
ledger.program_choice(&request.subject, cap).map(|p| (cap.to_string(), p.to_path_buf()))
})
.collect()
};
let binaries: BTreeMap<String, BinaryGrant> = request
.required
.iter()
.chain(&accepted)
.filter_map(|c| match c {
Capability::Process(program) => self.resolve_binary(program).map(|b| (c.to_string(), b)),
Capability::Process(program) => choices
.get(&c.to_string())
.map_or_else(|| self.resolve_binary(program), |path| ledger::approve_program(path).ok())
.map(|b| (c.to_string(), b)),
_ => None,
})
.collect();
+204 -15
Переглянути файл
@@ -22,9 +22,7 @@
//! keychain and are asked for with a `plugin_secret` request
//! ([`SecretRequest`]) when a request header needs one (rule 4).
use super::{
Consent, HostWorkspace, PluginEditor, PluginEvent, PluginHost, PluginSource, PluginStatusItem, SecretStore,
};
use super::{Consent, HostWorkspace, PluginEditor, PluginEvent, PluginHost, PluginSource, SecretStore};
use crate::rpc::Dispatcher;
use base64::Engine as _;
use ide_core::{IdeError, IdeResult};
@@ -45,6 +43,32 @@ pub const SYNC_PACKAGES: &str = "plugin_sync_packages";
pub const EVENT_NOTIFICATION: &str = "plugin";
/// Server → client request ([`SecretRequest`] → `Option<String>`).
pub const SECRET_REQUEST: &str = "plugin_secret";
/// Mutations of declared secrets, kept on the desktop.
pub const SECRET_WRITE: &str = "plugin_secret_write";
/// OAuth listeners bound on the desktop, never the project server.
pub const AUTH_REQUEST: &str = "plugin_auth";
#[derive(Clone, Serialize, Deserialize)]
pub struct SecretWrite {
pub plugin: String,
pub name: String,
pub value: Option<String>,
}
/// A remote plugin's operation on a desktop OAuth listener.
#[derive(Clone, Serialize, Deserialize)]
pub struct AuthRequest {
pub plugin: String,
pub operation: AuthOperation,
}
#[derive(Clone, Serialize, Deserialize)]
pub enum AuthOperation {
Begin { path: String },
Wait { id: u64, timeout_ms: u32 },
Close { id: u64 },
Clear,
}
/// Under the server's data directory.
pub const PLUGINS_DIR: &str = "remote-plugins";
const INCOMING_DIR: &str = "remote-plugins.incoming";
@@ -109,6 +133,10 @@ pub fn forwarded(event: &PluginEvent) -> bool {
event,
PluginEvent::Notification { .. }
| PluginEvent::StatusItemChanged { .. }
| PluginEvent::WindowStatusItemChanged { .. }
| PluginEvent::ExecuteCommand { .. }
| PluginEvent::OutputChanged { .. }
| PluginEvent::RevealOutput { .. }
| PluginEvent::ContextChanged { .. }
| PluginEvent::TaskStarted { .. }
| PluginEvent::TaskProgress { .. }
@@ -218,8 +246,19 @@ impl SecretStore for ClientSecrets {
}
}
fn set(&self, _: &str, _: &str, _: Option<&str>) -> Result<(), String> {
Err("secrets are stored on the desktop".into())
fn set(&self, plugin: &str, name: &str, value: Option<&str>) -> Result<(), String> {
let peer = self.peer.get().ok_or("desktop disconnected")?.clone();
let request = SecretWrite { plugin: plugin.into(), name: name.into(), value: value.map(str::to_owned) };
let ask = async {
tokio::time::timeout(SECRET_TIMEOUT, peer.request::<_, Result<(), String>>(SECRET_WRITE, request, None))
.await
};
let answer = if tokio::runtime::Handle::try_current().is_ok() {
tokio::task::block_in_place(|| self.runtime.block_on(ask))
} else {
self.runtime.block_on(ask)
};
answer.map_err(|_| "desktop timed out".to_owned())?.map_err(|e| e.to_string())?
}
}
@@ -237,7 +276,8 @@ impl RemotePlugins {
};
let host = Arc::new(PluginHost::new(data_dir.join(PLUGINS_DIR), Arc::new(sink), Limits::default())?);
host.set_workspace(Some(Arc::new(HostWorkspace(Arc::downgrade(projects)))));
host.set_secret_store(Arc::new(ClientSecrets { peer, runtime: projects.runtime.clone() }));
host.set_secret_store(Arc::new(ClientSecrets { peer: peer.clone(), runtime: projects.runtime.clone() }));
*host.shared.loopbacks.write() = Arc::new(ClientLoopbacks { peer, runtime: projects.runtime.clone() });
let trust = Arc::downgrade(projects);
host.set_project_policy(Arc::new(move |root| {
trust.upgrade().is_some_and(|h| h.trust.trusted(root).unwrap_or(false))
@@ -380,6 +420,7 @@ impl RemotePlugins {
let paths: Option<Vec<PathBuf>> = c.arg("paths")?;
let settings_scope: Option<SettingsScope> = c.arg("settingsScope")?;
let invocation = Invocation {
command_chain: c.arg::<Option<Vec<String>>>("commandChain")?.unwrap_or_default(),
client: Some(c.window.clone()),
workspace_root: c.host.project(&c.window).ok().map(|p| p.root.clone()),
editor: editor.map(PluginEditor::context),
@@ -401,7 +442,7 @@ impl RemotePlugins {
d.add("plugin_post_events", move |c| {
let h = h.clone();
async move {
alive(&h)?.post_events(Some(&c.window), c.arg("events")?);
alive(&h)?.post_window_events(&c.window, c.arg("events")?, c.arg("editor")?);
Ok(())
}
});
@@ -411,15 +452,9 @@ impl RemotePlugins {
async move { Ok(alive(&h)?.event_kinds().into_iter().collect::<Vec<_>>()) }
});
let h = host.clone();
d.add("plugin_status_items", move |_| {
d.add("plugin_status_items", move |c| {
let h = h.clone();
async move {
Ok(alive(&h)?
.status_items()
.into_iter()
.map(|(plugin_id, id, item)| PluginStatusItem { plugin_id, id, item })
.collect::<Vec<_>>())
}
async move { Ok(alive(&h)?.status_snapshot(&c.window)) }
});
let h = host.clone();
d.add("plugin_context_keys", move |c| {
@@ -437,6 +472,43 @@ impl RemotePlugins {
async move { Ok(alive(&h)?.answer_prompt(&c.arg::<String>("promptId")?, c.arg("answer")?)) }
});
let h = host.clone();
d.add("plugin_choose_program", move |c| {
let h = h.clone();
async move {
let host = alive(&h)?;
let id: String = c.arg("pluginId")?;
let cap: String = c.arg("capability")?;
let scope: SettingsScope = c.arg("scope")?;
let path: Option<PathBuf> = c.arg("path")?;
let root = match scope {
SettingsScope::Global => None,
SettingsScope::Project => Some(c.host.project(&c.window)?.root.clone()),
};
blocking(move || host.choose_program(&id, &cap, root.as_deref(), path.as_deref())).await
}
});
let h = host.clone();
d.add("plugin_program", move |c| {
let h = h.clone();
async move {
let host = alive(&h)?;
let id: String = c.arg("pluginId")?;
let program: String = c.arg("program")?;
let scope: SettingsScope = c.arg("scope")?;
let root = match scope {
SettingsScope::Global => None,
SettingsScope::Project => Some(c.host.project(&c.window)?.root.clone()),
};
blocking(move || host.program_for_project(&id, &program, root.as_deref()).map(ide_core::IpcPath::from))
.await
}
});
let h = host.clone();
d.add("plugin_answer_command", move |c| {
let h = h.clone();
async move { Ok(alive(&h)?.answer_command(&c.window, &c.arg::<String>("requestId")?, c.arg("answer")?)) }
});
let h = host.clone();
d.add("plugin_answer_commit", move |c| {
let h = h.clone();
async move { Ok(alive(&h)?.answer_commit(&c.arg::<String>("requestId")?, c.arg("answer")?)) }
@@ -621,6 +693,123 @@ fn safe_relative(path: &str) -> IdeResult<PathBuf> {
Ok(p.to_path_buf())
}
struct ClientLoopbacks {
peer: Arc<OnceLock<Peer>>,
runtime: tokio::runtime::Handle,
}
impl ClientLoopbacks {
fn request(
&self,
plugin: &str,
operation: AuthOperation,
cancel: Option<ide_core::CancellationToken>,
) -> Result<serde_json::Value, ide_plugin::HostError> {
let peer = self.peer.get().ok_or(ide_plugin::HostError::Cancelled)?.clone();
let timeout = match &operation {
AuthOperation::Wait { timeout_ms, .. } => Duration::from_millis(u64::from(*timeout_ms)) + SECRET_TIMEOUT,
_ => SECRET_TIMEOUT,
};
let request = AuthRequest { plugin: plugin.into(), operation };
let ask = async {
tokio::time::timeout(
timeout,
peer.request::<_, Result<serde_json::Value, ide_plugin::HostError>>(AUTH_REQUEST, request, cancel),
)
.await
.map_err(|_| ide_plugin::HostError::Failed("desktop OAuth request timed out".into()))?
.map_err(|e| ide_plugin::HostError::Failed(e.to_string()))?
};
if tokio::runtime::Handle::try_current().is_ok() {
tokio::task::block_in_place(|| self.runtime.block_on(ask))
} else {
self.runtime.block_on(ask)
}
}
}
impl super::auth::Service for ClientLoopbacks {
fn begin(&self, plugin: &str, _window: &str, path: &str) -> Result<(u64, String), ide_plugin::HostError> {
serde_json::from_value(self.request(plugin, AuthOperation::Begin { path: path.into() }, None)?)
.map_err(|e| ide_plugin::HostError::Failed(e.to_string()))
}
fn wait(
&self,
plugin: &str,
id: u64,
timeout: Duration,
cancel: &ide_core::CancellationToken,
) -> Result<Option<String>, ide_plugin::HostError> {
let result = self.request(
plugin,
AuthOperation::Wait { id, timeout_ms: timeout.as_millis().min(u128::from(u32::MAX)) as u32 },
Some(cancel.clone()),
);
if cancel.is_cancelled() {
self.close(plugin, id);
return Err(ide_plugin::HostError::Cancelled);
}
serde_json::from_value(result?).map_err(|e| ide_plugin::HostError::Failed(e.to_string()))
}
fn close(&self, plugin: &str, id: u64) {
let _ = self.request(plugin, AuthOperation::Close { id }, None);
}
fn clear(&self, plugin: &str) {
let _ = self.request(plugin, AuthOperation::Clear, None);
}
fn forget_window(&self, _: &str) {}
}
impl PluginHost {
/// A remote instance may mutate only declared secrets with a current grant.
pub fn remote_secret_write(&self, request: SecretWrite) -> Result<(), String> {
let plugin = self.get(&request.plugin).map_err(|e| e.message)?;
if !plugin.meta.lock().granted.iter().any(|g| g.covers(&ide_extension::Capability::Secrets)) {
return Err("secrets capability not granted".into());
}
if !self.ui.items(super::providers::SECRETS_POINT, Some(plugin.id())).iter().any(|s| s.key == request.name) {
return Err("undeclared secret".into());
}
if request.value.as_ref().is_some_and(|v| v.len() > 64 << 10) {
return Err("secret value too long".into());
}
self.shared.secrets.read().set(plugin.id(), &request.name, request.value.as_deref())
}
/// Serves a connected remote instance using this connection's actual window.
pub fn remote_auth(&self, window: &str, request: AuthRequest) -> Result<serde_json::Value, ide_plugin::HostError> {
if matches!(&request.operation, AuthOperation::Begin { .. } | AuthOperation::Wait { .. }) {
self.get(&request.plugin).map_err(|e| ide_plugin::HostError::NotFound(e.message))?;
}
let owner = format!("remote:{window}:{}", request.plugin);
let service = self.shared.loopbacks.read().clone();
let result = match request.operation {
AuthOperation::Begin { path } => {
if self.shared.client_closed(window) {
return Err(ide_plugin::HostError::Cancelled);
}
serde_json::to_value(service.begin(&owner, window, &path)?)
}
AuthOperation::Wait { id, timeout_ms } => serde_json::to_value(service.wait(
&owner,
id,
Duration::from_millis(u64::from(timeout_ms)),
&ide_core::CancellationToken::new(),
)?),
AuthOperation::Close { id } => {
service.close(&owner, id);
Ok(serde_json::Value::Null)
}
AuthOperation::Clear => {
service.clear(&owner);
Ok(serde_json::Value::Null)
}
};
result.map_err(|e| ide_plugin::HostError::Failed(e.to_string()))
}
/// A remote transport closed; abandon its browser listeners.
pub fn forget_remote_loopbacks(&self, window: &str) {
self.shared.loopbacks.read().forget_window(window);
}
}
#[cfg(test)]
mod tests {
use super::*;
+9 -5
Переглянути файл
@@ -115,6 +115,7 @@ type Pins = Arc<RwLock<HashMap<(String, String), ProgramPin>>>;
pub struct PluginRunDetection {
pub(crate) store: Arc<RunDetectors>,
pub(crate) pins: Pins,
pub(crate) project_pins: super::api::ProjectPins,
}
fn config_id(plugin: &str, detector: &str) -> String {
@@ -122,9 +123,10 @@ fn config_id(plugin: &str, detector: &str) -> String {
}
impl PluginRunDetection {
fn pin(&self, plugin: &str, d: &Detector) -> Option<ProgramPin> {
fn pin(&self, plugin: &str, d: &Detector, root: Option<&Path>) -> Option<ProgramPin> {
let cap = Capability::Process(d.command.trim().to_owned());
self.pins.read().get(&(plugin.to_owned(), cap.to_string())).cloned()
root.and_then(|root| self.project_pins.read().get(&(plugin.into(), cap.to_string(), root.into())).cloned())
.or_else(|| self.pins.read().get(&(plugin.to_owned(), cap.to_string())).cloned())
}
}
@@ -133,14 +135,16 @@ impl ExternalDetection for PluginRunDetection {
let items = self.store.items.read().clone();
items
.into_iter()
.filter(|(_, plugin, d)| self.pin(plugin, d).is_some() && d.files.iter().any(|f| root.join(f).exists()))
.filter(|(_, plugin, d)| {
self.pin(plugin, d, Some(root)).is_some() && d.files.iter().any(|f| root.join(f).exists())
})
.map(|(_, plugin, d)| RunConfig {
id: config_id(&plugin, &d.id),
name: d.name.clone(),
kind: "plugin".into(),
command: d.command.trim().to_owned(),
args: d.args.clone(),
cwd: None,
cwd: Some(root.to_path_buf().into()),
env: Default::default(),
detected: true,
is_test: d.test,
@@ -159,7 +163,7 @@ impl ExternalDetection for PluginRunDetection {
.map(|(_, p, d)| (p.clone(), d.clone()))
.ok_or_else(|| "the plugin that detected this configuration is no longer enabled".to_owned())?;
drop(items);
let pin = self.pin(&plugin, &d).ok_or_else(|| {
let pin = self.pin(&plugin, &d, config.cwd.as_ref().map(|p| p.as_ref())).ok_or_else(|| {
format!("allow process:{} for plugin {plugin} in Settings › Plugins to run this configuration", d.command)
})?;
pin.verify().map(Path::to_path_buf)
+23
Переглянути файл
@@ -166,6 +166,15 @@ pub struct PluginUpdate {
pub enum PluginEvent {
/// Plugins, their status or their contributions changed: re-fetch `plugin_list`.
CommandsChanged,
/// A bounded output channel snapshot, or withdrawal when the plugin stops.
#[serde(rename_all = "camelCase")]
OutputChanged { plugin_id: String, channel: String, text: Option<String> },
/// Reveal a read-only Output tab in the receiving window.
#[serde(rename_all = "camelCase")]
RevealOutput { plugin_id: String, channel: String, text: String },
/// Execute an action through the receiving window and answer over IPC.
#[serde(rename_all = "camelCase")]
ExecuteCommand { request_id: String, id: String, arg: Option<String>, chain: Vec<String> },
/// Cached document associations were disposed (reload, disable or failure).
DocumentIndexesChanged,
/// The routes `plugin_id` reports for the project `root` may have changed:
@@ -187,6 +196,9 @@ pub enum PluginEvent {
/// A plugin's status bar item was set (`item`) or removed.
#[serde(rename_all = "camelCase")]
StatusItemChanged { plugin_id: String, id: String, item: Option<StatusItem> },
/// An override in the receiving window; removal exposes the global item.
#[serde(rename_all = "camelCase")]
WindowStatusItemChanged { plugin_id: String, id: String, item: Option<StatusItem> },
/// A plugin's context key was set (`value`: JSON text) or removed, in the
/// emitted window (every window when the client is `None`).
#[serde(rename_all = "camelCase")]
@@ -340,6 +352,8 @@ pub struct PackageFile {
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PluginStatusItem {
/// Whether this item overrides the global item in the requesting window.
pub window: bool,
pub plugin_id: String,
pub id: String,
pub item: StatusItem,
@@ -388,3 +402,12 @@ pub struct PluginCommitCheckResult {
/// The check could not run (the plugin failed, timed out or lacks `vcs.read`).
pub error: Option<String>,
}
/// The invoking window's response to a command request.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(tag = "kind", content = "value", rename_all = "camelCase")]
pub enum CommandAnswer {
Value(Option<String>),
NotFound,
Failed(String),
}
+1 -1
Переглянути файл
@@ -309,7 +309,7 @@ impl PluginHost {
if !workspace.trusted(&cwd) {
return Err(IdeError::new(ide_core::error::ErrorKind::PermissionDenied, "project is not trusted"));
}
let program = self.program_for(plugin_id, &command.program)?;
let program = self.program_for_project(plugin_id, &command.program, Some(&cwd))?;
Ok(ide_terminal::TerminalOptions {
cwd: cwd.into(),
shell: Some(program.to_string_lossy().into_owned()),
+2
Переглянути файл
@@ -396,6 +396,8 @@ pub fn projectless_command_allowed(cmd: &str) -> bool {
| "plugin_set_enabled"
| "plugin_grant"
| "plugin_set_capability"
| "plugin_choose_program"
| "plugin_program"
| "plugin_roll_back"
| "plugin_reload"
)
+1
Переглянути файл
@@ -59,6 +59,7 @@ fn fixture() -> Fixture {
fn inv() -> Invocation {
Invocation {
command_chain: Vec::new(),
client: Some("main".into()),
workspace_root: None,
editor: None,
+1
Переглянути файл
@@ -194,6 +194,7 @@ fn two_windows_of_same_root_keep_unsaved_snapshots_isolated() {
&f.root,
Snapshot { path, version: Some(1), text, symbols: &symbols, scope: "" },
Invocation {
command_chain: Vec::new(),
client: Some(client.into()),
workspace_root: Some(f.root.clone()),
editor: None,
+239
Переглянути файл
@@ -285,6 +285,7 @@ fn fixture(limits: Limits) -> Fixture {
impl Fixture {
fn inv(&self) -> Invocation {
Invocation {
command_chain: Vec::new(),
client: Some("main".into()),
workspace_root: Some(self.project.clone()),
editor: None,
@@ -5642,3 +5643,241 @@ fn view_secondary_requires_api_1_3_and_a_boolean_tool_window_placement() {
assert!(err.message.contains(message), "{api}, {location}, {value}: {err:?}");
}
}
#[test]
fn api14_denies_new_privileges_and_requires_an_invoking_window() {
let f = fixture(Limits::default());
f.host.install_from_dir(&sample("api14"), &Consent::default()).unwrap();
for (command, arg, capability) in [
("ipc", "/tmp/api14-no-grant", "ipc:"),
("fetch", "http://example.com/", "net.http:"),
("secret", "value", "secrets"),
("delete-secret", "", "secrets"),
] {
let error = f.run("api14", command, Some(arg)).unwrap_err();
assert!(error.contains(capability) && error.contains("not granted"), "{error}");
}
for command in ["window-status", "remove-window-status", "execute", "oauth", "output"] {
let error = f.host.run_command("api14", command, Some("value"), Invocation::default()).unwrap_err();
assert_eq!(error.kind, ErrorKind::InvalidInput, "{command}: {error:?}");
}
f.host.set_capability("api14", "secrets", true).unwrap();
f.run("api14", "secret", Some(" raw value ")).unwrap();
assert_eq!(f.host.declared_secret("api14", "token"), Some(" raw value ".into()));
assert!(f.run("api14", "undeclared-secret", Some("value")).unwrap_err().contains("undeclared"));
f.run("api14", "delete-secret", None).unwrap();
assert_eq!(f.host.declared_secret("api14", "token"), None);
}
#[test]
fn api14_window_status_overrides_fall_back_and_are_withdrawn() {
let f = fixture(Limits::default());
f.install(&sample("api14"));
f.run("api14", "global-status", Some("global")).unwrap();
f.run("api14", "window-status", Some("main")).unwrap();
let snapshot = f.host.status_snapshot("main");
assert!(snapshot.iter().any(|i| i.window && i.item.text == "main"));
assert!(!f.host.status_snapshot("other").iter().any(|i| i.window));
f.run("api14", "global-status", Some("updated")).unwrap();
f.run("api14", "remove-window-status", None).unwrap();
assert_eq!(f.host.status_snapshot("main").len(), 1);
assert_eq!(f.host.status_snapshot("main")[0].item.text, "updated");
f.run("api14", "window-status", Some("override")).unwrap();
f.host.forget_client("main");
assert!(!f.host.status_snapshot("main").iter().any(|i| i.window));
f.host.reopen_client("main");
f.run("api14", "window-status", Some("again")).unwrap();
f.host.set_enabled("api14", false).unwrap();
assert!(f.host.status_snapshot("main").is_empty());
assert!(f.take_events().iter().any(|(window, event)| window.as_deref() == Some("main")
&& matches!(event, PluginEvent::WindowStatusItemChanged { item: None, .. })));
}
#[test]
fn api14_command_requests_preserve_window_result_and_reject_cycles() {
let f = Arc::new(fixture(Limits::default()));
f.install(&sample("api14"));
assert!(f.run("api14", "execute", Some("plugin.api14.execute")).unwrap_err().contains("recursive"));
for answer in [CommandAnswer::Value(Some("result".into())), CommandAnswer::Value(None), CommandAnswer::NotFound] {
f.take_events();
let runner = f.clone();
let worker = std::thread::spawn(move || runner.run("api14", "execute", Some("test.action")));
let deadline = Instant::now() + Duration::from_secs(5);
let request = loop {
if let Some((window, PluginEvent::ExecuteCommand { request_id, arg, chain, .. })) =
f.events.lock().iter().find(|(_, e)| matches!(e, PluginEvent::ExecuteCommand { .. })).cloned()
{
assert_eq!(window.as_deref(), Some("main"));
assert_eq!(arg.as_deref(), Some("argument"));
assert_eq!(chain, ["api14"]);
break request_id;
}
assert!(Instant::now() < deadline);
std::thread::sleep(Duration::from_millis(5));
};
assert!(!f.host.answer_command("other", &request, answer.clone()));
assert!(f.host.answer_command("main", &request, answer.clone()));
let result = worker.join().unwrap();
match answer {
CommandAnswer::Value(value) => assert_eq!(result.unwrap(), value),
CommandAnswer::NotFound => assert!(result.unwrap_err().contains("test.action")),
_ => unreachable!(),
}
}
}
#[test]
fn api14_settings_and_input_events_use_other_and_capture_the_editor() {
let f = fixture(Limits::default());
f.install(&sample("api14"));
use ide_plugin::WorkbenchEvent as E;
f.host.post_events(Some("main"), vec![E::SettingsChanged(Vec::new())]);
f.workspace
.settings
.lock()
.insert("api14".into(), serde_json::from_value(serde_json::json!({"enabled": true})).unwrap());
let path = to_ipc(&f.project.join("src/notes.txt"));
f.host.post_window_events(
"main",
vec![
E::SettingsChanged(vec!["another-plugin-key".into()]),
E::FileClosed(path.clone()),
E::InputModeChanged(ide_plugin::InputMode {
path: path.clone(),
mode: "visual".into(),
sub: Some("linewise".into()),
}),
],
Some(PluginEditor {
path: path.clone(),
language: "text".into(),
selections: vec![ide_core::Range::default()],
}),
);
f.host.flush_events_at(Instant::now() + Duration::from_secs(2));
assert!(f.host.wait_events(Duration::from_secs(5)));
let received: serde_json::Value = serde_json::from_str(&f.run("api14", "events", None).unwrap().unwrap()).unwrap();
let events = received.as_array().unwrap();
assert_eq!(events.len(), 3, "{received}");
assert_eq!(events[0]["kind"], "settings-changed");
assert_eq!(events[0]["data"], "[\"enabled\"]");
assert_eq!(events[2]["kind"], "input-mode-changed");
assert_eq!(events[2]["editor"][0], path);
assert_eq!(events[2]["editor"][1][0], serde_json::json!([0, 0, 0, 0]));
}
#[cfg(unix)]
#[test]
fn api14_ipc_echo_checks_the_grant_in_the_wasm_binding() {
use std::io::{Read, Write};
let f = fixture(Limits::default());
let pkg = f._tmp.path().join("api14-package");
copy_dir(&sample("api14"), &pkg);
let path = f._tmp.path().join("echo.sock");
let manifest = pkg.join("plugin.toml");
let text = std::fs::read_to_string(&manifest)
.unwrap()
.replace("ipc:$TMPDIR/api14-*", &format!("ipc:{}", f._tmp.path().join("*.sock").display()));
std::fs::write(manifest, text).unwrap();
f.install(&pkg);
let listener = std::os::unix::net::UnixListener::bind(&path).unwrap();
let worker = std::thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
let mut bytes = [0; 4];
stream.read_exact(&mut bytes).unwrap();
stream.write_all(&bytes).unwrap();
});
assert_eq!(f.run("api14", "ipc", path.to_str()).unwrap().as_deref(), Some("echo"));
worker.join().unwrap();
f.host.set_capability("api14", &format!("ipc:{}", f._tmp.path().join("*.sock").display()), false).unwrap();
assert!(f.run("api14", "ipc", path.to_str()).unwrap_err().contains("not granted"));
}
#[test]
fn api14_oauth_wait_excludes_the_call_budget_and_closes_after_redirect() {
use std::io::{Read, Write};
let f = Arc::new(fixture(Limits { timeout: Duration::from_millis(200), ..Limits::default() }));
f.install(&sample("api14"));
let runner = f.clone();
let worker = std::thread::spawn(move || runner.run("api14", "oauth", None));
let deadline = Instant::now() + Duration::from_secs(5);
let uri = loop {
if let Some((_, PluginEvent::OutputChanged { text: Some(text), .. })) = f
.events
.lock()
.iter()
.find(|(_, e)| matches!(e, PluginEvent::OutputChanged { channel, .. } if channel == "oauth"))
.cloned()
{
break text;
}
assert!(Instant::now() < deadline);
std::thread::sleep(Duration::from_millis(5));
};
assert!(uri.starts_with("http://127.0.0.1:"));
std::thread::sleep(Duration::from_millis(300));
let authority = uri.strip_prefix("http://").unwrap().split('/').next().unwrap();
let mut stream = std::net::TcpStream::connect(authority).unwrap();
stream.write_all(b"GET /oauth/callback?code=a%2Bb&state=test HTTP/1.1\r\nHost: localhost\r\n\r\n").unwrap();
let mut response = String::new();
stream.read_to_string(&mut response).unwrap();
assert!(response.contains("You can close this tab"));
assert_eq!(worker.join().unwrap().unwrap().as_deref(), Some("code=a%2Bb&state=test"));
assert!(std::net::TcpStream::connect(authority).is_err());
f.run("api14", "global-status", Some("still running")).unwrap();
}
#[cfg(unix)]
#[test]
fn api14_executable_choices_are_pinned_per_project_and_reset_revalidates() {
use std::os::unix::fs::PermissionsExt;
let f = fixture(Limits::default());
let package = f._tmp.path().join("api14-process");
copy_dir(&sample("api14"), &package);
let manifest = package.join("plugin.toml");
let text =
std::fs::read_to_string(&manifest).unwrap().replace("optional = [", "optional = [\"process:api14-tool\", ");
std::fs::write(manifest, text).unwrap();
f.install(&package);
let executable = |name: &str| {
let path = f._tmp.path().join(format!("{name}-bin"));
std::fs::write(&path, format!("#!/bin/sh\nprintf '{name}'\n")).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
path.canonicalize().unwrap()
};
let global = executable("global");
let project = executable("project");
f.host.choose_program("api14", "process:api14-tool", None, Some(&global)).unwrap();
f.host.choose_program("api14", "process:api14-tool", Some(&f.project), Some(&project)).unwrap();
assert_eq!(f.host.program_for("api14", "api14-tool").unwrap(), global);
assert_eq!(f.host.program_for_project("api14", "api14-tool", Some(&f.project)).unwrap(), project);
for command in ["process-run", "process-run-command", "process-start"] {
assert_eq!(f.run("api14", command, None).unwrap().as_deref(), Some("project"));
let invocation = Invocation { client: Some("global".into()), ..Invocation::default() };
assert_eq!(f.host.run_command("api14", command, None, invocation).unwrap().as_deref(), Some("global"));
}
f.run("api14", "terminal", None).unwrap();
assert!(
f.take_events().iter().any(
|(_, e)| matches!(e, PluginEvent::OpenTerminal { program, .. } if program.as_ref() == project.as_path())
)
);
f.run("api14", "log", None).unwrap();
assert!(
f.take_events()
.iter()
.any(|(_, e)| matches!(e, PluginEvent::OpenLogTab { log, .. } if log.program == "api14-tool"))
);
let unrelated = f._tmp.path().join("unrelated");
assert_eq!(f.host.program_for_project("api14", "api14-tool", Some(&unrelated)).unwrap(), global);
std::fs::write(&project, "changed").unwrap();
assert!(f.host.program_for_project("api14", "api14-tool", Some(&f.project)).is_err());
f.host.choose_program("api14", "process:api14-tool", Some(&f.project), None).unwrap();
assert_eq!(f.host.program_for_project("api14", "api14-tool", Some(&f.project)).unwrap(), global);
f.host.choose_program("api14", "process:api14-tool", Some(&f.project), Some(&project)).unwrap();
std::fs::write(&global, "changed").unwrap();
f.host.choose_program("api14", "process:api14-tool", Some(&f.project), None).unwrap();
assert!(
!f.host.info_of("api14").unwrap().capabilities.iter().find(|c| c.id == "process:api14-tool").unwrap().granted
);
}
+101
Переглянути файл
@@ -27,6 +27,7 @@ struct Client {
events: Mutex<Vec<EventMessage>>,
plugin_events: Mutex<Vec<PluginEventMessage>>,
secret_requests: Mutex<Vec<SecretRequest>>,
desktop: Option<Arc<PluginHost>>,
}
impl Handler for Client {
@@ -45,6 +46,19 @@ impl Handler for Client {
self.secret_requests.lock().push(r);
return Ok(serde_json::to_value(value).unwrap());
}
if let Some(desktop) = &self.desktop {
use ide_host::plugins::remote_host::{AUTH_REQUEST, SECRET_WRITE};
if method == AUTH_REQUEST {
return Ok(
serde_json::to_value(desktop.remote_auth("main", serde_json::from_value(params).unwrap())).unwrap()
);
}
if method == SECRET_WRITE {
return Ok(
serde_json::to_value(desktop.remote_secret_write(serde_json::from_value(params).unwrap())).unwrap()
);
}
}
Err((ide_jsonrpc::codes::METHOD_NOT_FOUND, method.to_owned()))
}
}
@@ -350,3 +364,90 @@ async fn remote_projects_get_plugin_views_and_custom_editors() {
plugins.host().shutdown();
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn api14_remote_calls_keep_browser_listeners_and_secrets_on_the_desktop() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let tmp = tempfile::tempdir().unwrap();
let desktop = Arc::new(
PluginHost::new(tmp.path().join("desktop/plugins"), Arc::new(|_: Option<&str>, _| {}), Limits::default())
.unwrap(),
);
desktop.install_from_dir(&fixture("api14"), &Consent::all()).unwrap();
let project = tmp.path().join("project");
std::fs::create_dir(&project).unwrap();
let project = project.canonicalize().unwrap();
let base = tmp.path().join("server");
let peer_slot = Arc::new(OnceLock::new());
let sink_peer = peer_slot.clone();
let host = Arc::new(Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(move |w| rpc::event_sink(sink_peer.clone(), Some(w.into()))),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}));
let plugins = RemotePlugins::start(&base.join("data"), &host, peer_slot.clone()).unwrap();
let mut dispatcher = Dispatcher::standard();
plugins.register(&mut dispatcher);
let (client_io, server_io) = tokio::io::duplex(1 << 20);
let (sr, sw) = tokio::io::split(server_io);
tokio::spawn(rpc::serve(host, dispatcher, peer_slot, sr, sw));
let (cr, cw) = tokio::io::split(client_io);
let client = Arc::new(Client { desktop: Some(desktop.clone()), ..Client::default() });
let peer = Peer::connect(cr, cw, client.clone());
let _: Value = peer.request("initialize", json!({ "version": rpc::PROTOCOL_VERSION }), None).await.unwrap();
invoke(&peer, "open_project", json!({ "path": project })).await.unwrap();
invoke(&peer, "project_trust_set", json!({ "path": project, "trusted": true, "folder": false })).await.unwrap();
sync(&peer, &desktop, &[]).await;
let report = sync(&peer, &desktop, &["api14"]).await;
assert!(report.failed.is_empty(), "{report:?}");
let run = |command: &str, arg: Option<&str>| json!({ "pluginId": "api14", "commandId": command, "arg": arg, "editor": null });
invoke(&peer, "plugin_run_command", run("secret", Some("remote-token"))).await.unwrap();
assert_eq!(desktop.declared_secret("api14", "token").as_deref(), Some("remote-token"));
invoke(&peer, "plugin_run_command", run("delete-secret", None)).await.unwrap();
assert_eq!(desktop.declared_secret("api14", "token"), None);
invoke(&peer, "plugin_run_command", run("window-status", Some("remote"))).await.unwrap();
let status = invoke(&peer, "plugin_status_items", json!({})).await.unwrap();
assert!(status.as_array().unwrap().iter().any(|s| s["window"] == true && s["item"]["text"] == "remote"));
let oauth_peer = peer.clone();
let oauth = tokio::spawn(async move {
invoke(
&oauth_peer,
"plugin_run_command",
json!({ "pluginId": "api14", "commandId": "oauth", "arg": null, "editor": null }),
)
.await
});
until("remote OAuth URI", 5, || {
client
.plugin_events
.lock()
.iter()
.any(|m| matches!(&m.event, PluginEvent::OutputChanged { channel, .. } if channel == "oauth"))
})
.await;
let uri = client
.plugin_events
.lock()
.iter()
.find_map(|m| match &m.event {
PluginEvent::OutputChanged { channel, text: Some(text), .. } if channel == "oauth" => Some(text.clone()),
_ => None,
})
.unwrap();
let authority = uri.strip_prefix("http://").unwrap().split('/').next().unwrap();
let mut stream = tokio::net::TcpStream::connect(authority).await.unwrap();
stream.write_all(b"GET /oauth/callback?code=desktop%2Bcode HTTP/1.1\r\nHost: localhost\r\n\r\n").await.unwrap();
let mut response = String::new();
stream.read_to_string(&mut response).await.unwrap();
assert!(response.contains("You can close this tab"));
assert_eq!(oauth.await.unwrap().unwrap(), json!("code=desktop%2Bcode"));
plugins.host().shutdown();
desktop.shutdown();
peer.kill();
}
+6
Переглянути файл
@@ -26,6 +26,11 @@ pub fn with_proxy(builder: reqwest::ClientBuilder, proxy: &ProxySettings) -> req
/// A client for `proxy`.
pub fn build(proxy: &ProxySettings) -> IdeResult<reqwest::Client> {
build_with_redirect(proxy, reqwest::redirect::Policy::default())
}
/// A client with an explicit redirect policy, for callers enforcing network grants.
pub fn build_with_redirect(proxy: &ProxySettings, redirect: reqwest::redirect::Policy) -> IdeResult<reqwest::Client> {
use rustls_platform_verifier::BuilderVerifierExt;
let fail = |e: String| IdeError::internal(format!("HTTP client: {e}"));
let provider = Arc::new(rustls::crypto::ring::default_provider());
@@ -44,6 +49,7 @@ pub fn build(proxy: &ProxySettings) -> IdeResult<reqwest::Client> {
];
let builder = reqwest::Client::builder()
.tls_backend_preconfigured(tls)
.redirect(redirect)
.resolve_to_addrs("localhost", &loopback)
.connect_timeout(Duration::from_secs(30))
.user_agent(concat!("OpenIDEA-HttpClient/", env!("CARGO_PKG_VERSION")));
+1
Переглянути файл
@@ -16,6 +16,7 @@ thiserror.workspace = true
tracing.workspace = true
parking_lot.workspace = true
semver = "1"
url = "2"
wasmtime = { version = "49.0.4", default-features = false, features = ["runtime", "cranelift", "component-model", "std", "parallel-compilation", "async"] }
wasmtime-wasi = { version = "49.0.4", default-features = false, features = ["p2"] }
+101 -1
Переглянути файл
@@ -50,7 +50,7 @@ use views_bindings::exports::openidea::plugin::view_provider as wit_view;
use views_bindings::openidea::plugin::view_types as wit_vt;
/// The API version of the world above, `major.minor` of [`host_api`].
pub const API_VERSION: &str = "1.3";
pub const API_VERSION: &str = "1.4";
const EPOCH_TICK: Duration = Duration::from_millis(10);
pub(crate) const MAX_TEXT: usize = 1 << 20;
pub(crate) const MAX_TITLE: usize = 256;
@@ -101,8 +101,40 @@ pub trait HostApi: Send + Sync {
let _ = (client, view);
Ok(())
}
/// Executes a stable command in the invoking window and waits for its result.
fn execute_command(
&self,
invocation: &Invocation,
id: &str,
arg: Option<String>,
cancel: &CancellationToken,
timeout: Duration,
) -> Result<Option<String>, HostError> {
let _ = (invocation, id, arg, cancel, timeout);
Err(HostError::NotFound("command".into()))
}
/// Appends text, or clears (`None`), in a plugin-owned output channel.
fn output_write(&self, channel: &str, text: Option<&str>) -> Result<(), HostError> {
let _ = (channel, text);
Err(HostError::Failed("output unavailable".into()))
}
/// Reveals an output channel in the invoking window.
fn output_reveal(&self, client: &str, channel: &str) -> Result<(), HostError> {
let _ = (client, channel);
Err(HostError::Failed("output unavailable".into()))
}
/// Checks manifest minimum API requirements for new declarations or subscriptions.
fn require_api(&self, what: &str, minor: u64) -> Result<(), HostError> {
let _ = (what, minor);
Ok(())
}
/// Sets (`Some`) or removes the plugin's status bar item `id`.
fn status_item(&self, id: &str, item: Option<StatusItem>);
/// Sets or removes the status override in the invoking window.
fn window_status_item(&self, client: &str, id: &str, item: Option<StatusItem>) -> Result<(), HostError> {
let _ = (client, id, item);
Err(HostError::Invalid("window status unavailable".into()))
}
/// Sets (`Some`, validated JSON text) or removes the plugin's context key,
/// for window `client` (every window if `None`).
fn set_context(&self, client: Option<&str>, key: &str, value: Option<String>) -> Result<(), HostError> {
@@ -181,6 +213,62 @@ pub trait HostApi: Send + Sync {
/// Performs `request` (its host is granted), filling in secret placeholders.
fn fetch(&self, request: HttpRequest, cancel: &CancellationToken) -> Result<HttpResponse, HostError>;
fn secret_is_set(&self, name: &str) -> bool;
/// Stores or deletes a secret declared by this plugin; never returns its value.
fn secret_set(&self, name: &str, value: Option<&str>) -> Result<(), HostError> {
let _ = (name, value);
Err(HostError::NotFound("secret".into()))
}
/// Creates a desktop loopback listener and returns its handle and redirect URI.
fn begin_loopback(&self, client: &str, path: &str) -> Result<(u64, String), HostError> {
let _ = (client, path);
Err(HostError::Failed("loopback unavailable".into()))
}
/// Awaits a browser redirect, excluded from the caller's execution budget.
fn wait_loopback(
&self,
id: u64,
timeout: Duration,
cancel: &CancellationToken,
) -> Result<Option<String>, HostError> {
let _ = (id, timeout, cancel);
Err(HostError::NotFound("loopback".into()))
}
/// Releases a desktop listener when its resource or plugin stops.
fn close_loopback(&self, id: u64) {
let _ = id;
}
/// Connects to an approved host-local socket; owned by this plugin instance.
fn ipc_connect(&self, name: &str, cancel: &CancellationToken, timeout: Duration) -> Result<u64, HostError> {
let _ = (name, cancel, timeout);
Err(HostError::Failed("IPC unavailable".into()))
}
/// Writes to an owned IPC connection.
fn ipc_write(
&self,
id: u64,
bytes: Vec<u8>,
cancel: &CancellationToken,
timeout: Duration,
) -> Result<(), HostError> {
let _ = (id, bytes, cancel, timeout);
Err(HostError::NotFound("connection".into()))
}
/// Reads from an owned IPC connection, empty on timeout or EOF.
fn ipc_read(
&self,
id: u64,
max: usize,
timeout: Duration,
cancel: &CancellationToken,
) -> Result<Vec<u8>, HostError> {
let _ = (id, max, timeout, cancel);
Err(HostError::NotFound("connection".into()))
}
/// Closes an owned IPC connection, including when its resource is dropped.
fn ipc_close(&self, id: u64) {
let _ = id;
}
/// Runs the approved file of `process:<program>` with `cmd.env` added to
/// the inherited environment, and waits.
fn run_process(
@@ -653,6 +741,18 @@ const MAX_BATCH: usize = 1000;
fn event_to_wit(e: WorkbenchEvent) -> wit_events::Event {
match e {
WorkbenchEvent::FileClosed(p) => wit_events::Event::Other(wit_types::Extension {
kind: "file-closed".into(),
data: serde_json::to_string(&p).expect("path serializes"),
}),
WorkbenchEvent::SettingsChanged(keys) => wit_events::Event::Other(wit_types::Extension {
kind: "settings-changed".into(),
data: serde_json::to_string(&keys).expect("keys serialize"),
}),
WorkbenchEvent::InputModeChanged(mode) => wit_events::Event::Other(wit_types::Extension {
kind: "input-mode-changed".into(),
data: serde_json::to_string(&mode).expect("mode serializes"),
}),
WorkbenchEvent::FileOpened(p) => wit_events::Event::FileOpened(p),
WorkbenchEvent::FileSaved(p) => wit_events::Event::FileSaved(p),
WorkbenchEvent::FilesChanged(batch) => wit_events::Event::Other(wit_types::Extension {
+56 -20
Переглянути файл
@@ -25,6 +25,8 @@ pub struct EditorContext {
/// Where a command or event batch comes from: the window and its project.
#[derive(Clone, Debug, Default)]
pub struct Invocation {
/// Plugin instances waiting on this command chain; never re-enter one.
pub command_chain: Vec<String>,
pub client: Option<String>,
pub workspace_root: Option<PathBuf>,
/// Settings actions can read the global layer while retaining their project context.
@@ -35,7 +37,7 @@ pub struct Invocation {
}
/// A failed host call, as the plugin sees it (WIT `types.error`).
#[derive(Clone, Debug, PartialEq, Eq)]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum HostError {
/// Not granted; names the capability.
Denied(String),
@@ -98,6 +100,9 @@ pub enum Prompt {
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Type)]
#[serde(rename_all = "kebab-case")]
pub enum EventKind {
FileClosed,
SettingsChanged,
InputModeChanged,
FileOpened,
FileSaved,
FilesChanged,
@@ -108,7 +113,10 @@ pub enum EventKind {
}
impl EventKind {
pub const ALL: [Self; 7] = [
pub const ALL: [Self; 10] = [
Self::FileClosed,
Self::SettingsChanged,
Self::InputModeChanged,
Self::FileOpened,
Self::FileSaved,
Self::FilesChanged,
@@ -120,6 +128,9 @@ impl EventKind {
pub fn name(self) -> &'static str {
match self {
Self::FileClosed => "file-closed",
Self::SettingsChanged => "settings-changed",
Self::InputModeChanged => "input-mode-changed",
Self::FileOpened => "file-opened",
Self::FileSaved => "file-saved",
Self::FilesChanged => "files-changed",
@@ -138,7 +149,7 @@ impl EventKind {
/// manifest declares).
pub fn capability(self) -> Option<ide_extension::Capability> {
match self {
Self::ActionPerformed => Some(ide_extension::Capability::InputEvents),
Self::ActionPerformed | Self::InputModeChanged => Some(ide_extension::Capability::InputEvents),
Self::Scheduled => None,
_ => Some(ide_extension::Capability::Events),
}
@@ -188,10 +199,21 @@ pub struct FilesChanged {
pub removed: Vec<String>,
}
/// The focused editor's input mode and optional visual sub-mode.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
pub struct InputMode {
pub path: String,
pub mode: String,
pub sub: Option<String>,
}
/// A workbench event delivered to plugins.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", tag = "kind", content = "value")]
pub enum WorkbenchEvent {
FileClosed(String),
SettingsChanged(Vec<String>),
InputModeChanged(InputMode),
FileOpened(String),
FileSaved(String),
FilesChanged(FilesChanged),
@@ -204,6 +226,9 @@ pub enum WorkbenchEvent {
impl WorkbenchEvent {
pub fn kind(&self) -> EventKind {
match self {
Self::FileClosed(_) => EventKind::FileClosed,
Self::SettingsChanged(_) => EventKind::SettingsChanged,
Self::InputModeChanged(_) => EventKind::InputModeChanged,
Self::FileOpened(_) => EventKind::FileOpened,
Self::FileSaved(_) => EventKind::FileSaved,
Self::FilesChanged(_) => EventKind::FilesChanged,
@@ -350,6 +375,8 @@ pub struct HttpRequest {
pub headers: Vec<(String, String)>,
pub body: Option<Vec<u8>>,
pub timeout: Duration,
/// Grants checked again before following a redirect.
pub grants: Vec<ide_extension::Capability>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
@@ -371,6 +398,8 @@ pub struct ProcessOutput {
/// the environment to add to the inherited one (WIT `process.command`).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ProcessCommand {
/// The invoking project whose executable override applies, independent of cwd.
pub approval_root: Option<PathBuf>,
pub program: String,
pub args: Vec<String>,
pub env: Vec<(String, String)>,
@@ -388,23 +417,27 @@ pub struct ProcessChunk {
/// Where `net:` requests may go: the URL's host when it is `https`, or
/// `http` to the loopback interface.
pub fn net_host(url: &str) -> Result<String, String> {
let (scheme, rest) = url.split_once("://").ok_or_else(|| format!("{url:?} is not an absolute URL"))?;
let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
let authority = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
let host = if let Some(v6) = authority.strip_prefix('[') {
v6.split(']').next().unwrap_or_default().to_owned()
} else {
authority.split(':').next().unwrap_or_default().to_ascii_lowercase()
};
if host.is_empty() {
return Err(format!("{url:?} has no host"));
let parsed = url::Url::parse(url).map_err(|e| format!("invalid URL: {e}"))?;
if !matches!(parsed.scheme(), "http" | "https") {
return Err(format!("unsupported scheme {:?}", parsed.scheme()));
}
let loopback = matches!(host.as_str(), "localhost" | "127.0.0.1" | "::1");
match scheme.to_ascii_lowercase().as_str() {
"https" => Ok(host),
"http" if loopback => Ok(host),
"http" => Err(format!("{url:?}: plain http is only allowed to localhost")),
other => Err(format!("{url:?}: unsupported scheme {other:?}")),
match parsed.host() {
Some(url::Host::Domain(host)) => Ok(host.trim_end_matches('.').to_ascii_lowercase()),
Some(url::Host::Ipv4(host)) => Ok(host.to_string()),
Some(url::Host::Ipv6(host)) => Ok(host.to_string()),
None => Err("URL has no host".into()),
}
}
/// The grant required by a URL; loopback HTTP retains the original `net:` rule.
pub fn net_capability(url: &str) -> Result<ide_extension::Capability, String> {
let host = net_host(url)?;
if url::Url::parse(url).is_ok_and(|u| u.scheme() == "http")
&& !matches!(host.as_str(), "localhost" | "127.0.0.1" | "::1")
{
Ok(ide_extension::Capability::NetHttp(host))
} else {
Ok(ide_extension::Capability::Net(host))
}
}
@@ -427,7 +460,10 @@ mod tests {
assert_eq!(net_host("https://API.example.com:8443/v1?x").unwrap(), "api.example.com");
assert_eq!(net_host("http://localhost:11434/api").unwrap(), "localhost");
assert_eq!(net_host("https://user:[email protected]/").unwrap(), "h.io");
assert!(net_host("http://example.com/").is_err());
assert_eq!(
net_capability("http://example.com/").unwrap(),
ide_extension::Capability::NetHttp("example.com".into())
);
assert!(net_host("file:///etc/passwd").is_err());
assert!(net_host("example.com").is_err());
}
+203 -6
Переглянути файл
@@ -6,7 +6,7 @@ use crate::runtime::{MAX_TITLE, StoreData, clip};
use crate::sandbox;
use crate::types::{
EditorContext, EventKind, HostError, HttpRequest, NotificationLevel, PickItem, ProcessChunk, ProcessCommand,
Prompt, StatusItem, net_host,
Prompt, StatusItem, net_capability,
};
use ide_core::ipc_path::to_ipc;
use ide_extension::Capability;
@@ -25,6 +25,8 @@ pub(crate) mod bindings {
"openidea:plugin/invocation.invocation": super::InvocationRes,
"openidea:plugin/tasks.task": super::TaskRes,
"openidea:plugin/process.child": super::ChildRes,
"openidea:plugin/ipc.connection": super::ConnectionRes,
"openidea:plugin/auth.loopback": super::LoopbackRes,
},
});
}
@@ -51,6 +53,10 @@ pub(crate) mod syntax_bindings {
"openidea:plugin/net": super::bindings::openidea::plugin::net,
"openidea:plugin/secrets": super::bindings::openidea::plugin::secrets,
"openidea:plugin/process": super::bindings::openidea::plugin::process,
"openidea:plugin/output": super::bindings::openidea::plugin::output,
"openidea:plugin/auth": super::bindings::openidea::plugin::auth,
"openidea:plugin/command-runner": super::bindings::openidea::plugin::command_runner,
"openidea:plugin/ipc": super::bindings::openidea::plugin::ipc,
"openidea:plugin/fs": super::bindings::openidea::plugin::fs,
"openidea:plugin/views": super::bindings::openidea::plugin::views,
"openidea:plugin/settings": super::bindings::openidea::plugin::settings,
@@ -80,6 +86,10 @@ pub(crate) mod providers_bindings {
"openidea:plugin/net": super::bindings::openidea::plugin::net,
"openidea:plugin/secrets": super::bindings::openidea::plugin::secrets,
"openidea:plugin/process": super::bindings::openidea::plugin::process,
"openidea:plugin/output": super::bindings::openidea::plugin::output,
"openidea:plugin/auth": super::bindings::openidea::plugin::auth,
"openidea:plugin/command-runner": super::bindings::openidea::plugin::command_runner,
"openidea:plugin/ipc": super::bindings::openidea::plugin::ipc,
"openidea:plugin/fs": super::bindings::openidea::plugin::fs,
"openidea:plugin/views": super::bindings::openidea::plugin::views,
"openidea:plugin/settings": super::bindings::openidea::plugin::settings,
@@ -109,6 +119,10 @@ pub(crate) mod views_bindings {
"openidea:plugin/net": super::bindings::openidea::plugin::net,
"openidea:plugin/secrets": super::bindings::openidea::plugin::secrets,
"openidea:plugin/process": super::bindings::openidea::plugin::process,
"openidea:plugin/output": super::bindings::openidea::plugin::output,
"openidea:plugin/auth": super::bindings::openidea::plugin::auth,
"openidea:plugin/command-runner": super::bindings::openidea::plugin::command_runner,
"openidea:plugin/ipc": super::bindings::openidea::plugin::ipc,
"openidea:plugin/fs": super::bindings::openidea::plugin::fs,
"openidea:plugin/views": super::bindings::openidea::plugin::views,
"openidea:plugin/settings": super::bindings::openidea::plugin::settings,
@@ -117,8 +131,8 @@ pub(crate) mod views_bindings {
}
use bindings::openidea::plugin::{
commit, detail_types, diagnostics, editor, events, fs, invocation, log, net, process, secrets, settings, storage,
tasks, types as wit, ui, vcs, views, workspace,
commit, detail_types, diagnostics, editor, events, fs, invocation, ipc, log, net, process, secrets, settings,
storage, tasks, types as wit, ui, vcs, views, workspace,
};
/// A project handle: its root.
@@ -319,6 +333,14 @@ impl StoreData {
self.ask(Prompt::QuickPick { title: clip(title, MAX_TITLE), items, multiple })
}
fn require_window(&self) -> Result<(), wit::Error> {
self.require_interactive()?;
if self.invocation.client.is_none() {
return Err(wit::Error::Invalid("requires an invoking window".into()));
}
Ok(())
}
/// APIs reserved for commands and events exclude code-action resolution.
fn require_interactive(&self) -> Result<(), wit::Error> {
if self.interactive {
@@ -381,6 +403,29 @@ impl ui::Host for StoreData {
Ok(())
}
fn set_window_status_item(&mut self, id: String, item: ui::StatusItem) -> Fallible<()> {
if let Err(e) = self.require_window() {
return Ok(Err(e));
}
let item = StatusItem {
text: clip(item.text, MAX_STATUS_TEXT),
tooltip: item.tooltip.map(|t| clip(t, 1024)),
command: item.command.map(|c| clip(c, 128)),
};
Ok(self
.host
.window_status_item(self.invocation.client.as_deref().expect("checked"), &clip(id, 64), Some(item))
.map_err(to_wit))
}
fn remove_window_status_item(&mut self, id: String) -> Fallible<()> {
if let Err(e) = self.require_window() {
return Ok(Err(e));
}
Ok(self
.host
.window_status_item(self.invocation.client.as_deref().expect("checked"), &clip(id, 64), None)
.map_err(to_wit))
}
fn set_context(&mut self, key: String, value: ui::ContextValue) -> Fallible<()> {
let valid_key =
(1..=64).contains(&key.len()) && key.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-'));
@@ -850,6 +895,11 @@ impl events::Host for StoreData {
let Some(kind) = EventKind::parse(&kind) else {
return Ok(Err(wit::Error::Invalid(format!("no event kind {kind:?} in this OpenIDEA"))));
};
if matches!(kind, EventKind::FileClosed | EventKind::SettingsChanged | EventKind::InputModeChanged)
&& let Err(e) = self.host.require_api(kind.name(), 4)
{
return Ok(Err(to_wit(e)));
}
if let Some(cap) = kind.capability()
&& let Err(e) = self.require(cap)
{
@@ -952,11 +1002,11 @@ impl diagnostics::Host for StoreData {
impl net::Host for StoreData {
fn fetch(&mut self, req: net::Request) -> Fallible<net::Response> {
let host = match net_host(&req.url) {
let capability = match net_capability(&req.url) {
Ok(h) => h,
Err(e) => return Ok(Err(wit::Error::Invalid(e))),
};
if let Err(e) = self.require(Capability::Net(host)) {
if let Err(e) = self.require(capability) {
return Ok(Err(e));
}
if req.headers.iter().any(|h| h.value.contains("{{secret:"))
@@ -974,6 +1024,7 @@ impl net::Host for StoreData {
headers: req.headers.into_iter().map(|h| (h.name, h.value)).collect(),
body: req.body,
timeout: wanted.min(self.remaining()),
grants: self.granted.clone(),
};
let token = self.cancel.token();
Ok(self
@@ -989,6 +1040,21 @@ impl net::Host for StoreData {
}
impl secrets::Host for StoreData {
fn set(&mut self, name: String, value: String) -> Fallible<()> {
if let Err(e) = self.require(Capability::Secrets) {
return Ok(Err(e));
}
if name.len() > 128 || value.len() > 64 << 10 {
return Ok(Err(wit::Error::Invalid("secret name or value too long".into())));
}
Ok(self.host.secret_set(&name, Some(&value)).map_err(to_wit))
}
fn delete(&mut self, name: String) -> Fallible<()> {
if let Err(e) = self.require(Capability::Secrets) {
return Ok(Err(e));
}
Ok(self.host.secret_set(&name, None).map_err(to_wit))
}
fn is_set(&mut self, name: String) -> wasmtime::Result<bool> {
Ok(self.granted.iter().any(|g| g.covers(&Capability::Secrets)) && self.host.secret_is_set(&name))
}
@@ -1013,7 +1079,12 @@ impl StoreData {
return Err(wit::Error::Invalid(format!("the value of {name:?} is too long or holds a NUL")));
}
}
Ok(ProcessCommand { program: cmd.program, args: cmd.args, env: cmd.env })
Ok(ProcessCommand {
program: cmd.program,
args: cmd.args,
env: cmd.env,
approval_root: self.invocation.workspace_root.clone(),
})
}
/// The project a call runs in, when it named one.
@@ -1489,3 +1560,129 @@ pub(crate) fn diagnostics_from_wit(items: Vec<diagnostics::Diagnostic>, source:
})
.collect()
}
/// An IPC connection owned by this plugin instance.
pub struct ConnectionRes {
id: u64,
host: std::sync::Arc<dyn crate::HostApi>,
}
impl Drop for ConnectionRes {
fn drop(&mut self) {
self.host.ipc_close(self.id);
}
}
impl ipc::Host for StoreData {
fn connect(&mut self, name: String) -> Fallible<Resource<ConnectionRes>> {
if let Err(e) = ide_extension::validate_ipc_name(&name, false) {
return Ok(Err(wit::Error::Invalid(e)));
}
if let Err(e) = self.require(Capability::Ipc(name.clone())) {
return Ok(Err(e));
}
let name = match ide_extension::expand_ipc_name(&name) {
Ok(name) => name,
Err(e) => return Ok(Err(wit::Error::Invalid(e))),
};
match self.host.ipc_connect(&name, &self.cancel.token(), self.remaining()) {
Ok(id) => self.push(ConnectionRes { id, host: self.host.clone() }).map(Ok),
Err(e) => Ok(Err(to_wit(e))),
}
}
}
impl ipc::HostConnection for StoreData {
fn write(&mut self, this: Resource<ConnectionRes>, bytes: Vec<u8>) -> Fallible<()> {
if bytes.len() > 1 << 20 {
return Ok(Err(wit::Error::Invalid("at most 1 MiB per write".into())));
}
let id = self.table.get(&this)?.id;
Ok(self.host.ipc_write(id, bytes, &self.cancel.token(), self.remaining()).map_err(to_wit))
}
fn read(&mut self, this: Resource<ConnectionRes>, max_bytes: u32, timeout_ms: u32) -> Fallible<Vec<u8>> {
let id = self.table.get(&this)?.id;
let timeout = Duration::from_millis(u64::from(timeout_ms)).min(self.remaining());
Ok(self.host.ipc_read(id, (max_bytes as usize).min(1 << 20), timeout, &self.cancel.token()).map_err(to_wit))
}
fn close(&mut self, this: Resource<ConnectionRes>) -> Fallible<()> {
let id = self.table.get(&this)?.id;
self.host.ipc_close(id);
Ok(Ok(()))
}
fn drop(&mut self, this: Resource<ConnectionRes>) -> wasmtime::Result<()> {
self.table.delete(this)?;
Ok(())
}
}
impl bindings::openidea::plugin::command_runner::Host for StoreData {
fn execute(&mut self, id: String, arg: Option<String>) -> Fallible<Option<String>> {
if let Err(e) = self.require_window() {
return Ok(Err(e));
}
if id.len() > 256 || arg.as_ref().is_some_and(|a| a.len() > 64 << 10) {
return Ok(Err(wit::Error::Invalid("command id or argument too long".into())));
}
Ok(self
.host
.execute_command(&self.invocation, &id, arg, &self.cancel.token(), self.remaining())
.map_err(to_wit))
}
}
/// A desktop OAuth listener; its URI remains available after the one-shot wait.
pub struct LoopbackRes {
id: u64,
uri: String,
host: std::sync::Arc<dyn crate::HostApi>,
}
impl Drop for LoopbackRes {
fn drop(&mut self) {
self.host.close_loopback(self.id);
}
}
impl bindings::openidea::plugin::auth::Host for StoreData {
fn begin_loopback(&mut self, path: String) -> Fallible<Resource<LoopbackRes>> {
if let Err(e) = self.require_window() {
return Ok(Err(e));
}
match self.host.begin_loopback(self.invocation.client.as_deref().expect("checked"), &path) {
Ok((id, uri)) => self.push(LoopbackRes { id, uri, host: self.host.clone() }).map(Ok),
Err(e) => Ok(Err(to_wit(e))),
}
}
}
impl bindings::openidea::plugin::auth::HostLoopback for StoreData {
fn redirect_uri(&mut self, this: Resource<LoopbackRes>) -> wasmtime::Result<String> {
Ok(self.table.get(&this)?.uri.clone())
}
fn wait(&mut self, this: Resource<LoopbackRes>, timeout_ms: u32) -> Fallible<Option<String>> {
if let Err(e) = self.require_window() {
return Ok(Err(e));
}
let id = self.table.get(&this)?.id;
let started = Instant::now();
let result = self.host.wait_loopback(id, Duration::from_millis(u64::from(timeout_ms)), &self.cancel.token());
let waited = started.elapsed();
self.deadline += waited;
self.call_started += waited;
Ok(result.map_err(to_wit))
}
fn drop(&mut self, this: Resource<LoopbackRes>) -> wasmtime::Result<()> {
self.table.delete(this)?;
Ok(())
}
}
impl bindings::openidea::plugin::output::Host for StoreData {
fn append(&mut self, channel: String, text: String) -> Fallible<()> {
Ok(self.host.output_write(&channel, Some(&text)).map_err(to_wit))
}
fn clear(&mut self, channel: String) -> Fallible<()> {
Ok(self.host.output_write(&channel, None).map_err(to_wit))
}
fn reveal(&mut self, channel: String) -> Fallible<()> {
if let Err(e) = self.require_window() {
return Ok(Err(e));
}
Ok(self.host.output_reveal(self.invocation.client.as_deref().expect("checked"), &channel).map_err(to_wit))
}
}
+5 -5
Переглянути файл
@@ -88,15 +88,15 @@ fn the_sdk_carries_the_hosts_wit() {
#[test]
fn the_version_check_runs_compatible_components_and_explains_the_rest() {
let host = v("1.3.0");
for ok in ["1.0.0", "1.3.0", "1.3.7", "1.0.0-rc.1"] {
let host = v("1.4.0");
for ok in ["1.0.0", "1.3.0", "1.3.7", "1.4.0", "1.0.0-rc.1"] {
assert_eq!(check_api(&v(ok), &host), Ok(()), "{ok}");
}
let newer = check_api(&v("1.4.0"), &host).unwrap_err();
assert!(newer.contains("1.4") && newer.contains("update OpenIDEA"), "{newer}");
let newer = check_api(&v("1.5.0"), &host).unwrap_err();
assert!(newer.contains("1.5") && newer.contains("update OpenIDEA"), "{newer}");
assert!(check_api(&v("2.0.0"), &host).unwrap_err().contains("update OpenIDEA"));
let older = check_api(&v("0.2.0"), &host).unwrap_err();
assert!(older.contains("rebuild it with the 1.3 SDK"), "{older}");
assert!(older.contains("rebuild it with the 1.4 SDK"), "{older}");
// 0.x: every minor is its own API.
assert_eq!(check_api(&v("0.2.0"), &v("0.2.5")), Ok(()));
assert!(check_api(&v("0.1.0"), &v("0.2.0")).is_err());
+337
Переглянути файл
@@ -0,0 +1,337 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "anyhow"
version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
[[package]]
name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "equivalent"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
[[package]]
name = "foldhash"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
[[package]]
name = "hashbrown"
version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
dependencies = [
"foldhash",
]
[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "id-arena"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "indexmap"
version = "2.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
"hashbrown",
"serde",
"serde_core",
]
[[package]]
name = "itoa"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "leb128fmt"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
[[package]]
name = "log"
version = "0.4.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
[[package]]
name = "macro-string"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e7b3a5bbb2f63aaa223a671ea1bd0e7bc16bd30ce387324cf63995deaddbbd2"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "openidea-plugin"
version = "0.1.0"
dependencies = [
"serde",
"serde_json",
"wit-bindgen",
]
[[package]]
name = "openidea-plugin-api14"
version = "0.1.0"
dependencies = [
"openidea-plugin",
"serde_json",
]
[[package]]
name = "prettyplease"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0"
dependencies = [
"proc-macro2",
"syn",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "semver"
version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "syn"
version = "3.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "wasm-encoder"
version = "0.262.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a"
dependencies = [
"leb128fmt",
"wasmparser",
]
[[package]]
name = "wasm-metadata"
version = "0.262.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c86ff6668190d9fb70372b306b4f9fe8930f0e2f57ce72e4922bf2f117900949"
dependencies = [
"anyhow",
"indexmap",
"wasm-encoder",
"wasmparser",
]
[[package]]
name = "wasmparser"
version = "0.262.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b"
dependencies = [
"bitflags",
"hashbrown",
"indexmap",
"semver",
]
[[package]]
name = "wit-bindgen"
version = "0.63.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b85a987ab61d365382d25c7d47e26edd48941b3bf6e3fbf76eff918bc71dab06"
dependencies = [
"bitflags",
"wit-bindgen-rust-macro",
]
[[package]]
name = "wit-bindgen-core"
version = "0.63.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "775e122e390603abfacd548027016cd0113a6e2bf2f8ce6bdd3658b013456ea8"
dependencies = [
"anyhow",
"heck",
"wit-parser",
]
[[package]]
name = "wit-bindgen-rust"
version = "0.63.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "84e26e13b9d972026778d2ffb7985736de116026fdc8d9464f966e12df2eb240"
dependencies = [
"anyhow",
"heck",
"indexmap",
"prettyplease",
"syn",
"wasm-metadata",
"wit-bindgen-core",
"wit-component",
]
[[package]]
name = "wit-bindgen-rust-macro"
version = "0.63.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "16a008a0d6b4840677326beb4edbeb210a2f1b7d0183fb7cc33f466b90fd7fb6"
dependencies = [
"anyhow",
"macro-string",
"prettyplease",
"proc-macro2",
"quote",
"syn",
"wit-bindgen-core",
"wit-bindgen-rust",
]
[[package]]
name = "wit-component"
version = "0.262.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "078def49fdb49cab405c3006e05793b3fdaf7069126ba6b9c97d01ec8c98fe4c"
dependencies = [
"anyhow",
"bitflags",
"indexmap",
"log",
"serde",
"serde_derive",
"serde_json",
"wasm-encoder",
"wasm-metadata",
"wasmparser",
"wit-parser",
]
[[package]]
name = "wit-parser"
version = "0.262.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00f0dc051466ffe46787721fca3d088536f158ae400be044f1b1c386ba9397ad"
dependencies = [
"anyhow",
"hashbrown",
"id-arena",
"indexmap",
"log",
"semver",
"serde",
"serde_derive",
"serde_json",
"unicode-ident",
"wasmparser",
]
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+21
Переглянути файл
@@ -0,0 +1,21 @@
[package]
name = "openidea-plugin-api14"
version = "0.1.0"
edition = "2024"
publish = false
[workspace]
[lib]
crate-type = ["cdylib", "rlib"]
[dependencies]
openidea-plugin = { path = "../../../../../sdk/rust/openidea-plugin" }
serde_json = "1"
[profile.release]
opt-level = "s"
lto = true
strip = true
codegen-units = 1
panic = "abort"
Бінарний файл не відображається.
+1
Переглянути файл
@@ -0,0 +1 @@
59145ee5ce6e05000c52d80174156c66e4fcdc5fa9ff329f0d803c15aa1f4fbc
+85
Переглянути файл
@@ -0,0 +1,85 @@
id = "api14"
name = "API 1.4 host tests"
version = "0.1.0"
engines.openidea = "^1.4"
wasm = "dist/plugin.wasm"
activation = ["on-command:*", "on-event:file-closed", "on-event:settings-changed", "on-event:input-mode-changed"]
[capabilities]
required = ["storage"]
optional = ["events", "events.input", "editor.read", "secrets", "net:localhost", "net.http:example.com", "ipc:$TMPDIR/api14-*"]
[[contributes.secrets]]
name = "token"
label = "Token"
[contributes.settings]
schema = "settings.json"
[[contributes.commands]]
id = "ipc"
title = "ipc"
[[contributes.commands]]
id = "fetch"
title = "fetch"
[[contributes.commands]]
id = "window-status"
title = "window-status"
[[contributes.commands]]
id = "remove-window-status"
title = "remove-window-status"
[[contributes.commands]]
id = "global-status"
title = "global-status"
[[contributes.commands]]
id = "execute"
title = "execute"
[[contributes.commands]]
id = "oauth"
title = "oauth"
[[contributes.commands]]
id = "secret"
title = "secret"
[[contributes.commands]]
id = "delete-secret"
title = "delete-secret"
[[contributes.commands]]
id = "undeclared-secret"
title = "undeclared-secret"
[[contributes.commands]]
id = "output"
title = "output"
[[contributes.commands]]
id = "events"
title = "events"
[[contributes.commands]]
id = "process-run"
title = "process-run"
[[contributes.commands]]
id = "process-run-command"
title = "process-run-command"
[[contributes.commands]]
id = "process-start"
title = "process-start"
[[contributes.commands]]
id = "terminal"
title = "terminal"
[[contributes.commands]]
id = "log"
title = "log"
+1
Переглянути файл
@@ -0,0 +1 @@
{"properties":{"enabled":{"type":"boolean","title":"Enabled","default":false}}}
+102
Переглянути файл
@@ -0,0 +1,102 @@
use openidea_plugin::{Error, Event, Invocation, Plugin, StatusItem, host, register_plugin};
#[derive(Default)]
struct Api14;
impl Plugin for Api14 {
fn run_command(&mut self, id: &str, _ctx: &Invocation, arg: Option<&str>) -> Result<Option<String>, Error> {
let arg = arg.unwrap_or_default();
match id {
"ipc" => {
let stream = host::ipc_connect(arg)?;
stream.write(b"echo")?;
let bytes = stream.read(4, 2000)?;
stream.close()?;
Ok(Some(String::from_utf8_lossy(&bytes).into()))
}
"fetch" => {
let response = host::fetch(&openidea_plugin::HttpRequest::get(arg))?;
Ok(Some(String::from_utf8_lossy(&response.body).into()))
}
"global-status" | "window-status" => {
let item = StatusItem { text: arg.into(), tooltip: None, command: Some("events".into()) };
if id == "global-status" {
host::set_status_item("state", &item);
} else {
host::set_window_status_item("state", &item)?;
}
Ok(None)
}
"remove-window-status" => {
host::remove_window_status_item("state")?;
Ok(None)
}
"execute" => host::execute_command(arg, Some("argument")),
"oauth" => {
let redirect = host::begin_loopback("oauth/callback")?;
host::output_append("oauth", &redirect.redirect_uri())?;
redirect.wait(2000)
}
"secret" => {
host::secret_set("token", arg)?;
Ok(None)
}
"delete-secret" => {
host::secret_delete("token")?;
Ok(None)
}
"undeclared-secret" => {
host::secret_set("undeclared", arg)?;
Ok(None)
}
"output" => {
host::output_append("test", arg)?;
host::output_reveal("test")?;
Ok(None)
}
"process-run" => Ok(Some(host::run_process("api14-tool", &[], None)?.stdout)),
"process-run-command" => Ok(Some(host::run_command(&host::Command::new("api14-tool"), None, None)?.stdout)),
"process-start" => {
let child = host::start(&host::Command::new("api14-tool"), None)?;
Ok(Some(child.wait(2000)?.stdout))
}
"terminal" => {
host::open_terminal("API test", "api14-tool", &[])?;
Ok(None)
}
"log" => {
host::open_log_tab(
"api-test",
"API test",
&openidea_plugin::details::ProcessLog {
program: "api14-tool".into(),
args: Vec::new(),
toggles: Vec::new(),
},
)?;
Ok(None)
}
"events" => host::storage::get("events"),
_ => Err(Error::NotFound(id.into())),
}
}
fn handle_events(&mut self, events: &[Event], ctx: &Invocation) {
let mut received: Vec<serde_json::Value> =
host::storage::get("events").unwrap().map(|s| serde_json::from_str(&s).unwrap()).unwrap_or_default();
for event in events {
if let Event::Other { kind, data } = event {
let editor = ctx.editor().map(|e| {
(
e.path(),
e.selections()
.unwrap()
.into_iter()
.map(|r| [r.start.line, r.start.character, r.end.line, r.end.character])
.collect::<Vec<_>>(),
)
});
received.push(serde_json::json!({ "kind": kind, "data": data, "editor": editor }));
}
}
host::storage::set("events", &serde_json::to_string(&received).unwrap()).unwrap();
}
}
register_plugin!(Api14);
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
6d7d707c7492d487fbd9debae791ad7e3755ac005f1f518efa54e6536ec59f08
aae3c82c01b54387a4a18d95614e5275374bb5d1fde8685e11cc4b0ca54f3edb
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
652977e0bf63bc7664807016998a4d4795d2a7eb841ee1912ef562057e5437cb
49a56737954cd79c7dcca5543856473bfe77b420e977c6091ab832bafadac8c1
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
42d3856b634bdaa69e21f4a42a9f375b73c2d19753a8986b82f2228bf92d37bc
07882856be39355607403ff5c2066c537333fc80e5fa4248f7193456c56e34c2
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
cacd381d84e1070fffe8f0ac64fad91b768df63b759c0b3e5e2d22a6a2fdeb73
81f06d523eab81c3a930906750d110d49a2ea1028c41aa825551b854ad2c971c
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
0d418585dca868fbceb6432d06c5c838c3d42a9e99e7a9c7641199f25fb8fbe8
e5552be8e6bcb0dc1aed69b15ef6d56c4861bca507514fd11549387a85703e38
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
6caa94db0c866c0c7f86011dbf837b3f9edb1c891276a4d435a8d02e8f64e0cb
8184794f370596474b2fc306a3adce3f1ce8685bea748442133efd92abab5cdc
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
8d9c6bcd572b6fb54dd42c79d66d4971e55ec3dc072fc769f5634212c2927e22
3b11fb8a7e61919808ef2c09c770be0b6cc86c2ba20abf62aa95b3e7f34c8453
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
2af65b7db7edce8450f0ca829adb3b79fcb64b1ec3d39b785fb9df9423815e7b
1319e0b252577fc01c1b999bb35c43168d2416c985362d49e06e7d627205347b
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
40f80dcba2f370d02e2d5ad9609b21500fc42fc7c7202b439485a9cbf7baf727
d2e60f464a297332b55172cac4968fced00a7ec218af9c6ce7e01b259da515d7
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
a5ca61ba85297c52936cf9892ccf1c678383641c84a5a885389b24582fa1abfb
4daf9ad04a2b10872799976debb792ce24f04fb128e0318e784e6a0a307db9de
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
5723b90f8a742f912b315209fc597e3ea7f428a2a234cf4ea5b4620454206d71
73d73b1e33e2e7ad58db158744630cc53b263213940b8aca251c1fe36f6e9368
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
dd5d41490f53a3b9b03d45ee8aba9f3fb08dd9211e835db5d3f9f7c42d3b6f9a
af621d99276ac3ad29a92c4c056e1bf8ab253b911a0fbd6562f0f227e2941177
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
185557c699fc00796eb487f50c688c3e91d8895bd05d4185b492352c187f9d98
b5e51d67739b775dda14f342db2d0776a0fea5aaf6fe482416b99581c998dd55
+3 -3
Переглянути файл
@@ -5,9 +5,9 @@ wit_bindgen::generate!({
inline: "
package fixture:misbehave;
world misbehave {
include openidea:plugin/plugin-syntax@1.3.0;
export openidea:plugin/providers@1.3.0;
export openidea:plugin/file-actions@1.3.0;
include openidea:plugin/plugin-syntax@1.4.0;
export openidea:plugin/providers@1.4.0;
export openidea:plugin/file-actions@1.4.0;
}
",
path: "../../../../../wit",
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
d047b5618051144ec754b481b6bc75fae428d96c83711e9f0edf78749df59016
85e18a196e960ff9b1bc61bae84fd3f7ec5b08872de0df4b12d6843b0bcea467
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
18957534fc011510894544b61e154a9d0972c27ab1872d9d2accd01864984fa0
15c74b27c3fc5809d061768df0abd84a785a641d685c33fc1ca4c637d7268008
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
3562bc253b0b4f0fa1cb15b9c8a7470a09719b28008aa8f5f459bbaba8eda598
9e8e38868d12ca3ac2504fc6e537cb93efc3fa4db33e08b8abdaaa86e5f6e254
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
f28b40f3708ec4f828d04f7cec29208b66d0ab6158b26c60c0bd989cdc74f9b4
742f536436ef3a6034087a85f41765bbb9a55a8f7ec61e24e752e4dc4031a57b
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
60f6c34375c918ee941dc8f5a1c7851732fd0f5dd2c14ec609db1955c557026a
9c84ce120727c3a85e9d94e607a266b02faf70b5ca77e4b2ee4debcca272e2b1
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
edac658f8a54e396f294c74d031a31787508583256659a8effa8cc3d330e9a08
569e5be98fcf45288141fc40bcb50e0a3fb8038d679c6b9a06c73efd0d425494
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
28e1d58c8ab50574e184cb401050a6fd2755c9398cd3a3720dc376f67461a44b
38c9e6fd9a8aa0b8c6ec830080fbba01a637a98fb0b19f77fbe98324271cb096
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
e80605523d9aaa1c88c83deac439a39a739541bdb327e279352441547de3c232
f9102292daa0fd169e55791b48dae2c10893cb3d867377e0745a013657b1496e
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
efb03a86021bf5690feab0446c77d977c6252a4da1ee41030d923350e6cc5d11
371709b0820de67ce575df082776a9b3c5e116aa44f18c8be53851192431d4f2
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
009f7e069920bcf0e7699b57cd41954dc1dcb620977e081c24ec58ef0a9809d2
81537fa6fb1212fda71bb081df1fceff3a2e27d3df43e89e1b7301d8b9efc306
+98 -57
Переглянути файл
@@ -37,7 +37,7 @@ sdk/rust/openidea-plugin/ # the Rust SDK (host API, Plugin trait, mock host)
crates/ide-plugin/tests/fixtures/ # test plugins: hello, jobs, language-toy, misbehave, semantic-tokens, hover, commit, inlay-hints
```
The plugin API is defined in [`wit/`](../wit/) (`openidea:plugin@1.3.0`, world
The plugin API is defined in [`wit/`](../wit/) (`openidea:plugin@1.4.0`, world
`plugin`).
## 1. Quick start
@@ -299,10 +299,12 @@ machine. Users can revoke optional capabilities in Settings › Plugins.
| `vcs.write` | medium | `Project::vcs_fetch` (trusted projects only), `host::set_commit_message` |
| `storage` | low | `host::storage` (64 MiB per plugin, counting UTF-8 bytes of keys and values) |
| `events` | low | file opened/saved, editor focused, repository changed events |
| `events.input` | medium | `action-performed` events (which actions you run, and how) |
| `events.input` | medium | `action-performed` and `input-mode-changed` events |
| `process:<program>` | high | `Project::run_process`, language servers, debug adapters, runs |
| `net:<host>` | medium | `host::fetch` to that host (`*.example.com`: its subdomains) |
| `secrets` | medium | `{{secret:<name>}}` in request headers, `host::secret_is_set` |
| `net:<host>` | medium | `host::fetch` over HTTPS (also loopback HTTP); `*.example.com` matches subdomains |
| `net.http:<host>` | medium | Unencrypted HTTP to that host; API 1.4, same wildcard rules as `net:` |
| `ipc:<path>` | high | Local Unix sockets or Windows named pipes on the project machine; API 1.4 |
| `secrets` | medium | `{{secret:<name>}}` in request headers, `host::secret_is_set`, `secret_set`, `secret_delete` |
| `clipboard` | medium | `host::copy_to_clipboard` and the clipboard API in the plugin's web views |
`process:` capabilities are also derived from what the contributions start: a
@@ -438,45 +440,51 @@ then run `openidea-plugin check`.
### The API
| Rust SDK | WIT | Notes |
| ------------------------------------------------------------------------ | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Plugin::run_command(id, ctx, arg)` | export `commands.run` | `ctx` is the window: `ctx.project()`, `ctx.editor()`. An error shows _"<title> failed: …"_; the plugin keeps running. `"msg".into()` is `Error::Failed`; `Cancelled` and `Denied` don't count as the plugin failing. |
| `Plugin::handle_events(events, ctx)` | export `event-handler.handle` | Batches of subscribed events, oldest first, per window. |
| `Plugin::activate` / `deactivate` | export `lifecycle` | Per instance: after a crash or idle reclaim a new one is activated. |
| `TextEditor::document()` → `{version, text}` | `editor.text-editor.document` | `selections()` are those when the command ran (0-based lines, UTF-16 columns). |
| `TextEditor::apply_edits(version, edits)` | `editor.text-editor.apply-edits` | One undoable change, only if the document is still at `version` — else `Error::Stale` and nothing changes. `transform_selections` retries once. |
| `Project::root()`, `read_file(path)` | `workspace.project` | Absolute or project-relative; `..`/symlinks escaping the root are rejected; UTF-8 only, ≤ 16 MiB; unsaved editor contents win; a missing path is `Error::NotFound`. |
| `Project::exists(path)`, `stat(path)` | `workspace.project` | `exists` covers files and directories, hidden and ignored included, without reading content; `stat` gives kind, size and modified time (`Error::NotFound` for a missing path). |
| `host::projects()` | `workspace.projects` | Every open project (for scheduled work without a window). |
| `Project::vcs_status()`, `vcs_remotes()`, `vcs_fetch()` | `vcs` | `vcs_remotes` returns `(name, url)` pairs; fetch runs git, so only in trusted projects (call it inside a task). |
| `host::pending_commit()`, `host::set_commit_message(revision, text)` | `commit` | The commit being prepared in the calling window and its message; see _Commits_. |
| `host::subscribe(kind)` | `events.subscribe` | For the session, across idle reclaim (an event activates the plugin). Or declare `on-event:<kind>`. |
| `host::begin_task(title, cancellable)` → `Task` | `tasks.begin` | Shown with the background tasks; `report`, `is_cancelled`; the call may run 60 s instead of 5 s while it is open; dropping it ends it. |
| `host::storage::{get, set, delete, keys}` | `storage` | Survives restarts; the instance's memory does not. Deleted on uninstall. |
| `host::set_status_item(id, item)`, `remove_status_item` | `ui` | `text`, `tooltip`, `command` (one of yours, run on click); at most 8; kept while the plugin is idle. |
| `host::set_context(key, value)`, `remove_context` | `ui.{set,remove}-context` | Sets `plugin.<id>.<key>` for `when` clauses in the window the call came from (`true`, `3.5`, `"text"`; `ContextValue`). Key 1–64 of `A-Za-z0-9_-`, 100 per plugin; gone when the plugin stops. |
| `host::notify(level, title, body)` | `ui.show-notification` | Balloon in the window the command or events came from (every window otherwise). |
| `host::copy_to_clipboard(text)` | `ui.copy-to-clipboard` | Copies `text` to the system clipboard. Needs `clipboard`. |
| `host::open_url(url)` | `ui.open-url` | Opens an `http://` or `https://` URL in the user's default browser. |
| `host::pick(title, items)`, `pick_many` | `ui.pick`, `ui.pick-many` | Picks key(s) from `PickItem`s, or `None` when dismissed. From a command/event or code-action resolution in its editor window (else `invalid`); waiting is excluded from the budget. |
| `host::input(prompt, value)` | `ui.input` | A one-line text box pre-filled with `value`; `None` when dismissed. Same rules as `pick`. |
| `host::input_multiline(prompt, value)` | `ui.input-multiline` | A multi-line text box pre-filled with `value`; `None` when dismissed; Cmd/Ctrl+Enter confirms. Only from a command or event of a window. |
| `host::confirm(title, body)` | `ui.confirm` | OK / Cancel; `true` on OK. Same rules as `pick`. |
| `host::locale()` | `ui.locale` | The IDE's UI language as a BCP 47 tag (`en`, `fr`, `zh-CN`); no capability. See _Translations_. |
| `host::log(level, msg)` | `log` | IDE log, tagged with the plugin id. `eprintln!` output is logged too and shown when the plugin crashes. |
| `Project::find_files(glob, limit)` | `workspace.project.find-files` | Project-relative glob (`**/*Mapper.xml`); honours `.gitignore`; at most `limit` paths. |
| `Project::symbols(query, limit)` | `workspace.symbols` | New in 1.3; `project.read`. Fuzzy in-memory search (no LSP): name, camelCase kind, container and UTF-16 location. Queries ≤ 256 UTF-8 bytes; limits capped at 1000. Snapshot notes below. |
| `host::publish_diagnostics(path, items)` | `diagnostics.publish` | Replaces this plugin's problems for the file (editor squiggles and the Problems view); an empty list clears them. |
| `host::fetch(request)` → `{status, headers, body}` | `net.fetch` | See _Network_. |
| `Project::run_process(program, args, stdin)` → `{code, stdout, stderr}` | `process.run` | Only the pinned program of a `process:` grant; runs in the project root of a trusted project; 4 MiB of output; killed when the call is cancelled or times out. |
| `host::run_command(cmd, project, stdin)` → `{code, stdout, stderr}` | `process.run-command` | API 1.3: same limits as `run_process`, with append-only environment variables; needs the pinned `process:<program>` grant. |
| `host::start(cmd, project)` → `Child` | `process.start` | API 1.3: `poll(max_bytes)`, `write(text)`, `close_stdin()`, `wait(timeout_ms)`, `kill()`; at most 8 handles; dropping one kills its process. |
| `host::refresh_view(view)` | `views.refresh` | The view (or custom editors) render again; call it when the content changed. |
| `host::reveal_view(view)` | `views.reveal` | Brings one of your declared `[[contributes.views]]` to the front in the calling window. |
| `host::post_view_message(view, text)` | `views.post-message` | To the script of the view's `html` body. |
| `host::open_terminal(title, program, args)` | `views.open-terminal` | A terminal tab in the invoking window running the approved `process:<program>` in the project root: output that keeps coming, interactive sessions. |
| `host::open_location(path, line, column)` | `views.open-location` | Opens a file inside the project in an editor of the invoking window, the caret at `line`/`column` (0-based, UTF-16): a view's links to code. Needs `project.read`. |
| `host::setting(key)`, `setting_bool`, `setting_string`, `setting_number` | `settings.get` | The user's value (project over global) or the schema's default. |
| Rust SDK | WIT | Notes |
| ------------------------------------------------------------------------- | ------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Plugin::run_command(id, ctx, arg)` | export `commands.run` | `ctx` is the window: `ctx.project()`, `ctx.editor()`. An error shows _"<title> failed: …"_; the plugin keeps running. `"msg".into()` is `Error::Failed`; `Cancelled` and `Denied` don't count as the plugin failing. |
| `Plugin::handle_events(events, ctx)` | export `event-handler.handle` | Batches of subscribed events, oldest first, per window. |
| `Plugin::activate` / `deactivate` | export `lifecycle` | Per instance: after a crash or idle reclaim a new one is activated. |
| `TextEditor::document()` → `{version, text}` | `editor.text-editor.document` | `selections()` are those when the command ran (0-based lines, UTF-16 columns). |
| `TextEditor::apply_edits(version, edits)` | `editor.text-editor.apply-edits` | One undoable change, only if the document is still at `version` — else `Error::Stale` and nothing changes. `transform_selections` retries once. |
| `Project::root()`, `read_file(path)` | `workspace.project` | Absolute or project-relative; `..`/symlinks escaping the root are rejected; UTF-8 only, ≤ 16 MiB; unsaved editor contents win; a missing path is `Error::NotFound`. |
| `Project::exists(path)`, `stat(path)` | `workspace.project` | `exists` covers files and directories, hidden and ignored included, without reading content; `stat` gives kind, size and modified time (`Error::NotFound` for a missing path). |
| `host::projects()` | `workspace.projects` | Every open project (for scheduled work without a window). |
| `Project::vcs_status()`, `vcs_remotes()`, `vcs_fetch()` | `vcs` | `vcs_remotes` returns `(name, url)` pairs; fetch runs git, so only in trusted projects (call it inside a task). |
| `host::pending_commit()`, `host::set_commit_message(revision, text)` | `commit` | The commit being prepared in the calling window and its message; see _Commits_. |
| `host::subscribe(kind)` | `events.subscribe` | For the session, across idle reclaim (an event activates the plugin). Or declare `on-event:<kind>`. |
| `host::begin_task(title, cancellable)` → `Task` | `tasks.begin` | Shown with the background tasks; `report`, `is_cancelled`; the call may run 60 s instead of 5 s while it is open; dropping it ends it. |
| `host::storage::{get, set, delete, keys}` | `storage` | Survives restarts; the instance's memory does not. Deleted on uninstall. |
| `host::set_status_item(id, item)`, `remove_status_item` | `ui` | `text`, `tooltip`, `command` (one of yours, run on click); at most 8; kept while the plugin is idle. |
| `host::set_window_status_item(id, item)`, `remove_window_status_item(id)` | `ui.{set,remove}-window-status-item` | API 1.4: window-only override; removed on window close or plugin stop; removing falls back to the global item. Click runs its command in that window. |
| `host::execute_command(id, arg)` → `Option<String>` | `command-runner.execute` | API 1.4: stable IDE action or `plugin.<plugin-id>.<command-id>` in the invoking window. IDE actions return none; plugin commands return their result. Unknown ids are not-found; at most 8 nested calls, no re-entry into a waiting instance. |
| `host::ipc_connect(name)` → `Connection` | `ipc.connect` | API 1.4: `write(bytes)`, `read(max_bytes, timeout_ms)`, `close()`; requires `ipc:<path>`, at most 8 connections, closed on drop or plugin stop. Runs on the project server in remote projects. |
| `host::secret_set(name, value)`, `secret_delete(name)` | `secrets.{set,delete}` | API 1.4: requires `secrets` and a declared name. Never returns the value. |
| `host::begin_loopback(path)` → `Loopback` | `auth.begin-loopback` | API 1.4: `redirect_uri()`, `wait(timeout_ms)` → raw query or none on timeout. Desktop-only, even for remote projects; no capability. At most 2 listeners; one-shot, closed on timeout, drop or stop. Waiting excludes the call budget. |
| `host::output_append(channel, text)`, `output_clear`, `output_reveal` | `output.{append,clear,reveal}` | API 1.4: read-only Output tabs; 32 named channels per plugin, each a 1 MiB UTF-8 ring buffer. Reveal requires the invoking window. |
| `host::set_context(key, value)`, `remove_context` | `ui.{set,remove}-context` | Sets `plugin.<id>.<key>` for `when` clauses in the window the call came from (`true`, `3.5`, `"text"`; `ContextValue`). Key 1–64 of `A-Za-z0-9_-`, 100 per plugin; gone when the plugin stops. |
| `host::notify(level, title, body)` | `ui.show-notification` | Balloon in the window the command or events came from (every window otherwise). |
| `host::copy_to_clipboard(text)` | `ui.copy-to-clipboard` | Copies `text` to the system clipboard. Needs `clipboard`. |
| `host::open_url(url)` | `ui.open-url` | Opens an `http://` or `https://` URL in the user's default browser. |
| `host::pick(title, items)`, `pick_many` | `ui.pick`, `ui.pick-many` | Picks key(s) from `PickItem`s, or `None` when dismissed. From a command/event or code-action resolution in its editor window (else `invalid`); waiting is excluded from the budget. |
| `host::input(prompt, value)` | `ui.input` | A one-line text box pre-filled with `value`; `None` when dismissed. Same rules as `pick`. |
| `host::input_multiline(prompt, value)` | `ui.input-multiline` | A multi-line text box pre-filled with `value`; `None` when dismissed; Cmd/Ctrl+Enter confirms. Only from a command or event of a window. |
| `host::confirm(title, body)` | `ui.confirm` | OK / Cancel; `true` on OK. Same rules as `pick`. |
| `host::locale()` | `ui.locale` | The IDE's UI language as a BCP 47 tag (`en`, `fr`, `zh-CN`); no capability. See _Translations_. |
| `host::log(level, msg)` | `log` | IDE log, tagged with the plugin id. `eprintln!` output is logged too and shown when the plugin crashes. |
| `Project::find_files(glob, limit)` | `workspace.project.find-files` | Project-relative glob (`**/*Mapper.xml`); honours `.gitignore`; at most `limit` paths. |
| `Project::symbols(query, limit)` | `workspace.symbols` | New in 1.3; `project.read`. Fuzzy in-memory search (no LSP): name, camelCase kind, container and UTF-16 location. Queries ≤ 256 UTF-8 bytes; limits capped at 1000. Snapshot notes below. |
| `host::publish_diagnostics(path, items)` | `diagnostics.publish` | Replaces this plugin's problems for the file (editor squiggles and the Problems view); an empty list clears them. |
| `host::fetch(request)` → `{status, headers, body}` | `net.fetch` | See _Network_. |
| `Project::run_process(program, args, stdin)` → `{code, stdout, stderr}` | `process.run` | Only the pinned program of a `process:` grant; runs in the project root of a trusted project; 4 MiB of output; killed when the call is cancelled or times out. |
| `host::run_command(cmd, project, stdin)` → `{code, stdout, stderr}` | `process.run-command` | API 1.3: same limits as `run_process`, with append-only environment variables; needs the pinned `process:<program>` grant. |
| `host::start(cmd, project)` → `Child` | `process.start` | API 1.3: `poll(max_bytes)`, `write(text)`, `close_stdin()`, `wait(timeout_ms)`, `kill()`; at most 8 handles; dropping one kills its process. |
| `host::refresh_view(view)` | `views.refresh` | The view (or custom editors) render again; call it when the content changed. |
| `host::reveal_view(view)` | `views.reveal` | Brings one of your declared `[[contributes.views]]` to the front in the calling window. |
| `host::post_view_message(view, text)` | `views.post-message` | To the script of the view's `html` body. |
| `host::open_terminal(title, program, args)` | `views.open-terminal` | A terminal tab in the invoking window running the approved `process:<program>` in the project root: output that keeps coming, interactive sessions. |
| `host::open_location(path, line, column)` | `views.open-location` | Opens a file inside the project in an editor of the invoking window, the caret at `line`/`column` (0-based, UTF-16): a view's links to code. Needs `project.read`. |
| `host::setting(key)`, `setting_bool`, `setting_string`, `setting_number` | `settings.get` | The user's value (project over global) or the schema's default. |
`Project::symbols` reads the current in-memory index: results may be partial
while indexing, and locations can lag unsaved edits. Normal saves and filesystem
@@ -507,15 +515,18 @@ from another feature, or nothing when run from Search Everywhere / a shortcut. `
### Events
| Kind | Capability | Delivered |
| ------------------ | -------------- | ------------------------------------------------------------------------- |
| `file-opened` | `events` | a file opens in an editor |
| `files-changed` | `events` | debounced created, modified and removed paths in open projects (API 1.3) |
| `file-saved` | `events` | after the file is written |
| `editor-focused` | `events` | the focused editor changes (path, or none) |
| `vcs-changed` | `events` | a repository's state changed (commit, checkout, fetch…; its root) |
| `action-performed` | `events.input` | an IDE action ran: id, title, source (keyboard, menu, toolbar…), shortcut |
| `scheduled` | — | the `on-schedule` period elapsed |
| Kind | Capability | Delivered |
| -------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `file-opened` | `events` | a file opens in an editor |
| `file-closed` | `events` | API 1.4, `Event::Other`: JSON path string |
| `settings-changed` | `events` | API 1.4, `Event::Other`: JSON array of this plugin's changed setting keys (effective values) |
| `input-mode-changed` | `events.input` | API 1.4, `Event::Other`: JSON `{path, mode, sub}` on focused Vim mode changes; `ctx.editor()` includes the document and current selections |
| `files-changed` | `events` | debounced created, modified and removed paths in open projects (API 1.3) |
| `file-saved` | `events` | after the file is written |
| `editor-focused` | `events` | the focused editor changes (path, or none) |
| `vcs-changed` | `events` | a repository's state changed (commit, checkout, fetch…; its root) |
| `action-performed` | `events.input` | an IDE action ran: id, title, source (keyboard, menu, toolbar…), shortcut |
| `scheduled` | — | the `on-schedule` period elapsed |
Events are batched: a running plugin gets them within a fraction of a second,
an idle one collects them for 2 s before it is woken, so frequent events
@@ -807,10 +818,19 @@ scrolling. Labels are cut at 256 bytes and tooltips at 1 KiB.
### Network and secrets
`host::fetch` makes an HTTPS request (plain HTTP only to `localhost`) to a host
the plugin was granted with `net:<host>`; redirects to another host are
refused and responses are limited to 8 MiB. Requests are made from the
machine the project is on.
`host::fetch` requires `net:<host>` for HTTPS and loopback HTTP. API 1.4 adds
`net.http:<host>` for unencrypted HTTP to other hosts; it does not imply an
HTTPS grant. Both use the same wildcard rules. Each redirect is checked before
connecting to the destination; HTTPS → HTTP also requires `net.http:<host>`,
even on loopback. Responses are limited to 8 MiB. Requests run on the project
machine. A manifest using `net.http:` or `ipc:` declares `engines.openidea = "^1.4"`.
`ipc:<path>` grants a local byte stream: an absolute Unix socket path (the host
expands `~/`, `$TMPDIR/` and `$XDG_RUNTIME_DIR/`) or `\\.\pipe\<name>` on Windows.
Only a grant's last path segment may contain `*`, for example
`ipc:$TMPDIR/discord-ipc-*`. It never grants TCP. A remote project's connection
runs on the server. Reads and writes honor cancellation and the call budget;
reads return empty bytes on timeout or EOF, and each operation is capped at 1 MiB.
Secrets declared under `[[contributes.secrets]]` are entered by the user in
Settings › Plugins and kept in the system keychain. The plugin never reads
@@ -818,6 +838,27 @@ them: it writes `{{secret:<name>}}` in a request header and the host fills it
in on the way out (`secrets` capability). `host::secret_is_set(name)` tells
whether the user has entered one.
API 1.4 can also store or delete declared secrets with `host::secret_set` and
`host::secret_delete`; the plugin still cannot read them. An OAuth flow uses
`begin_loopback("oauth/callback")`, `ui.open-url` with its `redirect_uri()`,
`wait`, an authorized `net.fetch` code exchange and `secrets.set` for the token.
The listener binds only `127.0.0.1` on a random port on the **desktop**, including
for remote projects, serves "You can close this tab", then closes. There are
no OS URI callbacks or `on-uri` activation. Validate OAuth state in the plugin.
Window status overrides, command execution, loopback creation/waiting and
output reveal are valid only in a command or event from a window. The Vim
context key `vim.mode` is `normal`, `insert`, `visual` or `replace`, and empty
when Vim is disabled. Subscribing to the three new event kinds, including
`on-event:<kind>` activation, requires `engines.openidea = "^1.4"`.
Settings › Plugins lets the user choose the executable of a `process:<name>`
grant globally or for the current project. The native chooser's selection is
approved again and pinned by path and content hash. Project choices override
the global choice for runs, process handles, terminals and log panes. Resetting
a choice verifies its fallback, or revokes the grant if that is unavailable.
The plugin continues to call its declared program name.
### Views and custom editors
A view is data: a toolbar, a body — `Tree`, `List`, `Form`, `Table`,
@@ -1753,7 +1794,7 @@ the API itself follows _Evolving the plugin API_ below.
## 10. Evolving the plugin API
Released versions are frozen: 1.0.0 shipped with OpenIDEA 0.1.36, 1.1.0
with 0.1.37 and 1.2.0 with 0.1.38. wasmtime decides what stays compatible: it resolves interface names
with 0.1.37, 1.2.0 with 0.1.38 and 1.3.0 with 0.1.39. wasmtime decides what stays compatible: it resolves interface names
by semver (a component importing `openidea:plugin/[email protected]` links against a
host defining `@1.1.0`, and the host finds its exports the same way), but
function types must match exactly — a record with another field count, or a
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
7dfbea1faeae8930b462fe80d431c83c49aeafa45ac7acd36f7d7f05fac3aaa4
8a1b87e6985c9bff6f034b56c4d4bf967a96f7579d5aff79213e631a95722408
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
adeef6ba69276d3ac8e9ba349ca6e787befa6532ccac69bc35a381c0428af189
1b68413078837975701fd58850a7f5dc1960de2ccc8e7f20effa57c2ca595eaf
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
51def3be1a570ee61cb23f0b738002427298dbdafffcb687896531685bbe3c77
2282cc3959e7b3576714d5dad611b51c404143ffbdadba809d0e3bc2d2afad29
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
6c4439b36b22289c8dc54498d6e7e72a4c4cc15eac1a4957fc2b71d4fbd3c330
eeb7ccd4b23564f1bb61edd50c4e3c50e445a028a0b4f90371b16b39bd1a40b4
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
00d56f431ab8e59c04796cf56054a98ba78040a5e4142c3f727725c31781a008
15d35ef3cbc8b81a16f66d645f6f4c8d20ccda9bbff911ca1548866d77d7b9a4
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
9fca272eec5a601b8de6071aa358954e9b79db08f45714f077624418e8f616bc
418d6e2b7725cc1099997febd78705f27b2b1739121e98a3db4fe43ae3c21b02
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
5adfc0d749feabe5fe7e20857fd636d01341b91f3dd8440779af6dcd14435619
f280966be4b29a792d1494bfbac1695b750895ded1011ba1a4b9501981b73997
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
1b388c40cb6be29c5e10e938c0c8f6848d10cb4bf1f7438db37f53b13314708e
db4087cf4c2265c78508949d167d0c3e8b5c0b9434000101d201d12196bed3f1
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
af4478864196b5802f505d26beafe4492bc1335536311bc873b9d18773f9eebb
85653ef957f5e0483889ea750e486c79fe7e6630fee65ff2aa2e187abbcf7964
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
46ce9f2d5b4f87a4be26facea4870f3de59952dc95c536fcf33fb0ff0a7c27a7
b488971480de36f755c1ed0e0d496ac356e24dae34ccf7b487468bf6688ab36a
Loaded 100 of 165 files, more files were not shown because too many files have changed in this diff. Show more