Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix(app): stop web pages from running PowerShell through /app-icon

Manas Raghuwanshi1ae9724ff805
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/icons.rs b/apps/screenpipe-app-tauri/src-tauri/src/icons.rs
index 4e31ed77b..6c4d676d1 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/icons.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/icons.rs
@@ -1,3 +1,6 @@
+// screenpipe — AI that knows everything you've seen, said, or heard
+// https://screenpipe.com
+
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
@@ -149,10 +152,7 @@ pub async fn get_app_icon(
if let Some(path) = get_exe_by_appx(app_name).await {
return Some(path);
}
- if let Some(path) = get_exe_from_potential_path(app_name).await {
- return Some(path);
- }
- None
+ get_exe_from_potential_path(app_name)
}
let path = match app_path {
@@ -293,6 +293,58 @@ fn powershell_exe() -> std::path::PathBuf {
.join("powershell.exe")
}
+/// Runs a fixed PowerShell script and returns the first non-empty line it prints.
+///
+/// `app_name` reaches the script only as `$env:SCREENPIPE_ICON_APP_NAME`. PowerShell
+/// reads an environment value as data, so a name like `x$(calc)` stays text. The
+/// name comes from `/app-icon`, which any web page can call, so never build a
+/// script from it: `&'static str` keeps every script a compile-time constant.
+#[cfg(target_os = "windows")]
+async fn run_powershell(script: &'static str, app_name: &str) -> Option<String> {
+ const CREATE_NO_WINDOW: u32 = 0x08000000;
+
+ let _permit = SEMAPHORE.acquire().await.ok()?;
+ let output = tokio::process::Command::new(powershell_exe())
+ .args(["-NoProfile", "-WindowStyle", "hidden", "-Command", script])
+ .env("SCREENPIPE_ICON_APP_NAME", app_name)
+ .creation_flags(CREATE_NO_WINDOW)
+ .output()
+ .await
+ .ok()?;
+
+ std::str::from_utf8(&output.stdout)
+ .ok()?
+ .lines()
+ .map(str::trim)
+ .find(|line| !line.is_empty())
+ .map(str::to_string)
+}
+
+/// Returns the first `.exe` under `dir` whose file name contains `name_lower`
+/// (case-insensitive), descending at most `max_depth` folder levels. Junctions and
+/// symlinked folders are not followed.
+#[cfg(any(target_os = "windows", test))]
+fn find_exe(dir: &std::path::Path, name_lower: &str, max_depth: usize) -> Option<String> {
+ for entry in std::fs::read_dir(dir).ok()?.flatten() {
+ let Ok(file_type) = entry.file_type() else {
+ continue;
+ };
+ if file_type.is_dir() {
+ if max_depth > 0 {
+ if let Some(found) = find_exe(&entry.path(), name_lower, max_depth - 1) {
+ return Some(found);
+ }
+ }
+ continue;
+ }
+ let file_name = entry.file_name().to_string_lossy().to_lowercase();
+ if file_name.ends_with(".exe") && file_name.contains(name_lower) {
+ return Some(entry.path().to_string_lossy().into_owned());
+ }
+ }
+ None
+}
+
/// Strip dots, dashes, underscores and spaces so "screenpi.pe" matches "screenpipe",
/// "wezterm-gui" matches "wezterm", etc.
#[cfg(target_os = "windows")]
@@ -318,8 +370,7 @@ fn names_match(folder: &str, search: &str) -> bool {
}
#[cfg(target_os = "windows")]
-async fn get_exe_from_potential_path(app_name: &str) -> Option<String> {
- const CREATE_NO_WINDOW: u32 = 0x08000000;
+fn get_exe_from_potential_path(app_name: &str) -> Option<String> {
let app_name = app_name.strip_suffix(".exe").unwrap_or(&app_name);
let app_lower = app_name.to_lowercase();
@@ -409,136 +460,41 @@ async fn get_exe_from_potential_path(app_name: &str) -> Option<String> {
}
}
- let potential_paths = [
- (
- r"C:\ProgramData\Microsoft\Windows\Start Menu\Programs",
- true,
- ),
- (r"C:\Windows\", false),
- ];
- for (path, recursive) in &potential_paths {
- let command = if *recursive {
- format!(
- r#"
- Get-ChildItem -Path "{}" -Filter "*{}*.exe" -Recurse | ForEach-Object {{ $_.FullName }}
- "#,
- path, app_name
- )
- } else {
- format!(
- r#"
- Get-ChildItem -Path "{}" -Filter "*{}*.exe" | ForEach-Object {{ $_.FullName }}
- "#,
- path, app_name
- )
- };
-
- let _permit = SEMAPHORE.acquire().await.unwrap();
-
- let output = tokio::process::Command::new(powershell_exe())
- .arg("-NoProfile")
- .arg("-WindowStyle")
- .arg("hidden")
- .arg("-Command")
- .arg(command)
- .creation_flags(CREATE_NO_WINDOW)
- .output()
- .await
- .ok()?;
-
- if output.status.success() {
- let stdout = std::str::from_utf8(&output.stdout).ok()?;
- if !stdout.is_empty() {
- return stdout.lines().next().map(str::to_string);
- }
- }
- }
- None
+ // Start Menu (a few levels deep), then system tools such as notepad.exe.
+ find_exe(
+ std::path::Path::new(r"C:\ProgramData\Microsoft\Windows\Start Menu\Programs"),
+ &app_lower,
+ 4,
+ )
+ .or_else(|| find_exe(std::path::Path::new(r"C:\Windows"), &app_lower, 0))
}
+/// Finds the app among installed Store (Appx/MSIX) packages and returns the first
+/// matching `.exe` in the package folder. One PowerShell process; the name is
+/// matched as plain text (no wildcards) and tried without, then with, spaces.
#[cfg(target_os = "windows")]
async fn get_exe_by_appx(app_name: &str) -> Option<String> {
- use std::str;
-
- const CREATE_NO_WINDOW: u32 = 0x08000000;
- let app_name = app_name.strip_suffix(".exe").unwrap_or(&app_name);
- let app_name_withoutspace = app_name.replace(" ", "");
-
- let _permit = SEMAPHORE.acquire().await.unwrap();
-
- let output = tokio::process::Command::new(powershell_exe())
- .arg("-NoProfile")
- .arg("-WindowStyle")
- .arg("hidden")
- .arg("-Command")
- .arg(format!(
- r#"Get-AppxPackage | Where-Object {{ $_.Name -like "*{}*" }}"#,
- app_name_withoutspace
- ))
- .creation_flags(CREATE_NO_WINDOW)
- .output()
- .await
- .ok()?;
-
- if !output.status.success() {
- return None;
- }
-
- let stdout = str::from_utf8(&output.stdout).ok()?;
- let package_name = stdout
- .lines()
- .find(|line| line.contains("PackageFullName"))
- .and_then(|line| line.split(':').nth(1))
- .map(str::trim)?;
-
- let exe_output = tokio::process::Command::new(powershell_exe())
- .arg("-NoProfile")
- .arg("-WindowStyle")
- .arg("hidden")
- .arg("-Command")
- .arg(format!(
- r#"
- Get-ChildItem -Path "C:\Program Files\WindowsApps\{}\*" -Filter "*{}*.exe" -Recurse | ForEach-Object {{ $_.FullName }}
- "#,
- package_name,
- app_name_withoutspace
- ))
- .creation_flags(CREATE_NO_WINDOW)
- .output()
- .await
- .ok()?;
-
- if exe_output.status.success() {
- let exe_stdout = str::from_utf8(&exe_output.stdout).ok()?;
- if !exe_stdout.is_empty() {
- return exe_stdout.lines().next().map(str::to_string);
- }
+ const SCRIPT: &str = r#"
+$name = $env:SCREENPIPE_ICON_APP_NAME
+$compact = $name -replace ' ', ''
+$pkg = Get-AppxPackage |
+ Where-Object { $_.Name.IndexOf($compact, [StringComparison]::OrdinalIgnoreCase) -ge 0 } |
+ Select-Object -First 1
+if ($pkg -and $pkg.InstallLocation) {
+ foreach ($term in (@($compact, $name) | Select-Object -Unique)) {
+ $exe = Get-ChildItem -LiteralPath $pkg.InstallLocation -Filter ('*' + $term + '*.exe') -Recurse -ErrorAction SilentlyContinue |
+ Select-Object -First 1
+ if ($exe) { $exe.FullName; break }
}
- // second attempt with space if the first attempt couldn't find exe
- let exe_output = tokio::process::Command::new(powershell_exe())
- .arg("-NoProfile")
- .arg("-WindowStyle")
- .arg("hidden")
- .arg("-Command")
- .arg(format!(
- r#"
- Get-ChildItem -Path "C:\Program Files\WindowsApps\{}\*" -Filter "*{}*.exe" -Recurse | ForEach-Object {{ $_.FullName }}
- "#,
- package_name,
- app_name
- ))
- .creation_flags(CREATE_NO_WINDOW)
- .output()
- .await
- .ok()?;
+}
+"#;
- if exe_output.status.success() {
- let exe_stdout = str::from_utf8(&exe_output.stdout).ok()?;
- if !exe_stdout.is_empty() {
- return exe_stdout.lines().next().map(str::to_string);
- }
+ let app_name = app_name.strip_suffix(".exe").unwrap_or(app_name);
+ if app_name.trim().is_empty() {
+ // An empty search term would match the first installed package.
+ return None;
}
- None
+ run_powershell(SCRIPT, app_name).await
}
#[cfg(target_os = "linux")]
@@ -967,3 +923,96 @@ pub fn list_installed_apps() -> Vec<String> {
names.into_iter().collect()
}
+
+#[cfg(test)]
+mod find_exe_tests {
+ use super::find_exe;
+ use std::path::Path;
+
+ fn touch(path: &Path) {
+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();
+ std::fs::write(path, b"").unwrap();
+ }
+
+ #[test]
+ fn finds_exe_case_insensitively_within_depth() {
+ let root = tempfile::tempdir().unwrap();
+ let exe = root
+ .path()
+ .join("Vendor")
+ .join("bin")
+ .join("WezTerm-GUI.EXE");
+ touch(&exe);
+
+ assert_eq!(
+ find_exe(root.path(), "wezterm", 2),
+ Some(exe.to_string_lossy().into_owned())
+ );
+ assert_eq!(find_exe(root.path(), "wezterm", 1), None);
+ assert_eq!(find_exe(root.path(), "wezterm", 0), None);
+ }
+
+ #[test]
+ fn ignores_files_that_are_not_exe() {
+ let root = tempfile::tempdir().unwrap();
+ for name in ["notepad.txt", "notepad.exe.bak", "notepad.lnk"] {
+ touch(&root.path().join(name));
+ }
+ assert_eq!(find_exe(root.path(), "notepad", 0), None);
+
+ let exe = root.path().join("notepad.exe");
+ touch(&exe);
+ assert_eq!(
+ find_exe(root.path(), "notepad", 0),
+ Some(exe.to_string_lossy().into_owned())
+ );
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn does_not_follow_symlinked_folders() {
+ let target = tempfile::tempdir().unwrap();
+ touch(&target.path().join("app.exe"));
+ let root = tempfile::tempdir().unwrap();
+ std::os::unix::fs::symlink(target.path(), root.path().join("link")).unwrap();
+
+ assert_eq!(find_exe(root.path(), "app", 3), None);
+ }
+}
+
+#[cfg(all(test, target_os = "windows"))]
+mod windows_powershell_tests {
+ use super::{get_exe_by_appx, run_powershell};
+
+ #[tokio::test]
+ async fn powershell_reads_the_app_name_as_text() {
+ for name in ["$(1+1)", "a`b", "a;b", "a\"b", "'a'"] {
+ let echoed = run_powershell(
+ "Write-Output ('[' + $env:SCREENPIPE_ICON_APP_NAME + ']')",
+ name,
+ )
+ .await;
+ assert_eq!(echoed, Some(format!("[{name}]")));
+ }
+ }
+
+ #[tokio::test]
+ async fn appx_lookup_never_runs_the_app_name() {
+ let dir = tempfile::tempdir().unwrap();
+ let marker = dir.path().join("ran");
+ let create = format!("New-Item -ItemType File -Path '{}'", marker.display());
+ // Each name created `marker` when the lookup pasted it into PowerShell
+ // source. U+201C is a curly quote PowerShell treats like `"`.
+ let payloads = [
+ format!("x$({create})"),
+ format!("x\"; {create}; \""),
+ format!("x\u{201C}; {create}; \u{201C}"),
+ format!("x'; {create}; '"),
+ format!("x; {create}"),
+ ];
+ for name in payloads {
+ let _ = get_exe_by_appx(&name).await;
+ assert!(!marker.exists(), "app name ran as code: {name}");
+ }
+ }
+}
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/server.rs b/apps/screenpipe-app-tauri/src-tauri/src/server.rs
index a1e92d627..6366ad50d 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/server.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/server.rs
@@ -72,10 +72,11 @@ struct AuthData {
user_id: String,
}
+/// `/app-icon` takes only a name. It used to accept a `path` too, which let any
+/// web page point the OS icon lookup at an arbitrary file or a remote share.
#[derive(Debug, Deserialize)]
struct AppIconQuery {
name: String,
- path: Option<String>,
}
#[derive(Deserialize, Debug)]
@@ -543,48 +544,77 @@ async fn handle_auth(
}))
}
-async fn get_app_icon_handler(
- State(_): State<ServerState>,
- Query(app_name): Query<AppIconQuery>,
-) -> impl IntoResponse {
+/// How long `/app-icon` remembers a name with no icon, so new installs still show up.
+const APP_ICON_MISS_TTL: std::time::Duration = std::time::Duration::from_secs(300);
+/// Most remembered misses. Unique names would otherwise grow the map without bound.
+const APP_ICON_MISS_CAP: usize = 1024;
+const MAX_APP_ICON_NAME_CHARS: usize = 256;
+
+/// Whether `name` could be an app or executable name. Keeps path separators and
+/// wildcards out of the OS lookups and bounds the miss-cache key. This is input
+/// hygiene; Windows lookups hand the name to PowerShell as data either way.
+fn is_valid_app_icon_name(name: &str) -> bool {
+ !name.trim().is_empty()
+ && name.chars().count() <= MAX_APP_ICON_NAME_CHARS
+ && !name.chars().any(|c| {
+ c.is_control() || matches!(c, '<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*')
+ })
+}
+
+fn remember_app_icon_miss(
+ misses: &mut std::collections::HashMap<String, std::time::Instant>,
+ name: String,
+) {
+ misses.insert(name, std::time::Instant::now());
+ if misses.len() > APP_ICON_MISS_CAP {
+ misses.retain(|_, at| at.elapsed() < APP_ICON_MISS_TTL);
+ if misses.len() > APP_ICON_MISS_CAP {
+ misses.clear();
+ }
+ }
+}
+
+fn no_app_icon() -> (
+ StatusCode,
+ [(http::header::HeaderName, HeaderValue); 2],
+ Bytes,
+) {
+ let headers = [
+ (CONTENT_TYPE, HeaderValue::from_static("image/png")),
+ (
+ http::header::CACHE_CONTROL,
+ HeaderValue::from_static("public, max-age=60"),
+ ),
+ ];
+ (StatusCode::NO_CONTENT, headers, Bytes::new())
+}
+
+async fn get_app_icon_handler(Query(query): Query<AppIconQuery>) -> impl IntoResponse {
use once_cell::sync::Lazy;
use std::collections::HashMap;
use std::sync::Mutex;
use std::time::Instant;
- // Cache of app names we already know have no icon, with expiry time.
- // Entries expire after 5 minutes so new installations are picked up.
- static NOT_FOUND_CACHE: Lazy<Mutex<HashMap<String, Instant>>> =
- Lazy::new(|| Mutex::new(HashMap::new()));
-
- const NOT_FOUND_TTL: std::time::Duration = std::time::Duration::from_secs(300);
+ // Names we already know have no icon, so repeat requests skip the lookup.
+ static MISSES: Lazy<Mutex<HashMap<String, Instant>>> = Lazy::new(|| Mutex::new(HashMap::new()));
- info!("received app icon request: {:?}", app_name);
+ info!("received app icon request: {:?}", query);
- // Check not-found cache first to skip expensive lookups
- let cache_key = format!(
- "{}:{}",
- app_name.name,
- app_name.path.as_deref().unwrap_or("")
- );
- if let Ok(cache) = NOT_FOUND_CACHE.lock() {
- if let Some(inserted_at) = cache.get(&cache_key) {
- if inserted_at.elapsed() < NOT_FOUND_TTL {
- let headers = [
- (CONTENT_TYPE, HeaderValue::from_static("image/png")),
- (
- http::header::CACHE_CONTROL,
- HeaderValue::from_static("public, max-age=60"),
- ),
- ];
- return (StatusCode::NO_CONTENT, headers, Bytes::new());
- }
+ if !is_valid_app_icon_name(&query.name) {
+ return no_app_icon();
+ }
+ if let Ok(misses) = MISSES.lock() {
+ if misses
+ .get(&query.name)
+ .is_some_and(|at| at.elapsed() < APP_ICON_MISS_TTL)
+ {
+ return no_app_icon();
}
}
#[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))]
{
- match crate::icons::get_app_icon(&app_name.name, app_name.path).await {
+ match crate::icons::get_app_icon(&query.name, None).await {
Ok(Some(icon)) => {
let headers = [
(CONTENT_TYPE, HeaderValue::from_static("image/png")),
@@ -596,36 +626,17 @@ async fn get_app_icon_handler(
(StatusCode::OK, headers, Bytes::from(icon.data))
}
Ok(None) | Err(_) => {
- // Cache the miss with timestamp for expiry
- if let Ok(mut cache) = NOT_FOUND_CACHE.lock() {
- cache.insert(cache_key, Instant::now());
- // Evict expired entries periodically
- if cache.len() > 100 {
- cache.retain(|_, t| t.elapsed() < NOT_FOUND_TTL);
- }
+ if let Ok(mut misses) = MISSES.lock() {
+ remember_app_icon_miss(&mut misses, query.name);
}
- let headers = [
- (CONTENT_TYPE, HeaderValue::from_static("image/png")),
- (
- http::header::CACHE_CONTROL,
- HeaderValue::from_static("public, max-age=60"),
- ),
- ];
- (StatusCode::NO_CONTENT, headers, Bytes::new())
+ no_app_icon()
}
}
}
#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
{
- let headers = [
- (CONTENT_TYPE, HeaderValue::from_static("image/png")),
- (
- http::header::CACHE_CONTROL,
- HeaderValue::from_static("public, max-age=60"),
- ),
- ];
- (StatusCode::NO_CONTENT, headers, Bytes::new())
+ no_app_icon()
}
}
@@ -882,8 +893,10 @@ curl -X POST http://localhost:11435/notify \
#[cfg(test)]
mod tests {
use super::{
- focus_handoff_matches_current_exe, is_allowed_browser_extension_origin,
- is_allowed_local_host, is_allowed_local_origin, with_control_server_boundary,
+ focus_handoff_matches_current_exe, get_app_icon_handler,
+ is_allowed_browser_extension_origin, is_allowed_local_host, is_allowed_local_origin,
+ is_valid_app_icon_name, remember_app_icon_miss, with_control_server_boundary,
+ APP_ICON_MISS_CAP, MAX_APP_ICON_NAME_CHARS,
};
use axum::{
body::Body,
@@ -971,6 +984,105 @@ mod tests {
}
}
+ #[test]
+ fn app_icon_accepts_real_app_names() {
+ for name in [
+ "Google Chrome",
+ "wezterm-gui.exe",
+ "Microsoft Teams (work or school)",
+ "org.gnome.Nautilus",
+ // `$` is legal in file names. Validation is not the injection barrier;
+ // icons.rs passes the name to PowerShell as data.
+ "x$(calc)",
+ ] {
+ assert!(is_valid_app_icon_name(name), "should accept {name:?}");
+ }
+ assert!(is_valid_app_icon_name(&"a".repeat(MAX_APP_ICON_NAME_CHARS)));
+ }
+
+ #[test]
+ fn app_icon_rejects_paths_wildcards_and_oversized_names() {
+ let too_long = "a".repeat(MAX_APP_ICON_NAME_CHARS + 1);
+ for name in [
+ "",
+ " ",
+ too_long.as_str(),
+ r"a\b",
+ r"\\evil.com\share\a",
+ "a/b",
+ "../etc",
+ "a\"b",
+ "*",
+ "a?b",
+ "C:",
+ "x\u{7}",
+ "x\ny",
+ ] {
+ assert!(!is_valid_app_icon_name(name), "should reject {name:?}");
+ }
+ }
+
+ #[test]
+ fn app_icon_miss_cache_stays_bounded() {
+ let mut misses = std::collections::HashMap::new();
+ for i in 0..APP_ICON_MISS_CAP * 3 {
+ remember_app_icon_miss(&mut misses, format!("random-{i}"));
+ assert!(misses.len() <= APP_ICON_MISS_CAP);
+ }
+ remember_app_icon_miss(&mut misses, "Slack".to_string());
+ assert!(misses.contains_key("Slack"));
+ }
+
+ /// Drives the real `/app-icon` route and the real macOS icon lookup.
+ #[cfg(target_os = "macos")]
+ #[tokio::test]
+ async fn app_icon_route_ignores_path_and_rejects_bad_names() {
+ use axum::body::HttpBody;
+
+ let app = with_control_server_boundary(
+ Router::new().route("/app-icon", axum::routing::get(get_app_icon_handler)),
+ );
+ let fetch = |uri: &'static str| {
+ let app = app.clone();
+ async move {
+ let request = Request::get(uri)
+ .header(HOST, "127.0.0.1:11435")
+ .body(Body::empty())
+ .unwrap();
+ let response = app.oneshot(request).await.unwrap();
+ let status = response.status();
+ let mut body = response.into_body();
+ let mut bytes = Vec::new();
+ while let Some(chunk) = body.data().await {
+ bytes.extend_from_slice(&chunk.unwrap());
+ }
+ (status, bytes)
+ }
+ };
+
+ let (status, safari) = fetch("/app-icon?name=Safari").await;
+ assert_eq!(status, StatusCode::OK);
+ assert!(safari.starts_with(b"\x89PNG"));
+
+ // `path` used to override the name, so these returned Calculator's icon.
+ assert!(Path::new("/System/Applications/Calculator.app").exists());
+ let (status, body) =
+ fetch("/app-icon?name=Safari&path=/System/Applications/Calculator.app").await;
+ assert_eq!((status, body), (StatusCode::OK, safari));
+ let (status, body) =
+ fetch("/app-icon?name=no-such-app-7f3a&path=/System/Applications/Calculator.app").await;
+ assert_eq!((status, body.len()), (StatusCode::NO_CONTENT, 0));
+
+ for uri in [
+ "/app-icon?name=a%2Fb",
+ "/app-icon?name=%5C%5Cevil.com%5Cshare%5Ca",
+ "/app-icon?name=",
+ ] {
+ let (status, body) = fetch(uri).await;
+ assert_eq!((status, body.len()), (StatusCode::NO_CONTENT, 0), "{uri}");
+ }
+ }
+
#[test]
fn focus_handoff_accepts_same_executable_or_legacy_payload() {
let current = Path::new(r"C:\Users\louis\AppData\Local\screenpipe\screenpipe-app.exe");