The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(app): serve the widget sandbox proxy on the ohwidget scheme
oxoxDev0cc50a93c75a
diff --git a/crates/openhuman-app/assets/widget-proxy.html b/crates/openhuman-app/assets/widget-proxy.htmlnew file mode 100644index 0000000000..e01f1c7dd0--- /dev/null+++ b/crates/openhuman-app/assets/widget-proxy.html@@ -0,0 +1,76 @@+<!doctype html>+<html>+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <meta name="referrer" content="no-referrer" />+ <style>+ html,+ body {+ margin: 0;+ padding: 0;+ height: 100%;+ background: transparent;+ overflow: hidden;+ }+ iframe {+ border: 0;+ display: block;+ width: 100%;+ height: 100%;+ background: transparent;+ }+ </style>+ </head>+ <body>+ <script>+ (function () {+ 'use strict';+ var host = window.parent;+ if (!host || host === window) return;+ var inner = null;++ function isRpc(data) {+ return (+ data !== null &&+ typeof data === 'object' &&+ data.jsonrpc === '2.0' &&+ (typeof data.method === 'string' || 'id' in data)+ );+ }++ function mount(html) {+ inner = document.createElement('iframe');+ inner.setAttribute('sandbox', 'allow-scripts allow-forms');+ inner.setAttribute('referrerpolicy', 'no-referrer');+ inner.setAttribute('title', 'widget');+ inner.srcdoc = html;+ document.body.appendChild(inner);+ }++ window.addEventListener('message', function (event) {+ var data = event.data;+ if (!isRpc(data)) return;+ if (event.source === host) {+ if (data.method === 'ui/notifications/sandbox-resource-ready') {+ var html = data.params && data.params.html;+ if (inner || typeof html !== 'string') return;+ mount(html);+ return;+ }+ if (inner && inner.contentWindow) inner.contentWindow.postMessage(data, '*');+ return;+ }+ if (inner && event.source === inner.contentWindow) {+ host.postMessage(data, '*');+ }+ });++ host.postMessage(+ { jsonrpc: '2.0', method: 'ui/notifications/sandbox-proxy-ready', params: {} },+ '*'+ );+ })();+ </script>+ </body>+</html>diff --git a/crates/openhuman-app/src/lib.rs b/crates/openhuman-app/src/lib.rsindex 2af57d4563..c31bd51e31 100644--- a/crates/openhuman-app/src/lib.rs+++ b/crates/openhuman-app/src/lib.rs@@ -109,6 +109,7 @@ mod ptt_overlay;mod reset_reboot_schedule;mod session;mod stderr_panic_hook;+mod widget_scheme;mod window_state;mod workspace_paths;@@ -2879,6 +2880,7 @@ pub fn run() {// Native backstop: the main webview never loads a remote page; any// http(s) navigation away from the app is handed to the OS browser..plugin(external_navigation::init())+ .register_asynchronous_uri_scheme_protocol(widget_scheme::SCHEME, widget_scheme::handle).plugin(tauri_plugin_deep_link::init()).plugin(tauri_plugin_notification::init()).plugin(tauri_plugin_global_shortcut::Builder::new().build())diff --git a/crates/openhuman-app/src/widget_scheme.rs b/crates/openhuman-app/src/widget_scheme.rsnew file mode 100644index 0000000000..deda9a40cf--- /dev/null+++ b/crates/openhuman-app/src/widget_scheme.rs@@ -0,0 +1,122 @@+//! `ohwidget:` — the origin tool-provided widgets run on.+//!+//! Serves one static page, the sandbox proxy, on an origin separate from the+//! app's, so a widget never shares the app's storage, cookies or IPC. The+//! proxy receives the widget's HTML from the app over `postMessage` and+//! renders it in an inner frame sandboxed without `allow-same-origin`. The+//! response's Content-Security-Policy, which that inner frame inherits, opens+//! only the `https` origins the widget declared; connections are denied when+//! it declared none. `frame-src about:` keeps the widget frame from being+//! navigated to a remote page, which the main webview's navigation guard+//! would otherwise hand to the OS browser.++use std::borrow::Cow;++use serde_json::Value;+use tauri::http::{header, Request, Response, StatusCode};+use tauri::{Runtime, UriSchemeContext, UriSchemeResponder};++pub(crate) const SCHEME: &str = "ohwidget";++const PROXY_PATH: &str = "/proxy";+const PROXY_HTML: &str = include_str!("../assets/widget-proxy.html");++/// The declared origins in `query`, reduced to `https` only by the core's+/// widget policy.+fn declared_origins(query: &str) -> (Vec<String>, Vec<String>) {+ let mut connect = Vec::new();+ let mut resource = Vec::new();+ for (key, value) in url::form_urlencoded::parse(query.as_bytes()) {+ match key.as_ref() {+ "connect" => connect.push(Value::String(value.into_owned())),+ "resource" => resource.push(Value::String(value.into_owned())),+ _ => {}+ }+ }+ let reduce = |items: Vec<Value>| {+ openhuman_core::mcp::ui::resolve::https_origins(Some(&Value::Array(items)))+ };+ (reduce(connect), reduce(resource))+}++/// The proxy page's Content-Security-Policy for these origins.+pub(crate) fn content_security_policy(connect: &[String], resource: &[String]) -> String {+ let sources = |extra: &str, origins: &[String]| {+ let mut parts = vec![extra.to_string()];+ parts.extend(origins.iter().cloned());+ parts.join(" ")+ };+ let connect_src = if connect.is_empty() {+ "'none'".to_string()+ } else {+ connect.join(" ")+ };+ [+ "default-src 'none'".to_string(),+ format!("script-src {}", sources("'unsafe-inline'", resource)),+ format!("style-src {}", sources("'unsafe-inline'", resource)),+ format!("img-src {}", sources("data: blob:", resource)),+ format!("font-src {}", sources("data:", resource)),+ format!("media-src {}", sources("data: blob:", resource)),+ format!("connect-src {connect_src}"),+ "frame-src about:".to_string(),+ "worker-src 'none'".to_string(),+ "object-src 'none'".to_string(),+ "base-uri 'none'".to_string(),+ "form-action 'none'".to_string(),+ ]+ .join("; ")+}++fn respond(status: StatusCode, body: Cow<'static, [u8]>, csp: Option<String>) -> Response<Vec<u8>> {+ let mut builder = Response::builder()+ .status(status)+ .header(header::CACHE_CONTROL, "no-store")+ .header(header::X_CONTENT_TYPE_OPTIONS, "nosniff")+ .header(header::REFERRER_POLICY, "no-referrer");+ if let Some(csp) = csp {+ builder = builder+ .header(header::CONTENT_TYPE, "text/html; charset=utf-8")+ .header(header::CONTENT_SECURITY_POLICY, csp);+ } else {+ builder = builder.header(header::CONTENT_TYPE, "text/plain; charset=utf-8");+ }+ builder.body(body.into_owned()).unwrap_or_else(|error| {+ log::warn!("[widget-scheme] response build failed: {error}");+ Response::new(Vec::new())+ })+}++/// The response for one `ohwidget:` request.+pub(crate) fn response_for(request: &Request<Vec<u8>>) -> Response<Vec<u8>> {+ if request.method() != tauri::http::Method::GET {+ return respond(StatusCode::METHOD_NOT_ALLOWED, Cow::Borrowed(b""), None);+ }+ if request.uri().path() != PROXY_PATH {+ log::debug!("[widget-scheme] unknown path requested");+ return respond(StatusCode::NOT_FOUND, Cow::Borrowed(b""), None);+ }+ let (connect, resource) = declared_origins(request.uri().query().unwrap_or(""));+ log::debug!(+ "[widget-scheme] serving the sandbox proxy (connect={}, resource={})",+ connect.len(),+ resource.len()+ );+ respond(+ StatusCode::OK,+ Cow::Borrowed(PROXY_HTML.as_bytes()),+ Some(content_security_policy(&connect, &resource)),+ )+}++pub(crate) fn handle<R: Runtime>(+ _ctx: UriSchemeContext<'_, R>,+ request: Request<Vec<u8>>,+ responder: UriSchemeResponder,+) {+ responder.respond(response_for(&request));+}++#[cfg(test)]+#[path = "widget_scheme_tests.rs"]+mod tests;diff --git a/crates/openhuman-app/src/widget_scheme_tests.rs b/crates/openhuman-app/src/widget_scheme_tests.rsnew file mode 100644index 0000000000..c7f3429188--- /dev/null+++ b/crates/openhuman-app/src/widget_scheme_tests.rs@@ -0,0 +1,88 @@+use super::*;++fn get(uri: &str) -> Response<Vec<u8>> {+ let request = Request::builder()+ .method("GET")+ .uri(uri)+ .body(Vec::new())+ .unwrap();+ response_for(&request)+}++fn csp_of(response: &Response<Vec<u8>>) -> String {+ response+ .headers()+ .get(header::CONTENT_SECURITY_POLICY)+ .unwrap()+ .to_str()+ .unwrap()+ .to_string()+}++#[test]+fn proxy_denies_connections_by_default() {+ let response = get("ohwidget://localhost/proxy");+ assert_eq!(response.status(), StatusCode::OK);+ let csp = csp_of(&response);+ assert!(csp.contains("connect-src 'none'"));+ assert!(csp.contains("default-src 'none'"));+ assert!(csp.contains("form-action 'none'"));+ assert!(String::from_utf8(response.body().clone())+ .unwrap()+ .contains("sandbox-proxy-ready"));+}++#[test]+fn proxy_opens_only_declared_https_origins() {+ let response = get(+ "http://ohwidget.localhost/proxy?connect=https%3A%2F%2Fapi.example.com%2Fv1&connect=http%3A%2F%2Finsecure.example.com&resource=https%3A%2F%2Fcdn.example.com&resource=javascript%3Aalert(1)",+ );+ let csp = csp_of(&response);+ assert!(csp.contains("connect-src https://api.example.com"));+ assert!(!csp.contains("insecure.example.com"));+ assert!(csp.contains("script-src 'unsafe-inline' https://cdn.example.com"));+ assert!(!csp.contains("javascript"));+}++#[test]+fn unknown_paths_and_methods_are_refused() {+ assert_eq!(get("ohwidget://localhost/other").status(), StatusCode::NOT_FOUND);+ let request = Request::builder()+ .method("POST")+ .uri("ohwidget://localhost/proxy")+ .body(Vec::new())+ .unwrap();+ assert_eq!(response_for(&request).status(), StatusCode::METHOD_NOT_ALLOWED);+}++#[test]+fn csp_semicolons_cannot_be_injected() {+ let response = get("ohwidget://localhost/proxy?connect=https%3A%2F%2Fa.example.com%3B%20script-src%20*");+ let csp = csp_of(&response);+ assert!(!csp.contains("script-src *"));+}++#[test]+fn widget_frame_cannot_be_navigated_to_a_remote_page() {+ let csp = csp_of(&get(+ "ohwidget://localhost/proxy?connect=https%3A%2F%2Fapi.example.com&resource=https%3A%2F%2Fcdn.example.com",+ ));+ let frame_src = csp+ .split("; ")+ .find(|directive| directive.starts_with("frame-src"))+ .unwrap();+ assert_eq!(frame_src, "frame-src about:");+}++#[test]+fn proxy_sandbox_grants_no_navigation_or_popups() {+ let sandbox = PROXY_HTML+ .split("setAttribute('sandbox', '")+ .nth(1)+ .and_then(|rest| rest.split('\'').next())+ .unwrap();+ assert_eq!(sandbox, "allow-scripts allow-forms");+ assert!(!PROXY_HTML.contains("allow-same-origin"));+ assert!(!PROXY_HTML.contains("allow-top-navigation"));+ assert!(!PROXY_HTML.contains("allow-popups"));+}diff --git a/crates/openhuman-app/tauri.conf.json b/crates/openhuman-app/tauri.conf.jsonindex d96e51d04d..ffa0f25831 100644--- a/crates/openhuman-app/tauri.conf.json+++ b/crates/openhuman-app/tauri.conf.json@@ -30,7 +30,7 @@}],"security": {- "csp": "default-src 'self' 'unsafe-inline' data: blob: https: wss: ipc: http://ipc.localhost http://127.0.0.1:* http://localhost:*; script-src 'self' 'wasm-unsafe-eval' https://www.googletagmanager.com tauri: tauri://localhost; img-src 'self' data: blob: https:; connect-src 'self' ipc: http://ipc.localhost http://127.0.0.1:* http://localhost:* ws://127.0.0.1:* ws://localhost:* https: wss: data: blob: https://*.google-analytics.com https://*.analytics.google.com https://*.googletagmanager.com; frame-src 'self' https: data: blob:"+ "csp": "default-src 'self' 'unsafe-inline' data: blob: https: wss: ipc: http://ipc.localhost http://127.0.0.1:* http://localhost:*; script-src 'self' 'wasm-unsafe-eval' https://www.googletagmanager.com tauri: tauri://localhost; img-src 'self' data: blob: https:; connect-src 'self' ipc: http://ipc.localhost http://127.0.0.1:* http://localhost:* ws://127.0.0.1:* ws://localhost:* https: wss: data: blob: https://*.google-analytics.com https://*.analytics.google.com https://*.googletagmanager.com; frame-src 'self' https: data: blob: ohwidget: http://ohwidget.localhost"},"macOSPrivateApi": true},