mirror of
https://github.com/storytold/figcraft.git
synced 2026-12-02 15:01:23 -05:00
* M11: a plugin can read the web hosts its manifest names (#1883) A plugin can read fresh data (catalogues, tokens, translations) from exact hosts it names in permissions.network (plugin API 9: allowedDomains, methods GET/HEAD). The new http_request host import asks FigCraft for an https:// address on one of those hosts; FigCraft makes the request through the session's network link with no credentials, follows no redirects (the plugin gets status and location), allows 8 requests per run or callback and fails a response over 4 MB. Any other scheme, host, port, user info or method is refused before anything is sent, and a session confined to automation roots makes no requests. Importing such a plugin needs the user's approval: plugin.import takes confirm: true for it and check: true to report what a manifest asks for without installing it; the app's import shows the hosts with Import and Cancel. Manage plugins lists the hosts. A plugin directory entry can't show the hosts yet, so directories neither publish nor install such plugins. The SDK gains http_request. * Plugin web requests reach only public addresses, and an approved import must match what was shown Review fixes for #1883. A plugin's request uses no proxy and a resolver that keeps only public addresses, so a host that resolves to this computer or the local network (an approved name rebinding to one included) is refused when it connects; IP literals are refused in permissions.network. The app's Import passes the network permission it showed as confirm, and plugin.import refuses a manifest that now asks for other hosts or methods (confirm: true still works for scripts).
This commit is contained in:
@@ -355,6 +355,6 @@ pub(crate) fn background(job: u64, req: NetRequest) -> Option<Next> {
|
||||
)
|
||||
}
|
||||
},
|
||||
NetRequest::Upload(_) | NetRequest::Web { .. } => return None,
|
||||
NetRequest::Upload(_) | NetRequest::Web { .. } | NetRequest::Http { .. } => return None,
|
||||
})
|
||||
}
|
||||
|
||||
+118
-11
@@ -1,13 +1,19 @@
|
||||
//! Reading a web page or picture for a board's link card ([`NetRequest::Web`]): `http` and
|
||||
//! `https` only, a few seconds at most, a few redirects, and at most [`MAX_WEB_BYTES`] of body
|
||||
//! (after decompression). Nothing is sent but the request itself: no cookies, no credentials.
|
||||
//! A plugin's request ([`NetRequest::Http`]) is the same, but `https` only and with no redirects
|
||||
//! followed (the plugin gets the redirect and may ask for its target, which is checked again),
|
||||
//! no proxy, and only to public addresses: a host that resolves to this machine or the local
|
||||
//! network is refused when it connects, so a rebinding name can't reach either.
|
||||
//!
|
||||
//! [`NetRequest::Web`]: figcraft_engine::live::NetRequest::Web
|
||||
//! [`NetRequest::Http`]: figcraft_engine::live::NetRequest::Http
|
||||
|
||||
use std::io::Read;
|
||||
use std::net::IpAddr;
|
||||
use std::time::Duration;
|
||||
|
||||
use figcraft_engine::live::{MAX_WEB_BYTES, WebPage};
|
||||
use figcraft_engine::live::{HttpResponse, MAX_WEB_BYTES, WebPage};
|
||||
use ureq::ResponseExt;
|
||||
|
||||
/// Read `url` (see the module docs).
|
||||
@@ -16,24 +22,102 @@ pub(crate) fn web(url: &str) -> Result<WebPage, String> {
|
||||
if !matches!(scheme.as_deref(), Some("http" | "https")) {
|
||||
return Err("only http and https addresses have previews".into());
|
||||
}
|
||||
let tls = ureq::tls::TlsConfig::builder().root_certs(ureq::tls::RootCerts::PlatformVerifier).build();
|
||||
let agent = ureq::Agent::config_builder()
|
||||
.tls_config(tls)
|
||||
.timeout_connect(Some(Duration::from_secs(5)))
|
||||
.timeout_global(Some(Duration::from_secs(10)))
|
||||
.max_redirects(5)
|
||||
.user_agent(concat!("FigCraft/", env!("CARGO_PKG_VERSION"), " (link preview)"))
|
||||
.build()
|
||||
let agent = config(ureq::Agent::config_builder().max_redirects(5).user_agent(concat!("FigCraft/", env!("CARGO_PKG_VERSION"), " (link preview)")))
|
||||
.new_agent();
|
||||
let mut resp = agent.get(url).call().map_err(|e| format!("couldn't reach {}: {e}", host(url)))?;
|
||||
let content_type = resp.headers().get("content-type").and_then(|v| v.to_str().ok()).unwrap_or_default().to_string();
|
||||
let final_url = resp.get_uri().to_string();
|
||||
// The cap is on the decoded body: a small compressed answer can't grow past it.
|
||||
let content_type = header(&resp, "content-type");
|
||||
let mut body = Vec::new();
|
||||
resp.body_mut().with_config().reader().take(MAX_WEB_BYTES as u64).read_to_end(&mut body).map_err(|e| e.to_string())?;
|
||||
Ok(WebPage { url: final_url, content_type, body })
|
||||
}
|
||||
|
||||
/// A plugin's `GET` or `HEAD` request to `url` (see the module docs); the engine has checked both
|
||||
/// against the plugin's manifest. A body over [`MAX_WEB_BYTES`] fails rather than arriving cut.
|
||||
pub(crate) fn http(url: &str, method: &str) -> Result<HttpResponse, String> {
|
||||
let config = config(ureq::Agent::config_builder().https_only(true).max_redirects(0).http_status_as_error(false).proxy(None).user_agent(concat!(
|
||||
"FigCraft/",
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
" (plugin)"
|
||||
)));
|
||||
let agent = ureq::Agent::with_parts(config, ureq::unversioned::transport::DefaultConnector::new(), PublicOnly::default());
|
||||
let call = match method {
|
||||
"GET" => agent.get(url).call(),
|
||||
"HEAD" => agent.head(url).call(),
|
||||
_ => return Err(format!("plugins can't send {method} requests")),
|
||||
};
|
||||
let mut resp = call.map_err(|e| format!("couldn't reach {}: {e}", host(url)))?;
|
||||
let (status, content_type, location) = (resp.status().as_u16(), header(&resp, "content-type"), header(&resp, "location"));
|
||||
let mut body = Vec::new();
|
||||
// A HEAD answer has no body, though its headers may say it's compressed.
|
||||
if method != "HEAD" {
|
||||
resp.body_mut().with_config().reader().take(MAX_WEB_BYTES as u64 + 1).read_to_end(&mut body).map_err(|e| e.to_string())?;
|
||||
}
|
||||
if body.len() > MAX_WEB_BYTES {
|
||||
return Err(format!("the response from {} is larger than {} MB", host(url), MAX_WEB_BYTES >> 20));
|
||||
}
|
||||
Ok(HttpResponse { status, content_type, location, body })
|
||||
}
|
||||
|
||||
/// `config` trusting the platform's certificates and waiting a few seconds at most. The body cap is
|
||||
/// on the decoded body: a small compressed answer can't grow past it.
|
||||
fn config(config: ureq::config::ConfigBuilder<ureq::typestate::AgentScope>) -> ureq::config::Config {
|
||||
let tls = ureq::tls::TlsConfig::builder().root_certs(ureq::tls::RootCerts::PlatformVerifier).build();
|
||||
config.tls_config(tls).timeout_connect(Some(Duration::from_secs(5))).timeout_global(Some(Duration::from_secs(10))).build()
|
||||
}
|
||||
|
||||
/// Resolves as usual but keeps only public addresses (see the module docs).
|
||||
#[derive(Debug, Default)]
|
||||
struct PublicOnly(ureq::unversioned::resolver::DefaultResolver);
|
||||
|
||||
impl ureq::unversioned::resolver::Resolver for PublicOnly {
|
||||
fn resolve(
|
||||
&self,
|
||||
uri: &ureq::http::Uri,
|
||||
config: &ureq::config::Config,
|
||||
timeout: ureq::unversioned::transport::NextTimeout,
|
||||
) -> Result<ureq::unversioned::resolver::ResolvedSocketAddrs, ureq::Error> {
|
||||
let mut addrs = self.empty();
|
||||
for a in self.0.resolve(uri, config, timeout)?.iter().filter(|a| public(a.ip())) {
|
||||
let _ = addrs.try_push(*a);
|
||||
}
|
||||
if addrs.is_empty() {
|
||||
return Err(ureq::Error::BadUri("it resolves only to this computer or the local network".into()));
|
||||
}
|
||||
Ok(addrs)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `ip` is on the internet: not this computer, the local network, a link-local, shared,
|
||||
/// documentation or unspecified address.
|
||||
fn public(ip: IpAddr) -> bool {
|
||||
match ip {
|
||||
IpAddr::V4(v4) => {
|
||||
let [a, b, ..] = v4.octets();
|
||||
!(v4.is_private()
|
||||
|| v4.is_loopback()
|
||||
|| v4.is_link_local()
|
||||
|| v4.is_unspecified()
|
||||
|| v4.is_broadcast()
|
||||
|| v4.is_documentation()
|
||||
|| a == 0
|
||||
|| (a == 100 && (64..128).contains(&b)))
|
||||
}
|
||||
IpAddr::V6(v6) => match v6.to_ipv4_mapped() {
|
||||
Some(v4) => public(IpAddr::V4(v4)),
|
||||
None => {
|
||||
let first = v6.segments()[0];
|
||||
!(v6.is_loopback() || v6.is_unspecified() || (first & 0xfe00) == 0xfc00 || (first & 0xffc0) == 0xfe80)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Header `name` of `resp` as text (empty when missing or not text).
|
||||
fn header(resp: &ureq::http::Response<ureq::Body>, name: &str) -> String {
|
||||
resp.headers().get(name).and_then(|v| v.to_str().ok()).unwrap_or_default().to_string()
|
||||
}
|
||||
|
||||
/// The host of `url`, for a message (never its path or query, which can carry tokens).
|
||||
fn host(url: &str) -> &str {
|
||||
let rest = url.split_once("://").map_or(url, |(_, r)| r);
|
||||
@@ -47,6 +131,29 @@ mod tests {
|
||||
fn only_web_addresses_are_read_and_messages_name_only_the_host() {
|
||||
assert!(super::web("file:///etc/passwd").is_err());
|
||||
assert!(super::web("ftp://example.com/").is_err());
|
||||
assert!(super::http("http://example.com/", "GET").is_err(), "plugins get https only");
|
||||
assert_eq!(super::host("https://user:secret@example.com:8080/a?token=x"), "example.com:8080");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugins_reach_only_public_addresses() {
|
||||
for local in [
|
||||
"127.0.0.1",
|
||||
"10.0.0.5",
|
||||
"172.16.1.1",
|
||||
"192.168.1.1",
|
||||
"169.254.169.254",
|
||||
"100.64.0.1",
|
||||
"0.0.0.0",
|
||||
"::1",
|
||||
"fd00::1",
|
||||
"fe80::1",
|
||||
"::ffff:192.168.1.1",
|
||||
] {
|
||||
assert!(!super::public(local.parse().unwrap()), "{local}");
|
||||
}
|
||||
for public in ["93.184.215.14", "2606:2800:21f:cb07:6820:80da:af6b:8b2c"] {
|
||||
assert!(super::public(public.parse().unwrap()), "{public}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,8 +8,8 @@ use std::time::Duration;
|
||||
use figcraft_collab::code;
|
||||
use figcraft_collab::message::{Access, Admin, AdminReply, ClientMsg, LibraryReply, LibraryReq, PluginReply, PluginReq};
|
||||
use figcraft_engine::live::{
|
||||
Bind, Event, HostInfo, HostOptions, LiveLink, NO_SESSION, NetReply, NetRequest, PageInfo, Presence, PublishOptions, Published, Resume, Role,
|
||||
SessionId, SessionInfo, Shared, WayIn, WebPage,
|
||||
Bind, Event, HostInfo, HostOptions, HttpResponse, LiveLink, NO_SESSION, NetReply, NetRequest, PageInfo, Presence, PublishOptions, Published,
|
||||
Resume, Role, SessionId, SessionInfo, Shared, WayIn, WebPage,
|
||||
};
|
||||
|
||||
use crate::guest::{Guest, GuestConfig, Publish, upload_file};
|
||||
@@ -274,6 +274,10 @@ impl LiveLink for NetLink {
|
||||
crate::fetch::web(url)
|
||||
}
|
||||
|
||||
fn http(&mut self, url: &str, method: &str) -> Result<HttpResponse, String> {
|
||||
crate::fetch::http(url, method)
|
||||
}
|
||||
|
||||
fn background(&mut self, job: u64, req: NetRequest) -> bool {
|
||||
let (inbox, limits) = (self.libraries.clone(), self.limits);
|
||||
let (failed, failure) = (inbox.clone(), req.failure());
|
||||
@@ -285,6 +289,7 @@ impl LiveLink for NetLink {
|
||||
NetRequest::Hosting { server, file, owner, req } => NetReply::Hosting(hosting(&server, &file, &owner, req, &limits)),
|
||||
NetRequest::Share { server, file, owner, revoke, create } => NetReply::Share(share(&server, &file, &owner, &revoke, create, &limits)),
|
||||
NetRequest::Web { url } => NetReply::Web(crate::fetch::web(&url)),
|
||||
NetRequest::Http { url, method } => NetReply::Http(crate::fetch::http(&url, &method)),
|
||||
};
|
||||
inbox.push(Event::Net { job, reply: Box::new(reply) });
|
||||
});
|
||||
|
||||
@@ -475,7 +475,7 @@ pub fn network_refused() -> Option<String> {
|
||||
}
|
||||
|
||||
/// What a confined command that would reach the network says.
|
||||
pub const NETWORK_REFUSED: &str = "automation roots are set: commands don't reach the network (publishing, live sessions, team libraries, plugin directories and link previews are off)";
|
||||
pub const NETWORK_REFUSED: &str = "automation roots are set: commands don't reach the network (publishing, live sessions, team libraries, plugin directories, link previews and plugin web requests are off)";
|
||||
|
||||
/// The path to use for `access` to `path`: resolved when confined, else as given.
|
||||
pub fn allow(path: impl AsRef<Path>, access: Access) -> Result<PathBuf> {
|
||||
|
||||
@@ -27,6 +27,10 @@ use crate::{EngineError, Result, Session, bad, spec};
|
||||
|
||||
/// Why there's no plugin directory here (the browser build, sessions without the network).
|
||||
pub const NO_DIRECTORY: &str = "plugin directories on a server need the desktop app, figcraft-cli or the MCP server";
|
||||
/// Why a plugin that asks for network access isn't published to or installed from a directory.
|
||||
// shortcut: an entry can't carry the hosts (its postcard wire format), so the install confirmation
|
||||
// couldn't show them; allow such plugins once the directory protocol negotiates new fields.
|
||||
const NO_NETWORK: &str = "it asks for network access, which a plugin directory can't show yet: import it from its manifest instead";
|
||||
/// Largest bundle downloaded or published (a server's own cap is at most this).
|
||||
pub const MAX_BUNDLE: usize = 32 << 20;
|
||||
/// The module's file name in an installed plugin's folder, and the folder its assets go in.
|
||||
@@ -137,6 +141,9 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
{
|
||||
return Err(fail("its manifest asks for commands the directory didn't show"));
|
||||
}
|
||||
if manifest.permissions.network.is_some() {
|
||||
return Err(fail(NO_NETWORK));
|
||||
}
|
||||
let source = address(&server);
|
||||
let path = save(s, &mut manifest, &bundle).map_err(|e| fail(&e))?;
|
||||
let out = json!({
|
||||
@@ -285,7 +292,9 @@ fn publish(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
(None, None) => return Err(bad(cmd, "pass `path` (a plugin folder or its figcraft-plugin.json) or `plugin` (an installed plugin's id)")),
|
||||
};
|
||||
// Checked here too, for a clear message before anything is sent.
|
||||
bundle.check().map_err(|e| bad(cmd, e))?;
|
||||
if bundle.check().map_err(|e| bad(cmd, e))?.permissions.network.is_some() {
|
||||
return Err(bad(cmd, NO_NETWORK));
|
||||
}
|
||||
let bytes = bundle.encode();
|
||||
if bytes.len() > MAX_BUNDLE {
|
||||
return Err(bad(cmd, format!("the plugin is larger than {} MiB", MAX_BUNDLE >> 20)));
|
||||
|
||||
@@ -255,6 +255,8 @@ struct EngineHost<'s> {
|
||||
manifest: &'s Manifest,
|
||||
/// Files offered for saving in this call.
|
||||
saves: u32,
|
||||
/// Web requests made in this call.
|
||||
requests: u32,
|
||||
}
|
||||
|
||||
/// Longest file name a plugin may suggest, in characters.
|
||||
@@ -265,6 +267,10 @@ const MAX_SAVE_MIME: usize = 100;
|
||||
const MAX_SAVE_BYTES: usize = 16 * 1024 * 1024;
|
||||
/// Files a plugin may offer per call.
|
||||
const MAX_SAVES: u32 = 1;
|
||||
/// Web requests a plugin may make per call.
|
||||
// shortcut: each request waits (the app too, 10 s at most each); run them in the background if
|
||||
// plugins need more or slower ones.
|
||||
const MAX_REQUESTS: u32 = 8;
|
||||
|
||||
/// A file name a plugin suggested, cleaned up: a bare name without folders, drive letters, `..` or
|
||||
/// characters no file system takes. `None` when nothing usable is left.
|
||||
@@ -417,6 +423,40 @@ impl figcraft_plugin::Host for EngineHost<'_> {
|
||||
self.s.request_ui("dialog.pluginSave", json!({"plugin": self.manifest.id, "name": name, "mime": sanitize_mime(mime), "data": data}));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn http(&mut self, request: &str) -> std::result::Result<String, String> {
|
||||
let m = self.manifest;
|
||||
let Some(net) = &m.permissions.network else {
|
||||
return Err(format!("{} didn't ask permission to reach the network (`permissions.network`)", m.name));
|
||||
};
|
||||
let req: Value = serde_json::from_str(request).map_err(|e| format!("a request must be JSON: {e}"))?;
|
||||
let url = string(&req, "url").ok_or("a request needs a `url`")?;
|
||||
let method = string(&req, "method").unwrap_or_else(|| "GET".into()).to_ascii_uppercase();
|
||||
if let Some(why) = net.refusal(&method, &url) {
|
||||
return Err(why);
|
||||
}
|
||||
if self.requests >= MAX_REQUESTS {
|
||||
return Err(format!("a plugin can make {MAX_REQUESTS} web requests per run"));
|
||||
}
|
||||
self.requests += 1;
|
||||
let r = match self.s.net(crate::live::NetRequest::Http { url: url.clone(), method }) {
|
||||
Ok((crate::live::NetReply::Http(r), _)) => r?,
|
||||
Ok(_) => return Err("the request got another answer".into()),
|
||||
Err(e) => return Err(e.to_string()),
|
||||
};
|
||||
let mut out = json!({"status": r.status, "url": url, "contentType": r.content_type});
|
||||
if !r.location.is_empty() {
|
||||
out["location"] = json!(r.location);
|
||||
}
|
||||
match String::from_utf8(r.body) {
|
||||
Ok(text) => out["body"] = json!(text),
|
||||
Err(e) => {
|
||||
use base64::Engine as _;
|
||||
out["bodyBase64"] = json!(base64::engine::general_purpose::STANDARD.encode(e.as_bytes()));
|
||||
}
|
||||
}
|
||||
Ok(out.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// The installed plugin `id`.
|
||||
@@ -533,6 +573,26 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
figcraft_plugin::check_module(&wasm, &Limits::default()).map_err(|e| plugin_error(&manifest.name, e))?;
|
||||
let mut out = describe(s, &InstalledPlugin { manifest: manifest.clone(), path: path.clone(), source: None });
|
||||
if get(p, "check") == Some(&Value::Bool(true)) {
|
||||
out["loaded"] = json!(false);
|
||||
out["imported"] = json!(false);
|
||||
return Ok(out);
|
||||
}
|
||||
if let Some(net) = &manifest.permissions.network {
|
||||
// `true`, or the network permission that was shown: a manifest changed since then asks again.
|
||||
let confirmed = match get(p, "confirm") {
|
||||
Some(Value::Bool(true)) => true,
|
||||
Some(shown @ Value::Object(_)) => serde_json::to_value(net).ok().as_ref() == Some(shown),
|
||||
_ => false,
|
||||
};
|
||||
if !confirmed {
|
||||
let (hosts, methods) = (net.allowed_domains.join(", "), net.methods.join(", "));
|
||||
return Err(bad(
|
||||
cmd,
|
||||
format!("{} asks to reach {hosts} ({methods}): check that (`check: true`) and pass `confirm: true`", manifest.name),
|
||||
));
|
||||
}
|
||||
}
|
||||
out["replaced"] = json!(register(s, InstalledPlugin { manifest, path, source: None }, wasm));
|
||||
out["loaded"] = json!(true);
|
||||
Ok(out)
|
||||
@@ -631,7 +691,7 @@ pub(crate) fn call_plugin(
|
||||
let ui_before = s.ui_requests.len();
|
||||
let r = s
|
||||
.grouped(label, |s| {
|
||||
let mut host = EngineHost { s, manifest: m, saves: 0 };
|
||||
let mut host = EngineHost { s, manifest: m, saves: 0, requests: 0 };
|
||||
instance.call(input, &mut host).map_err(|e| {
|
||||
usable = matches!(e, PluginError::Failed(_));
|
||||
plugin_error(&m.name, e)
|
||||
@@ -753,7 +813,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
spec!(
|
||||
"plugin.import",
|
||||
"Import plugin from manifest…",
|
||||
"{path (figcraft-plugin.json or its folder) | manifest (object or JSON text), wasm (base64)} replaces a plugin with the same id",
|
||||
"{path (figcraft-plugin.json or its folder) | manifest (object or JSON text), wasm (base64), check? (true: only report what it asks for), confirm? (true, or the `permissions.network` shown: required when it asks for network access)} replaces a plugin with the same id",
|
||||
false,
|
||||
import
|
||||
),
|
||||
|
||||
@@ -608,6 +608,8 @@ mod plugin_directory_tests;
|
||||
#[cfg(test)]
|
||||
mod plugin_libraries_tests;
|
||||
#[cfg(test)]
|
||||
mod plugin_network_tests;
|
||||
#[cfg(test)]
|
||||
mod plugin_panels_tests;
|
||||
#[cfg(test)]
|
||||
pub(crate) mod plugins_tests;
|
||||
|
||||
@@ -302,4 +302,12 @@ fn a_bundle_asking_for_more_than_the_directory_showed_is_not_installed() {
|
||||
s.execute("plugin.directory.list", &json!({"server": "ws://127.0.0.1:9/"})).unwrap();
|
||||
let err = s.execute("plugin.directory.install", &json!({"id": ID, "confirm": true})).unwrap_err().to_string();
|
||||
assert!(err.contains("commands"), "{err}");
|
||||
// Network access (#1883), which an entry can't show.
|
||||
let text = json!({"id": ID, "name": "Tiny", "version": "1.0.2", "author": "Ada", "main": "tiny.wasm", "api": 9, "permissions": {"access": "read", "network": {"allowedDomains": ["example.org"]}}}).to_string();
|
||||
let b = Bundle { manifest: text, wasm: wasm(), assets: vec![] }.encode();
|
||||
d.lock().unwrap().plugins = vec![(entry(ID, "1.0.2", &b), b)];
|
||||
s.execute("plugin.directory.list", &json!({"server": "ws://127.0.0.1:9/"})).unwrap();
|
||||
let err = s.execute("plugin.directory.install", &json!({"id": ID, "confirm": true})).unwrap_err().to_string();
|
||||
assert!(err.contains("network"), "{err}");
|
||||
assert!(s.prefs.plugins.is_empty(), "nothing was installed");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
//! Plugin web requests (#1883): a plugin reads only the hosts and methods its manifest names, over
|
||||
//! HTTPS, through the session's network link; importing one needs `confirm: true`, a run makes a
|
||||
//! few requests at most, and a session confined to automation roots makes none.
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use figcraft_collab::message::ClientMsg;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::live::{Event, HostOptions, HttpResponse, LiveLink, Presence, SessionInfo};
|
||||
use crate::plugins_tests::{b64, lit};
|
||||
use crate::{EngineError, Session};
|
||||
|
||||
const HOST: &str = "catalogue.example.org";
|
||||
|
||||
/// The requests a scripted web got: (address, method).
|
||||
type Asked = Arc<Mutex<Vec<(String, String)>>>;
|
||||
|
||||
/// A scripted web: every request it gets, answered with `body`.
|
||||
struct Link(Asked, Vec<u8>);
|
||||
|
||||
impl LiveLink for Link {
|
||||
fn host(&mut self, _: u64, _: HostOptions) -> Result<SessionInfo, String> {
|
||||
Err("no".into())
|
||||
}
|
||||
fn join(&mut self, _: u64, _: &str, _: &str) -> Result<(), String> {
|
||||
Err("no".into())
|
||||
}
|
||||
fn leave(&mut self, _: u64) {}
|
||||
fn presence(&mut self, _: u64, _: &Presence) {}
|
||||
fn send(&mut self, _: u64, _: ClientMsg) {}
|
||||
fn poll(&mut self) -> Vec<(u64, Event)> {
|
||||
Vec::new()
|
||||
}
|
||||
fn http(&mut self, url: &str, method: &str) -> Result<HttpResponse, String> {
|
||||
self.0.lock().unwrap().push((url.into(), method.into()));
|
||||
Ok(HttpResponse { status: 200, content_type: "application/json".into(), location: String::new(), body: self.1.clone() })
|
||||
}
|
||||
}
|
||||
|
||||
/// A session online to a web that answers `body`, and the requests it got.
|
||||
fn online(body: &[u8]) -> (Session, Asked) {
|
||||
let asked = Arc::new(Mutex::new(Vec::new()));
|
||||
let mut s = Session::new();
|
||||
s.live.install(Box::new(Link(asked.clone(), body.to_vec())));
|
||||
(s, asked)
|
||||
}
|
||||
|
||||
/// A module that makes `requests` (JSON) in order and outputs the reply to the last one.
|
||||
fn fetcher(requests: &[Value]) -> Vec<u8> {
|
||||
let (mut data, mut body, mut at) = (String::new(), String::new(), 0usize);
|
||||
for r in requests {
|
||||
let r = r.to_string();
|
||||
data += &format!("(data (i32.const {at}) \"{}\")\n", lit(&r));
|
||||
body += &format!("(drop (call $http (i32.const {at}) (i32.const {})))\n", r.len());
|
||||
at += r.len();
|
||||
}
|
||||
let wat = format!(
|
||||
r#"(module
|
||||
(import "figcraft" "http_request" (func $http (param i32 i32) (result i32)))
|
||||
(import "figcraft" "reply_read" (func $reply_read (param i32 i32) (result i32)))
|
||||
(import "figcraft" "set_output" (func $set_output (param i32 i32)))
|
||||
(memory (export "memory") 2)
|
||||
{data}
|
||||
(func (export "figcraft_run") (param $n i32) (result i32)
|
||||
{body}
|
||||
(call $set_output (i32.const 40000) (call $reply_read (i32.const 40000) (i32.const 20000)))
|
||||
(i32.const 0)))"#
|
||||
);
|
||||
wat::parse_str(&wat).unwrap_or_else(|e| panic!("{e}\n{wat}"))
|
||||
}
|
||||
|
||||
fn manifest(id: &str, network: Option<Value>) -> Value {
|
||||
let mut m = json!({"id": id, "name": "Fetcher", "version": "1.0.0", "main": "plugin.wasm", "api": 9, "permissions": {"access": "read"}});
|
||||
if let Some(n) = network {
|
||||
m["permissions"]["network"] = n;
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
fn import(s: &mut Session, manifest: &Value, requests: &[Value], extra: Value) -> Result<Value, EngineError> {
|
||||
let mut p = json!({"manifest": manifest, "wasm": b64(&fetcher(requests))});
|
||||
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
|
||||
s.execute("plugin.import", &p)
|
||||
}
|
||||
|
||||
/// Install plugin `id` reading `HOST` with GET that makes `requests`, run it, and return its output.
|
||||
fn run(s: &mut Session, id: &str, requests: &[Value]) -> Value {
|
||||
import(s, &manifest(id, Some(json!({"allowedDomains": [HOST]}))), requests, json!({"confirm": true})).unwrap();
|
||||
let out = s.execute("plugin.run", &json!({"id": id})).unwrap()["output"].clone();
|
||||
// A refusal is the reply's text; a response is its JSON.
|
||||
out.as_str().and_then(|t| serde_json::from_str(t).ok()).unwrap_or(out)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plugin_reads_its_hosts_and_nothing_else() {
|
||||
let (mut s, asked) = online(br#"{"icons":3}"#);
|
||||
let url = format!("https://{HOST}/icons.json");
|
||||
let out = run(&mut s, "org.test.get", &[json!({"url": url})]);
|
||||
assert_eq!(out["status"], 200, "{out}");
|
||||
assert_eq!(out["body"], r#"{"icons":3}"#);
|
||||
assert_eq!(*asked.lock().unwrap(), vec![(url, "GET".to_string())]);
|
||||
// Another scheme, host, port, user info or method is refused before the link is asked.
|
||||
for (i, (url, method)) in [
|
||||
(format!("http://{HOST}/"), "GET"),
|
||||
("https://other.example.org/".into(), "GET"),
|
||||
(format!("https://{HOST}:8443/"), "GET"),
|
||||
(format!("https://{HOST}@other.example.org/"), "GET"),
|
||||
(format!("https://{HOST}/"), "POST"),
|
||||
(format!("https://{HOST}/"), "HEAD"),
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let out = run(&mut s, &format!("org.test.bad{i}"), &[json!({"url": url, "method": method})]);
|
||||
assert!(out.as_str().is_some_and(|t| t.contains("asked for") || t.contains("https://")), "{url} {method}: {out}");
|
||||
}
|
||||
assert_eq!(asked.lock().unwrap().len(), 1, "no refused request reached the network");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_binary_body_arrives_as_base64() {
|
||||
let (mut s, _) = online(&[0xff, 0x00, 0x7f]);
|
||||
let out = run(&mut s, "org.test.bin", &[json!({"url": format!("https://{HOST}/a.png")})]);
|
||||
assert_eq!(out["bodyBase64"], b64(&[0xff, 0x00, 0x7f]), "{out}");
|
||||
assert!(out.get("body").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plugin_without_the_permission_reaches_nothing() {
|
||||
let (mut s, asked) = online(b"{}");
|
||||
import(&mut s, &manifest("org.test.none", None), &[json!({"url": format!("https://{HOST}/")})], json!({})).unwrap();
|
||||
let out = s.execute("plugin.run", &json!({"id": "org.test.none"})).unwrap();
|
||||
assert!(out["output"].as_str().unwrap_or_default().contains("permissions.network"), "{out}");
|
||||
assert!(asked.lock().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn importing_a_plugin_that_reads_the_web_needs_confirmation() {
|
||||
let (mut s, _) = online(b"{}");
|
||||
let m = manifest("org.test.ask", Some(json!({"allowedDomains": [HOST], "methods": ["get", "HEAD"]})));
|
||||
let e = import(&mut s, &m, &[], json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains(HOST) && e.contains("confirm"), "{e}");
|
||||
let checked = import(&mut s, &m, &[], json!({"check": true})).unwrap();
|
||||
assert_eq!(checked["permissions"]["network"]["methods"], json!(["GET", "HEAD"]), "{checked}");
|
||||
assert!(s.prefs.plugins.is_empty(), "neither refusal nor check installs it");
|
||||
// Approving what was shown imports only that: other hosts ask again.
|
||||
let shown = checked["permissions"]["network"].clone();
|
||||
let mut other = shown.clone();
|
||||
other["allowedDomains"] = json!(["other.example.org"]);
|
||||
assert!(import(&mut s, &m, &[], json!({"confirm": other})).is_err());
|
||||
assert!(s.prefs.plugins.is_empty());
|
||||
import(&mut s, &m, &[], json!({"confirm": shown})).unwrap();
|
||||
assert_eq!(s.prefs.plugins.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_makes_a_few_requests_at_most() {
|
||||
let (mut s, asked) = online(b"{}");
|
||||
let one = json!({"url": format!("https://{HOST}/")});
|
||||
let out = run(&mut s, "org.test.many", &vec![one; 9]);
|
||||
assert!(out.as_str().is_some_and(|t| t.contains("web requests per run")), "{out}");
|
||||
assert!(asked.lock().unwrap().len() < 9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_confined_to_automation_roots_reaches_no_host() {
|
||||
let dir = std::env::temp_dir().join(format!("figcraft-plugin-net-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let roots = Arc::new(crate::file_access::Roots::new(&[], &[dir.to_string_lossy().into_owned()]).unwrap());
|
||||
let (mut s, asked) = online(b"{}");
|
||||
let out = crate::file_access::confined(Some(&roots), || run(&mut s, "org.test.confined", &[json!({"url": format!("https://{HOST}/")})]));
|
||||
assert!(out.as_str().is_some_and(|t| t.contains(crate::file_access::NETWORK_REFUSED)), "{out}");
|
||||
assert!(asked.lock().unwrap().is_empty());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -128,6 +128,7 @@ fn answer(s: &mut Session, wire: &Arc<Mutex<Wire>>) -> usize {
|
||||
NetRequest::Hosting { .. } => NetReply::Hosting(Err("no".into())),
|
||||
NetRequest::Share { .. } => NetReply::Share(Err("no".into())),
|
||||
NetRequest::Web { .. } => NetReply::Web(Err("no".into())),
|
||||
NetRequest::Http { .. } => NetReply::Http(Err("no".into())),
|
||||
};
|
||||
w.answers.push(Event::Net { job: *job, reply: Box::new(reply) });
|
||||
}
|
||||
|
||||
@@ -72,9 +72,9 @@ pub(crate) use host::{clean_shared, share_answer};
|
||||
pub(crate) use join::start_join;
|
||||
pub use join::{can_remove_people, specs};
|
||||
pub use types::{
|
||||
Bind, DEFAULT_SERVER, Event, HostOptions, LiveLink, MAX_NAME, MAX_PEERS, MAX_SELECTION, MAX_WEB_BYTES, NO_HOSTING, NO_SESSION, NO_WEB, NetReply,
|
||||
NetRequest, ONLINE_OFF, PEOPLE, PageInfo, PublishOptions, Published, Role, SessionId, SessionInfo, Share, Shared, SharedLink, Status,
|
||||
TOO_LARGE_TO_JOIN, Via, WayIn, WebPage, join_target, parse_color,
|
||||
Bind, DEFAULT_SERVER, Event, HostOptions, HttpResponse, LiveLink, MAX_NAME, MAX_PEERS, MAX_SELECTION, MAX_WEB_BYTES, NO_HOSTING, NO_HTTP,
|
||||
NO_SESSION, NO_WEB, NetReply, NetRequest, ONLINE_OFF, PEOPLE, PageInfo, PublishOptions, Published, Role, SessionId, SessionInfo, Share, Shared,
|
||||
SharedLink, Status, TOO_LARGE_TO_JOIN, Via, WayIn, WebPage, join_target, parse_color,
|
||||
};
|
||||
|
||||
/// The view a follow last applied: any other view means the user moved.
|
||||
|
||||
@@ -337,6 +337,9 @@ pub enum NetRequest {
|
||||
/// A web page or picture at `url` (`http` or `https`), for a link card's preview
|
||||
/// ([`LiveLink::web`]).
|
||||
Web { url: String },
|
||||
/// A plugin's request to an address its manifest allows (`https`, `GET` or `HEAD`), with no
|
||||
/// redirects followed ([`LiveLink::http`]).
|
||||
Http { url: String, method: String },
|
||||
}
|
||||
|
||||
impl NetRequest {
|
||||
@@ -347,6 +350,7 @@ impl NetRequest {
|
||||
NetRequest::Library { .. } | NetRequest::Upload(_) => NO_TEAM_LIBRARIES,
|
||||
NetRequest::Hosting { .. } | NetRequest::Share { .. } => NO_HOSTING,
|
||||
NetRequest::Web { .. } => NO_WEB,
|
||||
NetRequest::Http { .. } => NO_HTTP,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -359,6 +363,7 @@ impl NetRequest {
|
||||
NetRequest::Hosting { .. } => |why| NetReply::Hosting(Err(why)),
|
||||
NetRequest::Share { .. } => |why| NetReply::Share(Err(why)),
|
||||
NetRequest::Web { .. } => |why| NetReply::Web(Err(why)),
|
||||
NetRequest::Http { .. } => |why| NetReply::Http(Err(why)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -377,6 +382,7 @@ impl NetRequest {
|
||||
a == b && f == g && x == y
|
||||
}
|
||||
(NetRequest::Web { url: a }, NetRequest::Web { url: b }) => a == b,
|
||||
(NetRequest::Http { url: a, method: x }, NetRequest::Http { url: b, method: y }) => a == b && x == y,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -393,6 +399,7 @@ pub enum NetReply {
|
||||
/// What the server says about its hosting, and its answer to the request, if one was sent.
|
||||
Hosting(std::result::Result<(HostInfo, Option<AdminReply>), String>),
|
||||
Web(std::result::Result<WebPage, String>),
|
||||
Http(std::result::Result<HttpResponse, String>),
|
||||
}
|
||||
|
||||
/// What a session without the network says about servers' hosting.
|
||||
@@ -402,6 +409,20 @@ pub const NO_WEB: &str = "link previews need the desktop app";
|
||||
/// The most of a web page or picture [`LiveLink::web`] reads.
|
||||
pub const MAX_WEB_BYTES: usize = 4 << 20;
|
||||
|
||||
/// What a session without plugin web requests says (the browser build, scripts without the network).
|
||||
pub const NO_HTTP: &str = "plugin web requests need the desktop app";
|
||||
|
||||
/// A plugin's web response ([`LiveLink::http`]): its status, the content type and redirect target
|
||||
/// it names, and (at most [`MAX_WEB_BYTES`] of) its body.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct HttpResponse {
|
||||
pub status: u16,
|
||||
pub content_type: String,
|
||||
/// The `Location` of a redirect (which isn't followed), else empty.
|
||||
pub location: String,
|
||||
pub body: Vec<u8>,
|
||||
}
|
||||
|
||||
/// What [`LiveLink::web`] read: where it ended up after redirects, what it says it is and (at most
|
||||
/// [`MAX_WEB_BYTES`] of) its body.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -520,6 +541,11 @@ pub trait LiveLink: Send {
|
||||
fn web(&mut self, _url: &str) -> std::result::Result<WebPage, String> {
|
||||
Err(NO_WEB.into())
|
||||
}
|
||||
/// A plugin's `method` request to `url` ([`NetRequest::Http`]); waits, a few seconds at most.
|
||||
/// The caller has checked both against the plugin's manifest.
|
||||
fn http(&mut self, _url: &str, _method: &str) -> std::result::Result<HttpResponse, String> {
|
||||
Err(NO_HTTP.into())
|
||||
}
|
||||
/// What the server at `server` says about its hosting, and with a file's owner token
|
||||
/// (`file` and `owner`) its answer to `req` about that file; waits for the server. Errors
|
||||
/// never echo the token.
|
||||
@@ -545,6 +571,7 @@ pub trait LiveLink: Send {
|
||||
NetRequest::Upload(o) => NetReply::Upload(self.upload(o)),
|
||||
NetRequest::Hosting { server, file, owner, req } => NetReply::Hosting(self.hosting(&server, &file, &owner, req)),
|
||||
NetRequest::Web { url } => NetReply::Web(self.web(&url)),
|
||||
NetRequest::Http { url, method } => NetReply::Http(self.http(&url, &method)),
|
||||
}
|
||||
}
|
||||
/// Send `req` on a thread of its own and return at once: the answer arrives as [`Event::Net`]
|
||||
|
||||
@@ -9,7 +9,7 @@ pub mod manifest;
|
||||
mod sandbox;
|
||||
pub mod widget;
|
||||
|
||||
pub use manifest::{API_VERSION, Access, MANIFEST_FILE, Manifest, Panel, Param, ParamKind, Permissions, Placement, PluginCommand};
|
||||
pub use manifest::{API_VERSION, Access, MANIFEST_FILE, Manifest, Network, Panel, Param, ParamKind, Permissions, Placement, PluginCommand};
|
||||
pub use sandbox::{ENTRY, Host, IMPORT_MODULE, Instance, Limits, PluginError, RunOutput, UiChange, check_module, run};
|
||||
pub use widget::{MenuItem, MenuKind, WidgetHover, WidgetKind, WidgetNode, WidgetRender};
|
||||
|
||||
@@ -18,6 +18,8 @@ mod bundle_tests;
|
||||
#[cfg(test)]
|
||||
mod libraries_tests;
|
||||
#[cfg(test)]
|
||||
mod network_tests;
|
||||
#[cfg(test)]
|
||||
mod placement_tests;
|
||||
#[cfg(test)]
|
||||
mod save_file_tests;
|
||||
|
||||
@@ -8,7 +8,7 @@ use serde_json::{Map, Value};
|
||||
/// The manifest's file name.
|
||||
pub const MANIFEST_FILE: &str = "figcraft-plugin.json";
|
||||
/// The plugin API version this build implements (`api` in the manifest).
|
||||
pub const API_VERSION: u32 = 8;
|
||||
pub const API_VERSION: u32 = 9;
|
||||
/// Largest manifest read.
|
||||
pub const MAX_MANIFEST_BYTES: usize = 256 * 1024;
|
||||
|
||||
@@ -20,6 +20,8 @@ const MAX_COMMANDS: usize = 64;
|
||||
const MAX_PARAMS: usize = 32;
|
||||
const MAX_OPTIONS: usize = 64;
|
||||
const MAX_ALLOW: usize = 256;
|
||||
/// Most hosts a plugin may ask to reach.
|
||||
const MAX_HOSTS: usize = 16;
|
||||
/// Largest panel spec a plugin may show (images included, as base64), and its most controls.
|
||||
pub const MAX_PANEL_BYTES: usize = 1024 * 1024;
|
||||
/// Largest image in a panel (its file's bytes).
|
||||
@@ -45,7 +47,8 @@ pub struct Manifest {
|
||||
/// The WebAssembly module, relative to the manifest (`plugin.wasm`).
|
||||
pub main: String,
|
||||
/// The plugin API version the plugin was written for (1 when not given; panels and settings
|
||||
/// need 2, widgets 3, `saveFile`, widget fields and property menus 4, the time 7, `libraries` 8).
|
||||
/// need 2, widgets 3, `saveFile`, widget fields and property menus 4, the time 7, `libraries` 8,
|
||||
/// `network` 9).
|
||||
#[serde(default = "api_version", deserialize_with = "api_from_number_or_string")]
|
||||
pub api: u32,
|
||||
#[serde(default)]
|
||||
@@ -102,6 +105,81 @@ pub struct Permissions {
|
||||
/// `commands` leaves it out; needs `write` access). No other library, and no path.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub libraries: Vec<String>,
|
||||
/// API 9: the web hosts the plugin may read from with `http_request` (HTTPS only, through
|
||||
/// FigCraft). Without it, a plugin reaches no network.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub network: Option<Network>,
|
||||
}
|
||||
|
||||
/// `permissions.network`: exact host names and the HTTP methods a plugin may use on them.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Network {
|
||||
/// Exact host names (`catalogue.example.org`): no wildcards, ports, schemes or paths.
|
||||
#[serde(rename = "allowedDomains")]
|
||||
pub allowed_domains: Vec<String>,
|
||||
/// `GET` and `HEAD` (`GET` when none is given).
|
||||
#[serde(default)]
|
||||
pub methods: Vec<String>,
|
||||
}
|
||||
|
||||
impl Network {
|
||||
/// Why `url` with `method` isn't one this permission admits, if it isn't: HTTPS to one of the
|
||||
/// hosts exactly, on the default port, without user info.
|
||||
pub fn refusal(&self, method: &str, url: &str) -> Option<String> {
|
||||
if !self.methods.iter().any(|m| m == method) {
|
||||
return Some(format!("`{}` isn't one of the methods asked for ({})", truncate(method), self.methods.join(", ")));
|
||||
}
|
||||
let Some(rest) = url.get(..8).filter(|s| s.eq_ignore_ascii_case("https://")).map(|_| &url[8..]) else {
|
||||
return Some("only https:// addresses can be requested".into());
|
||||
};
|
||||
if url.len() > 2048 || url.chars().any(|c| c.is_whitespace() || c.is_control() || c == '\\') {
|
||||
return Some("not a usable address".into());
|
||||
}
|
||||
let host = rest.split(['/', '?', '#']).next().unwrap_or_default().to_ascii_lowercase();
|
||||
if self.allowed_domains.contains(&host) {
|
||||
return None;
|
||||
}
|
||||
// A port, user info or another host: only the exact names shown at install.
|
||||
Some(format!("`{}` isn't one of the hosts asked for ({})", truncate(&host), self.allowed_domains.join(", ")))
|
||||
}
|
||||
|
||||
/// Lower-case the hosts and methods (`GET` when none) and check them.
|
||||
fn check(&mut self) -> Result<(), String> {
|
||||
if self.allowed_domains.is_empty() || self.allowed_domains.len() > MAX_HOSTS {
|
||||
return Err(format!("`permissions.network.allowedDomains` needs 1–{MAX_HOSTS} host names"));
|
||||
}
|
||||
for d in &mut self.allowed_domains {
|
||||
*d = d.trim().to_ascii_lowercase();
|
||||
let label = |l: &str| {
|
||||
!l.is_empty()
|
||||
&& l.len() <= 63
|
||||
&& !l.starts_with('-')
|
||||
&& !l.ends_with('-')
|
||||
&& l.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
|
||||
};
|
||||
// A name, not an address: its last label has a letter (so `10.0.0.5` isn't one).
|
||||
let named = d.rsplit('.').next().is_some_and(|tld| tld.bytes().any(|b| b.is_ascii_alphabetic()));
|
||||
if d.len() > 253 || !d.contains('.') || !named || !d.split('.').all(label) {
|
||||
return Err(format!(
|
||||
"`{}` in `permissions.network.allowedDomains` isn't an exact host name like catalogue.example.org (no wildcards, ports or paths)",
|
||||
truncate(d)
|
||||
));
|
||||
}
|
||||
}
|
||||
if self.methods.is_empty() {
|
||||
self.methods.push("GET".into());
|
||||
}
|
||||
for m in &mut self.methods {
|
||||
*m = m.trim().to_ascii_uppercase();
|
||||
if !matches!(m.as_str(), "GET" | "HEAD") {
|
||||
return Err(format!("`{}` in `permissions.network.methods`: plugins may only read (GET, HEAD)", truncate(m)));
|
||||
}
|
||||
}
|
||||
match first_duplicate(self.allowed_domains.iter().chain(&self.methods).map(String::as_str)) {
|
||||
Some(dup) => Err(format!("`{}` is in `permissions.network` twice", truncate(dup))),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Permissions {
|
||||
@@ -396,6 +474,12 @@ impl Manifest {
|
||||
return Err("saveFile needs plugin API 4 (`\"api\": 4`)".into());
|
||||
}
|
||||
self.check_libraries()?;
|
||||
if let Some(net) = &mut self.permissions.network {
|
||||
if self.api < 9 {
|
||||
return Err("network access needs plugin API 9 (`\"api\": 9`)".into());
|
||||
}
|
||||
net.check()?;
|
||||
}
|
||||
if self.commands.is_empty() && !self.widget {
|
||||
self.commands.push(PluginCommand { id: "run".into(), label: "Run".into(), params: Vec::new() });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
//! `permissions.network` (#1883): exact host names and read-only methods, from API 9, and only
|
||||
//! HTTPS addresses on exactly those hosts pass.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Manifest;
|
||||
|
||||
fn manifest(api: u32, network: Value) -> Result<Manifest, String> {
|
||||
Manifest::from_value(&json!({"id": "org.example.cat", "name": "Cat", "main": "cat.wasm", "api": api, "permissions": {"network": network}}))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_hosts_and_read_only_methods_from_api_9() {
|
||||
let m = manifest(9, json!({"allowedDomains": [" Catalogue.Example.org "]})).unwrap();
|
||||
let net = m.permissions.network.unwrap();
|
||||
assert_eq!(net.allowed_domains, ["catalogue.example.org"]);
|
||||
assert_eq!(net.methods, ["GET"], "GET when none is given");
|
||||
assert!(manifest(8, json!({"allowedDomains": ["example.org"]})).unwrap_err().contains("API 9"));
|
||||
for bad in [
|
||||
json!({"allowedDomains": []}),
|
||||
json!({"allowedDomains": ["*.example.org"]}),
|
||||
json!({"allowedDomains": ["example.org:8443"]}),
|
||||
json!({"allowedDomains": ["https://example.org"]}),
|
||||
json!({"allowedDomains": ["example.org/path"]}),
|
||||
json!({"allowedDomains": ["localhost"]}),
|
||||
json!({"allowedDomains": ["10.0.0.5"]}),
|
||||
json!({"allowedDomains": ["-bad.example.org"]}),
|
||||
json!({"allowedDomains": ["example.org", "EXAMPLE.org"]}),
|
||||
json!({"allowedDomains": ["example.org"], "methods": ["POST"]}),
|
||||
json!({"allowedDomains": ["example.org"], "methods": ["GET", "get"]}),
|
||||
json!({"allowedDomains": (0..17).map(|i| format!("h{i}.example.org")).collect::<Vec<_>>()}),
|
||||
] {
|
||||
assert!(manifest(9, bad.clone()).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_https_to_the_exact_hosts_and_methods_pass() {
|
||||
let net = manifest(9, json!({"allowedDomains": ["cat.example.org"], "methods": ["GET"]})).unwrap().permissions.network.unwrap();
|
||||
for ok in ["https://cat.example.org", "HTTPS://CAT.example.org/a?b=c#d", "https://cat.example.org?x=1"] {
|
||||
assert_eq!(net.refusal("GET", ok), None, "{ok}");
|
||||
}
|
||||
for bad in [
|
||||
"http://cat.example.org/",
|
||||
"https://evil.example.org/?cat.example.org",
|
||||
"https://cat.example.org.evil.org/",
|
||||
"https://cat.example.org:444/",
|
||||
r"https://cat.example.org@evil.org/",
|
||||
"https://user@cat.example.org/",
|
||||
r"https://cat.example.org\@evil.org/",
|
||||
"https://cat.example.org/ x",
|
||||
"ftp://cat.example.org/",
|
||||
"https://",
|
||||
] {
|
||||
assert!(net.refusal("GET", bad).is_some(), "{bad}");
|
||||
}
|
||||
assert!(net.refusal("HEAD", "https://cat.example.org/").is_some(), "a method it didn't ask for");
|
||||
}
|
||||
@@ -2,8 +2,8 @@
|
||||
//! memory cap, and sees the outside world only through the host functions below. There is no WASI:
|
||||
//! no file system, network, clock or randomness.
|
||||
//!
|
||||
//! # ABI (version 4; version 1 is the first seven imports, version 2 adds panels and settings,
|
||||
//! version 3 widgets, version 4 `save_file`)
|
||||
//! # ABI (version 9; version 1 is the first seven imports, version 2 adds panels and settings,
|
||||
//! version 3 widgets, version 4 `save_file`, version 9 `http_request`)
|
||||
//!
|
||||
//! The module exports its `memory` and `figcraft_run(input_len: i32) -> i32`. Host functions are
|
||||
//! imported from the module `figcraft`; strings are UTF-8 `(ptr, len)` pairs in the plugin's memory.
|
||||
@@ -24,6 +24,7 @@
|
||||
//! | `setting_delete` | `(key_ptr, key_len)` | Forgets a setting. |
|
||||
//! | `widget_render` | `(ptr, len) -> i32` | Draws the widget being called back: a [`WidgetRender`] as JSON. 1: invalid, the reply says why. |
|
||||
//! | `save_file` | `(name_ptr, name_len, mime_ptr, mime_len, data_ptr, data_len) -> i32` | Offers a file to save (needs `permissions.saveFile`). The host asks the user where it goes; the plugin never gets a path. 0: accepted, 1: refused, the reply says why. |
|
||||
//! | `http_request` | `(ptr, len) -> i32` | Reads a web address the manifest allows (`permissions.network`): `{"url", "method"}` as JSON. 0: the reply holds the response JSON; 1: refused or failed, the reply says why. |
|
||||
//!
|
||||
//! When `figcraft_run` starts, the reply holds the input JSON (`input_len` bytes):
|
||||
//! `{"api", "command", "params", "selection"}`, plus `event` and `values` when a panel calls the
|
||||
@@ -63,6 +64,7 @@ const IMPORTS: &[(&str, usize, usize)] = &[
|
||||
("setting_delete", 2, 0),
|
||||
("widget_render", 2, 1),
|
||||
("save_file", 6, 1),
|
||||
("http_request", 2, 1),
|
||||
];
|
||||
|
||||
/// What a run may use.
|
||||
@@ -149,6 +151,10 @@ pub trait Host {
|
||||
fn save_file(&mut self, _name: &str, _mime: &str, _data: &[u8]) -> Result<(), String> {
|
||||
Err("saving files isn't available here".into())
|
||||
}
|
||||
/// Make the web request `request` (`{"url", "method"}` JSON): the response JSON, or why not.
|
||||
fn http(&mut self, _request: &str) -> Result<String, String> {
|
||||
Err("network requests aren't available here".into())
|
||||
}
|
||||
}
|
||||
|
||||
/// What a run asked of the panel.
|
||||
@@ -187,6 +193,7 @@ enum Request {
|
||||
SettingSet(String, String),
|
||||
SettingDelete(String),
|
||||
SaveFile(String, String, Vec<u8>),
|
||||
Http(String),
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -209,6 +216,16 @@ impl State {
|
||||
1
|
||||
}
|
||||
|
||||
/// Make a host answer the reply: 0 with its result, 1 with why it was refused.
|
||||
fn status(&mut self, answer: Result<String, String>) -> i32 {
|
||||
let (status, reply) = match answer {
|
||||
Ok(v) => (0, v),
|
||||
Err(m) => (1, m),
|
||||
};
|
||||
self.set_reply(reply.into_bytes());
|
||||
status
|
||||
}
|
||||
|
||||
/// Make `bytes` the reply; returns its length.
|
||||
fn set_reply(&mut self, bytes: Vec<u8>) -> i32 {
|
||||
let max = self.limits.max_message;
|
||||
@@ -221,14 +238,8 @@ impl State {
|
||||
/// Answer a paused host call; the host function's result, if it has one.
|
||||
fn answer(&mut self, host: &mut dyn Host, request: Request) -> Option<i32> {
|
||||
match request {
|
||||
Request::Call(cmd, params) => {
|
||||
let (status, reply) = match host.call(&cmd, ¶ms) {
|
||||
Ok(v) => (0, v),
|
||||
Err(m) => (1, m),
|
||||
};
|
||||
self.set_reply(reply.into_bytes());
|
||||
Some(status)
|
||||
}
|
||||
Request::Call(cmd, params) => Some(self.status(host.call(&cmd, ¶ms))),
|
||||
Request::Http(req) => Some(self.status(host.http(&req))),
|
||||
Request::Selection => Some(self.set_reply(host.selection().into_bytes())),
|
||||
Request::Log(line) => {
|
||||
host.log(&line);
|
||||
@@ -636,6 +647,12 @@ fn linker(engine: &Engine) -> Result<Linker<State>, PluginError> {
|
||||
Err(ask(&mut c, Request::SaveFile(name, mime, data)))
|
||||
})
|
||||
.map_err(err)?;
|
||||
l.func_wrap(IMPORT_MODULE, "http_request", |mut c: Ctx<'_>, ptr: i32, len: i32| -> Result<i32, wasmi::Error> {
|
||||
charge(&mut c)?;
|
||||
let req = read_str(&mut c, ptr, len)?;
|
||||
Err(ask(&mut c, Request::Http(req)))
|
||||
})
|
||||
.map_err(err)?;
|
||||
Ok(l)
|
||||
}
|
||||
|
||||
|
||||
@@ -135,6 +135,7 @@ name = "English"
|
||||
"Everything runs without asking" = "Everything runs without asking"
|
||||
"Extra fine" = "Extra fine"
|
||||
"Extra thick" = "Extra thick"
|
||||
"FigCraft makes each request for it ({methods}), without your cookies or sign-ins, and follows no redirects. What it reads can reach your document. Import only plugins you trust." = "FigCraft makes each request for it ({methods}), without your cookies or sign-ins, and follows no redirects. What it reads can reach your document. Import only plugins you trust."
|
||||
"Files and network ask first" = "Files and network ask first"
|
||||
"Fill this with realistic content" = "Fill this with realistic content"
|
||||
"Fine" = "Fine"
|
||||
@@ -142,11 +143,13 @@ name = "English"
|
||||
"Frame {start} isn't in this file: presenting from the start." = "Frame {start} isn't in this file: presenting from the start."
|
||||
"Get a key" = "Get a key"
|
||||
"How many versions of the design to build" = "How many versions of the design to build"
|
||||
"Import plugin" = "Import plugin"
|
||||
"In $/1M" = "In $/1M"
|
||||
"In use" = "In use"
|
||||
"Installed, not signed in. Sign in with:" = "Installed, not signed in. Sign in with:"
|
||||
"Instructions" = "Instructions"
|
||||
"Instructions the agent follows for a kind of work. Type / in the box to add one to a request; the agent also loads one when it fits." = "Instructions the agent follows for a kind of work. Type / in the box to add one to a request; the agent also loads one when it fits."
|
||||
"It asks permission to read from the web:" = "It asks permission to read from the web:"
|
||||
"Layer" = "Layer"
|
||||
"Layer {name}: select it" = "Layer {name}: select it"
|
||||
"Leave {name} out of the request" = "Leave {name} out of the request"
|
||||
@@ -518,6 +521,7 @@ name = "English"
|
||||
"When to use it" = "When to use it"
|
||||
"Working…" = "Working…"
|
||||
"Write a description for this component" = "Write a description for this component"
|
||||
"reads from the web: {hosts}" = "reads from the web: {hosts}"
|
||||
"{count} steps" = "{count} steps"
|
||||
"{count} steps, {failed} failed" = "{count} steps, {failed} failed"
|
||||
"{count} tokens" = "{count} tokens"
|
||||
|
||||
@@ -43,8 +43,8 @@ impl PluginsTab {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Manage plugins window's state: its tab, the Browse tab's fields and the plugin waiting for
|
||||
/// the user to confirm its install (by id).
|
||||
/// The Manage plugins window's state: its tab, the Browse tab's fields, the plugin waiting for the
|
||||
/// user to confirm its install (by id) and the imported one that asks for network access.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct PluginsWindow {
|
||||
pub tab: PluginsTab,
|
||||
@@ -52,6 +52,9 @@ pub struct PluginsWindow {
|
||||
pub server: Option<String>,
|
||||
pub query: String,
|
||||
pub confirm: Option<String>,
|
||||
/// A manifest picked to import whose network access the user hasn't approved yet (checked, not
|
||||
/// installed).
|
||||
pub import: Option<InstalledPlugin>,
|
||||
}
|
||||
|
||||
/// Width of the plugin windows' fields.
|
||||
@@ -157,13 +160,68 @@ fn run(app: &mut FigApp, cmd: &str, params: Value) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Plugins ▸ Development ▸ Import plugin from manifest…: pick a `figcraft-plugin.json`.
|
||||
/// Plugins ▸ Development ▸ Import plugin from manifest…: pick a `figcraft-plugin.json`. One that
|
||||
/// asks for network access is checked first and waits for the user's approval.
|
||||
pub fn import_dialog(app: &mut FigApp) {
|
||||
app.pick_open(tr("Import plugin from manifest"), &["json"], |app, p| {
|
||||
if let Some(v) = app.run("plugin.import", json!({"path": p.to_string_lossy()})) {
|
||||
app.toast(trf("Imported {name}", &[("name", &v["name"].as_str().unwrap_or(tr("the plugin")))]));
|
||||
app.pick_open(tr("Import plugin from manifest"), &["json"], |app, p| picked(app, p.to_string_lossy().into_owned()));
|
||||
}
|
||||
|
||||
/// The manifest at `path` was picked: import it, or ask first when it reads the web.
|
||||
pub(crate) fn picked(app: &mut FigApp, path: String) {
|
||||
let Some(v) = app.run("plugin.import", json!({"path": path, "check": true})) else { return };
|
||||
match serde_json::from_value::<figcraft_engine::plugins::Manifest>(v) {
|
||||
Ok(manifest) if manifest.permissions.network.is_some() => {
|
||||
app.ui.plugins_manage.import = Some(InstalledPlugin { manifest, path: Some(path), source: None });
|
||||
}
|
||||
_ => import(app, &path, Value::Bool(false)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Import the plugin whose manifest is at `path`; `confirm` is the network access the user approved
|
||||
/// (the engine refuses a manifest that now asks for other access).
|
||||
fn import(app: &mut FigApp, path: &str, confirm: Value) {
|
||||
if let Some(v) = app.run("plugin.import", json!({"path": path, "confirm": confirm})) {
|
||||
app.toast(trf("Imported {name}", &[("name", &v["name"].as_str().unwrap_or(tr("the plugin")))]));
|
||||
}
|
||||
}
|
||||
|
||||
/// The approval an imported plugin that asks for network access needs: the hosts it may read from
|
||||
/// and its other permissions, then Import or Cancel.
|
||||
fn import_confirm_window(app: &mut FigApp, ctx: &Context) {
|
||||
let Some(p) = app.ui.plugins_manage.import.clone() else { return };
|
||||
let Some(net) = &p.manifest.permissions.network else { return };
|
||||
let t = Tokens::get(ctx);
|
||||
let (mut open, mut import_it, mut cancel) = (true, false, false);
|
||||
window(tr("Import plugin"), ctx).id(Id::unique("plugin_import_confirm")).open(&mut open).show(ctx, |ui| {
|
||||
ui.set_width(340.0);
|
||||
ui.label(RichText::new(&p.manifest.name).font(semibold(13.0)).color(t.text));
|
||||
widgets::label(ui, &summary(&p), t.text_secondary);
|
||||
ui.add_space(10.0);
|
||||
ui.label(RichText::new(tr("It asks permission to read from the web:")).font(semibold(11.0)).color(t.text));
|
||||
for host in &net.allowed_domains {
|
||||
ui.add(egui::Label::new(RichText::new(format!("• https://{host}")).font(regular(11.0)).color(t.text)).wrap());
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
widgets::label(
|
||||
ui,
|
||||
&trf(
|
||||
"FigCraft makes each request for it ({methods}), without your cookies or sign-ins, and follows no redirects. What it reads can reach your document. Import only plugins you trust.",
|
||||
&[("methods", &net.methods.join(", "))],
|
||||
),
|
||||
t.text_secondary,
|
||||
);
|
||||
ui.add_space(12.0);
|
||||
ui.horizontal(|ui| {
|
||||
import_it = widgets::button(ui, tr("Import"), true, true).clicked();
|
||||
cancel = widgets::button(ui, tr("Cancel"), false, true).clicked();
|
||||
});
|
||||
});
|
||||
if !open || cancel || import_it {
|
||||
app.ui.plugins_manage.import = None;
|
||||
}
|
||||
if import_it && let Some(path) = &p.path {
|
||||
import(app, path, json!(net));
|
||||
}
|
||||
}
|
||||
|
||||
/// The installed plugins at the top of the Plugins menu: a plugin with one command is an item, one
|
||||
@@ -222,6 +280,9 @@ pub fn show(app: &mut FigApp, ctx: &Context) {
|
||||
if app.ui.plugin_form.is_some() {
|
||||
form_window(app, ctx);
|
||||
}
|
||||
if app.ui.plugins_manage.import.is_some() {
|
||||
import_confirm_window(app, ctx);
|
||||
}
|
||||
show_docked_tab(app);
|
||||
if app.session.plugins.panels.iter().any(|p| !is_docked(p)) {
|
||||
panel_windows(app, ctx);
|
||||
@@ -615,6 +676,9 @@ fn summary(p: &InstalledPlugin) -> String {
|
||||
if !m.permissions.libraries.is_empty() {
|
||||
parts.push(trf("can enable its libraries: {libraries}", &[("libraries", &m.permissions.libraries.join(", "))]));
|
||||
}
|
||||
if let Some(net) = &m.permissions.network {
|
||||
parts.push(trf("reads from the web: {hosts}", &[("hosts", &net.allowed_domains.join(", "))]));
|
||||
}
|
||||
parts.push(match (&p.source, &p.path) {
|
||||
(Some(server), _) => trf("from {server}", &[("server", server)]),
|
||||
(None, Some(path)) => trf("development: {path}", &[("path", path)]),
|
||||
|
||||
@@ -295,6 +295,8 @@ mod perf_tests;
|
||||
#[cfg(test)]
|
||||
mod pixel_grid_tests;
|
||||
#[cfg(test)]
|
||||
mod plugin_import_tests;
|
||||
#[cfg(test)]
|
||||
mod plugin_panel_tests;
|
||||
#[cfg(test)]
|
||||
mod plugin_save_ui_tests;
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
//! Importing a development plugin that reads the web (#1883): picking its manifest installs
|
||||
//! nothing until the user approves the hosts it shows; one that doesn't read the web is imported at
|
||||
//! once.
|
||||
|
||||
use figcraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::layers_drag_tests::Ui;
|
||||
use crate::plugins_browse_tests::{centre, click, named, shows};
|
||||
|
||||
/// A plugin folder in the temp folder whose manifest has `permissions`; its manifest's path.
|
||||
fn folder(tag: &str, permissions: serde_json::Value) -> String {
|
||||
let dir = std::env::temp_dir().join(format!("figcraft-import-{tag}-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let wasm =
|
||||
wat::parse_str(r#"(module (memory (export "memory") 1) (func (export "figcraft_run") (param i32) (result i32) i32.const 0))"#).unwrap();
|
||||
std::fs::write(dir.join("p.wasm"), wasm).unwrap();
|
||||
let manifest =
|
||||
json!({"id": format!("org.test.{tag}"), "name": "Catalogue", "version": "1.0.0", "main": "p.wasm", "api": 9, "permissions": permissions});
|
||||
let path = dir.join("figcraft-plugin.json");
|
||||
std::fs::write(&path, manifest.to_string()).unwrap();
|
||||
path.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plugin_that_reads_the_web_is_imported_only_once_its_hosts_are_approved() {
|
||||
let mut u = Ui::new(Session::new());
|
||||
u.ctx.enable_accesskit();
|
||||
let path = folder("web", json!({"network": {"allowedDomains": ["catalogue.example.org"]}}));
|
||||
crate::plugins_ui::picked(&mut u.app, path.clone());
|
||||
assert!(u.app.session.prefs.plugins.is_empty(), "nothing is installed before the user approves");
|
||||
assert!(u.app.ui.plugins_manage.import.is_some(), "it asks first");
|
||||
// A new window's first frame only measures it.
|
||||
u.frame(vec![]);
|
||||
assert!(shows(&mut u, "https://catalogue.example.org"), "the confirmation names the host");
|
||||
let import = named(&mut u, "Import");
|
||||
click(&mut u, centre(&import[0]));
|
||||
let p = &u.app.session.prefs.plugins;
|
||||
assert_eq!(p.len(), 1);
|
||||
assert!(p[0].manifest.permissions.network.is_some());
|
||||
assert_eq!(u.app.ui.plugins_manage.import, None);
|
||||
let _ = std::fs::remove_dir_all(std::path::Path::new(&path).parent().unwrap());
|
||||
|
||||
// One that doesn't read the web needs no approval.
|
||||
let plain = folder("plain", json!({"access": "read"}));
|
||||
crate::plugins_ui::picked(&mut u.app, plain.clone());
|
||||
assert_eq!(u.app.session.prefs.plugins.len(), 2);
|
||||
assert_eq!(u.app.ui.plugins_manage.import, None);
|
||||
let _ = std::fs::remove_dir_all(std::path::Path::new(&plain).parent().unwrap());
|
||||
}
|
||||
@@ -113,24 +113,24 @@ impl crate::Services for Saved {
|
||||
}
|
||||
}
|
||||
|
||||
fn centre(n: &egui::accesskit::Node) -> Pos2 {
|
||||
pub(crate) fn centre(n: &egui::accesskit::Node) -> Pos2 {
|
||||
let b = n.bounds().unwrap();
|
||||
Pos2::new(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32)
|
||||
}
|
||||
|
||||
/// Every node labelled `label`, in tree order.
|
||||
fn named(u: &mut Ui, label: &str) -> Vec<egui::accesskit::Node> {
|
||||
pub(crate) fn named(u: &mut Ui, label: &str) -> Vec<egui::accesskit::Node> {
|
||||
let tree = u.frame_output(vec![]).platform_output.accesskit_update.unwrap().nodes;
|
||||
tree.into_iter().map(|(_, n)| n).filter(|n| n.label() == Some(label)).collect()
|
||||
}
|
||||
|
||||
/// Some node's label (a text's value) holds `text`.
|
||||
fn shows(u: &mut Ui, text: &str) -> bool {
|
||||
pub(crate) fn shows(u: &mut Ui, text: &str) -> bool {
|
||||
let tree = u.frame_output(vec![]).platform_output.accesskit_update.unwrap().nodes;
|
||||
tree.iter().any(|(_, n)| n.label().or(n.value()).is_some_and(|l| l.contains(text)))
|
||||
}
|
||||
|
||||
fn click(u: &mut Ui, at: Pos2) {
|
||||
pub(crate) fn click(u: &mut Ui, at: Pos2) {
|
||||
u.button(at, true);
|
||||
u.button(at, false);
|
||||
}
|
||||
|
||||
@@ -293,6 +293,9 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe
|
||||
Docked panels and shipped libraries (#2752, 2026-12-01): a panel can dock in the left sidebar,
|
||||
and a plugin can enable the `.figcraft` libraries it ships in its `assets` folder
|
||||
(`permissions.libraries`, plugin API 8), so it can place their components in any file.
|
||||
Reading the web (#1883, 2026-12-02): a plugin can read the exact hosts its manifest names
|
||||
(`permissions.network`, plugin API 9) over HTTPS with `GET` or `HEAD`, through FigCraft, after
|
||||
the user approves them on import.
|
||||
- **Missing:** a public catalogue and Community files, publisher accounts and signatures, ratings
|
||||
and install counts, background update checks, keeping plugins installed in the browser past the
|
||||
page (the directory works there since 2026-10-31); widgets have no
|
||||
@@ -720,6 +723,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-12-02 | minor | Gap 6, #1883: a plugin can read the web hosts its manifest names: `permissions.network` (plugin API 9) lists exact hosts and `GET`/`HEAD`, and `http_request` asks FigCraft for an `https://` address on one of them (no redirects followed, no credentials sent, 8 requests per run, 4 MB per response). Importing such a plugin needs the user's approval (`plugin.import` `confirm: true`, `check: true` to look first); Manage plugins lists the hosts; plugin directories refuse such plugins until an entry can show them; confined sessions make no requests. Estimate unchanged. Tests: `network_tests`, `plugin_network_tests` |
|
||||
| 2026-12-01 | minor | Gap 24: M12, #1736: as the help describes, dragging the border between two rows of the selected board table sizes the row above it (it keeps at least that height, and still grows with its text), in one undo step through `board.tableEdit {action: resizeRow, index, size}`. A click in the selected table picks a cell (it shows an outline), and the bar's colours go on that cell, or on every cell with the table selected; `board.setColor` takes a cell's text id from `board.table`'s `cells`, or the table's id. Every cell is as tall as its row, so a colour reaches the row's line. Not built: the row and column grabbers, picking several cells, Tab between cells. Numbers unchanged. Tests: `board_table_size_tests`. |
|
||||
| 2026-12-01 | minor | Gap 18, #1392: bounded automatic retries recover same-stamp read failures; warnings are deduplicated per file and failed replacement, clearing on recovery or a new stamp. No parity or estimate changes |
|
||||
| 2026-12-01 | minor | Gap 18: saved files refresh across desktop app instances (#1388), retaining clean tabs' identity and view; local edits and busy tabs stay intact and conflicting saves are refused. Path aliases reuse a tab and Save as cannot overwrite another open tab's file. No parity or estimate changes |
|
||||
|
||||
+1
-1
@@ -136,7 +136,7 @@ Each may be given more than once, as `--flag DIR` or `--flag=DIR`:
|
||||
MCP's `collab.join`, `collab.publish` and `collab.share` to a server explicitly allowed with
|
||||
`--automation-allow-server` (below). Hosting a file (`collab.host`, `collab.share {via: "local"}`), team
|
||||
libraries on a server (`library.check` refuses, and `library.updates` / `library.list` report the
|
||||
refusal for each instead of the last version fetched) and plugin directories remain refused with
|
||||
refusal for each instead of the last version fetched), plugin directories and plugins' web requests remain refused with
|
||||
`automation roots are set: commands don't reach the network …`. The app started with the flags
|
||||
confines its own window too, so its sharing is off as well. One exception: a root on a network
|
||||
share (a UNC path such as `\\server\share\…`, or a mounted network drive) is still a root, so
|
||||
|
||||
+48
-7
@@ -8,7 +8,8 @@ permissions its manifest asks for, and nothing more.
|
||||
- **Sandboxed.** Plugins run in [wasmi](https://github.com/wasmi-labs/wasmi), a pure-Rust
|
||||
WebAssembly interpreter (no JIT), in the desktop app and in the browser build alike. There is no
|
||||
WASI: no file system, network, clock or randomness (since API 7 the host hands each call its
|
||||
time instead, see below). A run has an instruction budget (fuel) and a
|
||||
time instead, and since API 9 FigCraft can make web requests for it to the hosts its manifest
|
||||
names, see below). A run has an instruction budget (fuel) and a
|
||||
memory cap, so an endless loop or a runaway allocation fails that run, not the app.
|
||||
- **One undo step.** Everything a run does is one step in the undo history, named after the plugin;
|
||||
so is everything one callback from its panel does. When a run or a callback fails (the plugin
|
||||
@@ -25,7 +26,8 @@ permissions its manifest asks for, and nothing more.
|
||||
lines and SVG pictures.
|
||||
- **Permissions.** The manifest says whether the plugin only reads the document or may edit it, and
|
||||
can narrow the commands it may call. FigCraft enforces both. Since API 8 it can also name
|
||||
libraries it ships, which it may then enable in the open file.
|
||||
libraries it ships, which it may then enable in the open file, and since API 9 web hosts it may
|
||||
read from.
|
||||
- **Distribution.** A team's own `figcraft-server` can keep a plugin directory: plugins are
|
||||
published to it with the server's key, browsed and installed from Plugins ▸ Manage plugins, and
|
||||
updated when a newer version is published (see [Plugin directories](#plugin-directories)). No
|
||||
@@ -114,6 +116,37 @@ directory refuses a plugin whose `assets` folder lacks one it names.
|
||||
"permissions": {"access": "write", "commands": ["library.place", "library.list"], "libraries": ["icons.figcraft"]}
|
||||
```
|
||||
|
||||
**Reading the web (API 9).** A plugin that needs fresh data (an icon or token catalogue, a
|
||||
translation table, a template list) can name the hosts it reads from in `permissions.network`, and
|
||||
then ask FigCraft for an address on one of them with `http_request`. Nothing else reaches the
|
||||
network: there are no sockets, and the commands that do (`collab.*`, team libraries, plugin
|
||||
directories) stay closed to plugins.
|
||||
|
||||
```json
|
||||
"permissions": {"access": "write", "network": {"allowedDomains": ["catalogue.example.org"], "methods": ["GET"]}}
|
||||
```
|
||||
|
||||
- Hosts are exact names (up to 16): no wildcards, ports, schemes or paths. Methods are `GET` and
|
||||
`HEAD` (`GET` when none is given).
|
||||
- Only `https://` addresses on exactly those hosts, on the default port and without user info, are
|
||||
requested; any other is refused before anything is sent.
|
||||
- FigCraft sends the request itself, with no cookies, sign-ins or other credentials of yours, and
|
||||
follows no redirects: the plugin gets the redirect (`status` and `location`) and may ask for the
|
||||
new address, which is checked again.
|
||||
- No proxy is used, and an address that resolves to this computer or the local network is refused
|
||||
when it connects (a host name, not an IP address, goes in the manifest).
|
||||
- A run (and each panel or widget callback) makes 8 requests at most. Each waits 10 seconds at
|
||||
most, and the app waits with it. A response over 4 MB fails.
|
||||
- The plugin gets `{status, url, contentType, location?, body}`, with `bodyBase64` instead of `body`
|
||||
when the response isn't text.
|
||||
- Importing such a plugin asks first: Plugins ▸ Import plugin from manifest shows the hosts and
|
||||
**Import** installs it if the manifest still asks for exactly those hosts (`plugin.import` needs
|
||||
`confirm: true`, or the `permissions.network` that was shown; `check: true` reports what a
|
||||
manifest asks for without installing it). Manage plugins lists the hosts under the plugin. A plugin
|
||||
directory can't show the hosts yet, so it neither publishes nor installs such plugins.
|
||||
- A session confined to automation roots (`figcraft-cli mcp`) makes no requests, as it reaches no
|
||||
server. The browser build runs no plugins.
|
||||
|
||||
**Widgets.** A widget is a frame on the canvas that belongs to its plugin. It moves, copies,
|
||||
deletes, exports and undoes like any layer, as one layer: the layers inside it are locked. Clicking
|
||||
one of its parts that the plugin made clickable (with the Move tool; the pointer turns into a hand
|
||||
@@ -283,12 +316,13 @@ does, but there is no folder to keep a plugin in, so it lasts as long as the pag
|
||||
| `version`, `description` | Optional text. A plugin published to a [directory](#plugin-directories) needs a `version` of one to four numbers (`1.2.0`), each version newer than the last. |
|
||||
| `author` | Optional: who made it, as you type it (64 characters at most); plugin directories show it. |
|
||||
| `main` | Required. The module, a `.wasm` path relative to the manifest, inside its folder. |
|
||||
| `api` | The plugin API version the plugin was written for: `1` (the default), `2` (panels and settings), `3` (widgets), `4` (saving files, widget fields and property menus), `5` (panels from widgets), `6` (widget lines and SVG), `7` (the time) or `8` (libraries it ships). A manifest asking for a newer one than FigCraft runs is refused, so a plugin that needs panels, widgets, `saveFile` or `libraries` fails clearly on an older FigCraft. |
|
||||
| `api` | The plugin API version the plugin was written for: `1` (the default), `2` (panels and settings), `3` (widgets), `4` (saving files, widget fields and property menus), `5` (panels from widgets), `6` (widget lines and SVG), `7` (the time), `8` (libraries it ships) or `9` (reading the web). A manifest asking for a newer one than FigCraft runs is refused, so a plugin that needs panels, widgets, `saveFile`, `libraries` or `network` fails clearly on an older FigCraft. |
|
||||
| `permissions.saveFile` | API 4: `true` lets the plugin offer a file to save (an exporter's output). FigCraft asks the user where it goes with its own Save dialog (a download in the browser); the plugin never gets a path. Manage plugins lists it ("can save files"). A plugin directory's entries don't carry it (their wire format stays as it is), so installing any API 4 plugin from one says it may offer files to save. |
|
||||
| `widget` | API 3: `true` when the plugin draws a widget (it's listed in Plugins ▸ Widgets). |
|
||||
| `permissions.access` | `read` (the default): commands that leave the document as it is; such plugins also run from Developer Mode's Inspect tab. `write`: edits too. |
|
||||
| `permissions.commands` | Optional allowlist: exact command ids or prefixes ending in `*` (`node.*`). Empty: any command the access allows. |
|
||||
| `permissions.libraries` | API 8, with `write` access: up to 32 `.figcraft` file names in the plugin's `assets` folder (plain names, no folders) that it may enable with `library.add` (see [Libraries a plugin ships](#using-plugins)). |
|
||||
| `permissions.network` | API 9: `{allowedDomains, methods?}`, the exact hosts (1–16) the plugin may read from over HTTPS and the methods it uses (`GET`, `HEAD`; `GET` by default). Importing it needs the user's approval (see [Reading the web](#using-plugins)). |
|
||||
| `commands` | The menu commands, each `{id, label, params?}`. Without any, the plugin has one, `run`, unless it's a widget (a widget needs no command). |
|
||||
| `params[]` | `{name, label?, type, default?, options?, min?, max?}`; `type` is `text`, `number` (clamped to `min`/`max`), `boolean`, `select` (one of `options`, a menu), `list` (one of `options`, shown as a list), `slider` (a number between `min` and `max`, both required, shown as a slider with its value beside it) or `color` (hex, `#RRGGBB` or `#RRGGBBAA`). A default that doesn't fit is dropped. |
|
||||
|
||||
@@ -307,6 +341,8 @@ it can handle):
|
||||
back), `codeConnect.import` with a `path` and `variable.import` with a file path instead of JSON,
|
||||
`window.*` (new windows open files), `view.theme*`;
|
||||
- live sessions and online files: `collab.*`;
|
||||
- the network, except `https://` requests through `http_request` to the hosts and with the methods
|
||||
its `permissions.network` names;
|
||||
- other documents and the version history: `doc.*` and `version.*` (except `doc.list`, which gives a
|
||||
plugin the open files' names but not their paths, and `version.list`);
|
||||
- the undo history and nesting: `edit.undo`, `edit.redo`, `edit.repeat`, `command.batch` (a run is
|
||||
@@ -333,11 +369,11 @@ allocation or copy. This also applies when the configured per-call overhead is z
|
||||
read is charged for the bytes actually returned, not the requested buffer size. `calls` counts
|
||||
every ABI import, including calls which only query the reply length.
|
||||
|
||||
## ABI (version 6)
|
||||
## ABI (version 9)
|
||||
|
||||
Version 2 adds panels and settings to version 1, version 3 adds widgets, version 4 adds
|
||||
`save_file` and widget fields and property menus (new keys in the widget description and new
|
||||
widget events), version 5 lets a widget open its plugin's panel (no new imports), and version 6 adds lines and SVG to the widget description; a module written for an older version runs unchanged and gets the input it always
|
||||
widget events), version 5 lets a widget open its plugin's panel (no new imports), and version 6 adds lines and SVG to the widget description, version 9 adds `http_request`; a module written for an older version runs unchanged and gets the input it always
|
||||
got. A widget description with a field or a menu from a plugin whose manifest says `3` is refused, as
|
||||
is one with a line or an SVG from a manifest that says less than `6`,
|
||||
and a FigCraft that runs an older API refuses a manifest that asks for `4` when it's imported. Strings are UTF-8 `(ptr, len)` pairs in the plugin's linear memory; all values
|
||||
@@ -413,6 +449,7 @@ included, is refused when the plugin is imported):
|
||||
| `setting_set` | `(key_ptr, key_len, value_ptr, value_len) -> status` | API 2. Stores JSON under the key, for this plugin only, kept with the preferences. `1`: refused (not JSON, a bad key, over 64 KB), the reply says why. |
|
||||
| `setting_delete` | `(key_ptr, key_len)` | API 2. Forgets a setting. |
|
||||
| `save_file` | `(name_ptr, name_len, mime_ptr, mime_len, data_ptr, data_len) -> status` | API 4, needs `permissions.saveFile`. Offers a file to save; FigCraft asks the user where it goes once the run succeeds. `1`: refused (no permission, a bad file name, over 16 MB, a second file in one run), the reply says why. |
|
||||
| `http_request` | `(ptr, len) -> status` | API 9, needs `permissions.network`. Reads a web address: `{"url", "method"?}` as JSON (`GET` by default). `0`: the reply holds `{status, url, contentType, location?, body \| bodyBase64}`; `1`: refused (no permission, another host or method, not HTTPS, a ninth request in one run, a confined session) or failed (unreachable, over 4 MB), the reply says why. |
|
||||
| `widget_render` | `(ptr, len) -> status` | API 3. Draws the widget being inserted or clicked, or (API 5) the widget whose panel called back (the widget description below, as JSON). `1`: the description is invalid, the reply says why. A widget call that doesn't draw keeps the widget as it was (inserting one must draw it). |
|
||||
|
||||
A pointer or length outside the plugin's memory traps, which fails the run. Host functions can only
|
||||
@@ -582,7 +619,8 @@ description may have fields and a `menu`; with `"permissions": {"saveFile": true
|
||||
`save_file(name, mime, &bytes)` offers a file; FigCraft asks the user where it goes and the plugin
|
||||
never learns a path. With `"api": 7`, `input.now_ms` and `input.utc_offset_min`. With `"api": 8`
|
||||
and `"permissions": {"libraries": [...]}`, `call("library.add", &json!({"path": "icons.figcraft"}))`
|
||||
enables a library from its `assets` folder. Outside
|
||||
enables a library from its `assets` folder. With `"api": 9` and `"permissions": {"network": {...}}`,
|
||||
`http_request("GET", "https://catalogue.example.org/icons.json")` reads it. Outside
|
||||
WebAssembly every host call fails, so the plugin's own logic can be unit-tested with `cargo test`.
|
||||
|
||||
Any language that compiles to WebAssembly works the same way: export `memory` and `figcraft_run`,
|
||||
@@ -600,7 +638,10 @@ import what you need from `figcraft`.
|
||||
vectors, components or variables).
|
||||
- Panels: no free layout inside a panel; images can't be clicked.
|
||||
- Libraries: a plugin enables only library files it ships; it can't enable a team library on a
|
||||
server, which would need the network.
|
||||
server.
|
||||
- The web: only `GET` and `HEAD` without a body or headers of the plugin's own, one request at a
|
||||
time while the app waits, and no plugin that reads the web in a plugin directory yet (an entry
|
||||
can't show its hosts).
|
||||
- Data in the document: plugins keep data on layers (pages included) with `node.set {props:
|
||||
{pluginData: {key: value}}}` (a `null` value removes a key) and read it back with `node.get`, which
|
||||
reports `pluginData: {key: value}` (values as strings) when a layer has any; there is no separate
|
||||
|
||||
@@ -666,6 +666,7 @@ Carried over from the ROADMAP's "Shipped so far" (2026-10-10). The test count th
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-12-02 | patch | M11, #1883: a plugin can read fresh data from the web hosts its manifest names (plugin API 9, `permissions.network`: exact hosts, `GET`/`HEAD`, HTTPS only, through FigCraft with no credentials and no redirects followed), after the user approves them on import. Older plugins unchanged. Numbers unchanged. Tests: `network_tests`, `plugin_network_tests`. |
|
||||
| 2026-12-01 | patch | M11, #2752: a plugin can enable the libraries it ships (plugin API 8, `permissions.libraries`: `.figcraft` files in its `assets` folder), so an asset-browser plugin places its components without the user adding its library to each file first. Older plugins unchanged. Numbers unchanged. Tests: `libraries_tests`, `plugin_libraries_tests`. |
|
||||
| 2026-12-01 | patch | M3, #2777: a frame that doesn't clip its content grew its drop shadows by their spread; the reference tool ignores the spread there, as its renders of a synthetic file show (a 160 × 120 frame, radius 24, with a shadow spread by 4 and one 6 to the left spread by -2: no ring above it, the bare outline moved 6; a rectangle and a clipping frame grow and shrink theirs). The canvas, PNG/JPG/WebP, PDF and SVG exports now draw an unclipped frame's drop shadows without their spread and leave no room for it in the export's area; clipping the content again brings the spread back. Inner shadows keep their spread (not measured). Numbers unchanged |
|
||||
| 2026-11-30 | patch | M3, paint: a pass-through frame's drop shadows in a blend mode of their own (the linear-burn ring of an iOS kit's glass buttons, imported from a `.fig`) were blended among themselves and laid over the backdrop as one, a grey ring where the reference tool draws a dark one: the tool groups a layer's shadows only when the layer is in a blend mode of its own (Normal included), and burns a pass-through frame's into what lies under it, as its renders of a synthetic file show (frames and shapes, Normal and pass-through, with and without fills or children). The shadows of a pass-through frame now blend by their modes with the backdrop; other layers keep the group. Found on an iOS kit: 60 screens with glass buttons draw closer to the tool's renders, none further. Test: `fill_blend_tests::a_pass_through_frames_drop_shadows_blend_with_the_backdrop` (fails on main). |
|
||||
|
||||
@@ -221,6 +221,21 @@ pub fn save_file(name: &str, mime: &str, data: &[u8]) -> Result<()> {
|
||||
if host::save_file(name.as_bytes(), mime.as_bytes(), data) == 0 { Ok(()) } else { Err(String::from_utf8_lossy(&host::reply()).into_owned()) }
|
||||
}
|
||||
|
||||
/// Read `url` with `method` (`GET` or `HEAD`): `{status, url, contentType, location?, body |
|
||||
/// bodyBase64}` (`body` when it's text). FigCraft makes the request; redirects aren't followed
|
||||
/// (`location` says where to). Needs `"api": 9` and the address's host and method in
|
||||
/// `permissions.network`. A refusal (another host or method, not HTTPS, too many requests in one
|
||||
/// run, a confined session) or a failure (unreachable, over 4 MB) is an error.
|
||||
pub fn http_request(method: &str, url: &str) -> Result<Value> {
|
||||
let req = serde_json::to_string(&serde_json::json!({"method": method, "url": url})).map_err(|e| e.to_string())?;
|
||||
let status = host::http_request(req.as_bytes());
|
||||
let reply = String::from_utf8(host::reply()).map_err(|_| "the reply isn't UTF-8".to_string())?;
|
||||
if status != 0 {
|
||||
return Err(reply);
|
||||
}
|
||||
serde_json::from_str(&reply).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// The body of `figcraft_run` (use [`entry!`]): read the input, run `f`, hand back its output.
|
||||
pub fn run_plugin(input_len: i32, f: fn(Input) -> Result<Value>) -> i32 {
|
||||
let input = host::reply();
|
||||
@@ -273,6 +288,7 @@ mod host {
|
||||
pub fn setting_delete(key: *const u8, key_len: usize);
|
||||
pub fn widget_render(ptr: *const u8, len: usize) -> i32;
|
||||
pub fn save_file(name: *const u8, name_len: usize, mime: *const u8, mime_len: usize, data: *const u8, data_len: usize) -> i32;
|
||||
pub fn http_request(ptr: *const u8, len: usize) -> i32;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -321,6 +337,9 @@ mod host {
|
||||
pub fn save_file(name: &[u8], mime: &[u8], data: &[u8]) -> i32 {
|
||||
unsafe { sys::save_file(name.as_ptr(), name.len(), mime.as_ptr(), mime.len(), data.as_ptr(), data.len()) }
|
||||
}
|
||||
pub fn http_request(s: &[u8]) -> i32 {
|
||||
unsafe { sys::http_request(s.as_ptr(), s.len()) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Outside WebAssembly (a plugin's own unit tests) every host call fails.
|
||||
@@ -357,6 +376,9 @@ mod host {
|
||||
pub fn save_file(_name: &[u8], _mime: &[u8], _data: &[u8]) -> i32 {
|
||||
1
|
||||
}
|
||||
pub fn http_request(_s: &[u8]) -> i32 {
|
||||
1
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
Reference in New Issue
Block a user