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(windows): prevent Consumer startup while Enterprise runs (#7598)

Ezra Ellette16856a504c17
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
index f9a3659a9..b2d6465aa 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
@@ -506,6 +506,45 @@ async fn main() {
// See `dev_isolation`.
dev_isolation::apply();
+ let focus_port: u16 = std::env::var("SCREENPIPE_FOCUS_PORT")
+ .ok()
+ .and_then(|value| value.parse().ok())
+ .unwrap_or(11435);
+ #[cfg(target_os = "windows")]
+ let api_port: u16 = std::env::var("SCREENPIPE_PORT")
+ .ok()
+ .and_then(|value| value.parse().ok())
+ .unwrap_or_else(|| recording::LocalApiContext::default().port);
+
+ // Enterprise owns an edition marker before either build can initialize
+ // Tauri, the store, database, or recorder. Consumer exits based on this
+ // kernel-backed build identity even while Enterprise has not bound a port
+ // or its HTTP endpoints are unhealthy.
+ #[cfg(target_os = "windows")]
+ if !arguments.iter().any(|argument| argument == "--cpu-smoke")
+ {
+ #[cfg(feature = "enterprise-build")]
+ if let Err(error) =
+ windows_enterprise_takeover::publish_enterprise_presence(focus_port, api_port)
+ {
+ eprintln!("screenpipe: enterprise presence initialization failed: {error}");
+ std::process::exit(1);
+ }
+
+ #[cfg(not(feature = "enterprise-build"))]
+ match windows_enterprise_takeover::enterprise_is_present(focus_port, api_port).await {
+ Ok(true) => {
+ eprintln!("screenpipe: Enterprise is running; Consumer startup is blocked.");
+ std::process::exit(0);
+ }
+ Ok(false) => {}
+ Err(error) => {
+ eprintln!("screenpipe: Enterprise presence check failed: {error}");
+ std::process::exit(1);
+ }
+ }
+ }
+
#[cfg(target_os = "linux")]
linux_webkit_env::configure();
@@ -619,17 +658,8 @@ async fn main() {
#[cfg(not(target_os = "macos"))]
let launchd_job_label: Option<String> = None;
- let focus_port: u16 = std::env::var("SCREENPIPE_FOCUS_PORT")
- .ok()
- .and_then(|v| v.parse().ok())
- .unwrap_or(11435);
-
#[cfg(all(target_os = "windows", feature = "enterprise-build"))]
let enterprise_duplicate = {
- let api_port = std::env::var("SCREENPIPE_PORT")
- .ok()
- .and_then(|v| v.parse().ok())
- .unwrap_or_else(|| recording::LocalApiContext::default().port);
match windows_enterprise_takeover::take_over_screenpipe_owners(focus_port, api_port)
.await
{
@@ -1844,10 +1874,6 @@ async fn main() {
let app_handle = app.handle().clone();
// Initialize server first (core service)
- let focus_port: u16 = std::env::var("SCREENPIPE_FOCUS_PORT")
- .ok()
- .and_then(|v| v.parse().ok())
- .unwrap_or(11435);
let server_shutdown_tx = spawn_server(app_handle.clone(), focus_port);
app.manage(server_shutdown_tx);
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/windows_enterprise_takeover.rs b/apps/screenpipe-app-tauri/src-tauri/src/windows_enterprise_takeover.rs
index 765e9c5ce..23dc63bf6 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/windows_enterprise_takeover.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/windows_enterprise_takeover.rs
@@ -5,9 +5,10 @@
//! control port. This runs before Tauri or the embedded database is opened.
use std::io::{Read, Seek, SeekFrom, Write};
+use std::os::windows::ffi::OsStrExt;
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
use std::path::{Path, PathBuf};
-use std::sync::Mutex;
+use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant};
use sysinfo::{Pid, PidExt, ProcessExt, System, SystemExt};
@@ -15,7 +16,268 @@ use sysinfo::{Pid, PidExt, ProcessExt, System, SystemExt};
pub(crate) const LOG_NAME: &str = "enterprise-takeover.log";
const MAX_LOG_BYTES: u64 = 32 * 1024;
const CREATE_NO_WINDOW: u32 = 0x08000000;
+const ENTERPRISE_PRODUCT_NAME: &str = "screenpipe enterprise";
static LOG_WRITER: Mutex<()> = Mutex::new(());
+static ENTERPRISE_PRESENCE: OnceLock<OwnedHandle> = OnceLock::new();
+
+fn presence_name(control_port: u16, api_port: u16) -> String {
+ // Local objects are scoped to the interactive Windows session. Including
+ // the already-isolated ports keeps debug and E2E launches independent from
+ // installed production instances without trusting an installation path.
+ format!(r"Local\ScreenpipeEnterprise-{control_port}-{api_port}")
+}
+
+/// Publish authoritative Enterprise build identity before any app state opens.
+/// The kernel releases the marker when the process truly exits, including on a
+/// crash, so Consumer cannot mistake a stale file or unhealthy HTTP endpoint
+/// for a live Enterprise instance.
+#[cfg(feature = "enterprise-build")]
+pub(crate) fn publish_enterprise_presence(control_port: u16, api_port: u16) -> Result<(), String> {
+ use windows::core::HSTRING;
+ use windows::Win32::System::Threading::CreateMutexW;
+
+ if ENTERPRISE_PRESENCE.get().is_some() {
+ return Ok(());
+ }
+ let name = HSTRING::from(presence_name(control_port, api_port));
+ let handle = unsafe { CreateMutexW(None, false, &name) }.map_err(|error| {
+ let cause = format!("could not publish Enterprise presence: {error}");
+ record(
+ "presence_publish_failed",
+ &cause,
+ "enterprise_start_aborted",
+ );
+ cause
+ })?;
+ // SAFETY: CreateMutexW returned an owned kernel handle, transferred once.
+ let handle = unsafe { OwnedHandle::from_raw_handle(handle.0 as *mut _) };
+ let _ = ENTERPRISE_PRESENCE.set(handle);
+ Ok(())
+}
+
+/// Consumer must stop while the Enterprise build owns its session marker.
+#[cfg(not(feature = "enterprise-build"))]
+pub(crate) async fn enterprise_is_present(
+ control_port: u16,
+ api_port: u16,
+) -> Result<bool, String> {
+ use windows::core::HSTRING;
+ use windows::Win32::Foundation::ERROR_FILE_NOT_FOUND;
+ use windows::Win32::System::Threading::{OpenMutexW, SYNCHRONIZATION_ACCESS_RIGHTS};
+
+ let name = HSTRING::from(presence_name(control_port, api_port));
+ match unsafe { OpenMutexW(SYNCHRONIZATION_ACCESS_RIGHTS(0x0010_0000), false, &name) } {
+ Ok(handle) => {
+ // SAFETY: OpenMutexW returned an owned kernel handle, closed here.
+ drop(unsafe { OwnedHandle::from_raw_handle(handle.0 as *mut _) });
+ record(
+ "consumer_blocked",
+ &format!(
+ "Enterprise presence verified for control_port={control_port} api_port={api_port}"
+ ),
+ "consumer_start_aborted",
+ );
+ return Ok(true);
+ }
+ Err(error) if error.code() == ERROR_FILE_NOT_FOUND.to_hresult() => {}
+ Err(error) => {
+ let cause = format!("could not inspect Enterprise presence: {error}");
+ record("presence_check_failed", &cause, "consumer_start_aborted");
+ return Err(cause);
+ }
+ }
+
+ for port in [control_port, api_port] {
+ let Some(pid) = listening_pid(port).await.map_err(|error| {
+ let cause = format!("could not inspect legacy Enterprise owner: {error}");
+ record(
+ "legacy_presence_check_failed",
+ &cause,
+ "consumer_start_aborted",
+ );
+ cause
+ })?
+ else {
+ continue;
+ };
+ if pid == std::process::id() {
+ continue;
+ }
+ let same_session = is_current_session(pid).map_err(|error| {
+ let cause = format!("could not inspect legacy Enterprise owner session: {error}");
+ record(
+ "legacy_presence_check_failed",
+ &cause,
+ "consumer_start_aborted",
+ );
+ cause
+ })?;
+ if !same_session {
+ continue;
+ }
+ let exe = process_executable(pid).map_err(|error| {
+ let cause = format!("could not identify legacy Enterprise owner: {error}");
+ record(
+ "legacy_presence_check_failed",
+ &cause,
+ "consumer_start_aborted",
+ );
+ cause
+ })?;
+ if !looks_like_screenpipe_exe(&exe) {
+ continue;
+ }
+ let product_name = executable_product_name(&exe).map_err(|error| {
+ let cause = format!("could not inspect legacy Enterprise metadata: {error}");
+ record(
+ "legacy_presence_check_failed",
+ &cause,
+ "consumer_start_aborted",
+ );
+ cause
+ })?;
+ if product_name.is_some_and(|name| name.eq_ignore_ascii_case(ENTERPRISE_PRODUCT_NAME)) {
+ record(
+ "consumer_blocked",
+ &format!("legacy Enterprise ProductName verified for pid={pid} port={port}"),
+ "consumer_start_aborted",
+ );
+ return Ok(true);
+ }
+ }
+ Ok(false)
+}
+
+fn process_executable(pid: u32) -> Result<PathBuf, String> {
+ use windows::core::PWSTR;
+ use windows::Win32::System::Threading::{
+ OpenProcess, QueryFullProcessImageNameW, PROCESS_NAME_FORMAT,
+ PROCESS_QUERY_LIMITED_INFORMATION,
+ };
+
+ let process = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) }
+ .map_err(|error| format!("could not open owner pid={pid}: {error}"))?;
+ // SAFETY: OpenProcess returned an owned kernel handle, transferred once.
+ let process = unsafe { OwnedHandle::from_raw_handle(process.0 as *mut _) };
+ let mut path = vec![0u16; 32_768];
+ let mut length = path.len() as u32;
+ unsafe {
+ QueryFullProcessImageNameW(
+ windows::Win32::Foundation::HANDLE(process.as_raw_handle()),
+ PROCESS_NAME_FORMAT(0),
+ PWSTR(path.as_mut_ptr()),
+ &mut length,
+ )
+ .map_err(|error| format!("could not query owner pid={pid} executable: {error}"))?;
+ }
+ path.truncate(length as usize);
+ Ok(PathBuf::from(String::from_utf16(&path).map_err(
+ |error| format!("owner pid={pid} returned an invalid executable path: {error}"),
+ )?))
+}
+
+fn executable_product_name(path: &Path) -> Result<Option<String>, String> {
+ use std::ffi::c_void;
+
+ #[link(name = "version")]
+ extern "system" {
+ fn GetFileVersionInfoSizeW(filename: *const u16, handle: *mut u32) -> u32;
+ fn GetFileVersionInfoW(
+ filename: *const u16,
+ handle: u32,
+ length: u32,
+ data: *mut c_void,
+ ) -> i32;
+ fn VerQueryValueW(
+ block: *const c_void,
+ sub_block: *const u16,
+ buffer: *mut *mut c_void,
+ length: *mut u32,
+ ) -> i32;
+ }
+
+ let path_wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
+ let size = unsafe { GetFileVersionInfoSizeW(path_wide.as_ptr(), std::ptr::null_mut()) };
+ if size == 0 {
+ let error = std::io::Error::last_os_error();
+ if matches!(error.raw_os_error(), Some(1812..=1815)) {
+ return Ok(None);
+ }
+ return Err(format!(
+ "{} has no readable PE version resource: {}",
+ path.display(),
+ error
+ ));
+ }
+ let mut data = vec![0u8; size as usize];
+ unsafe {
+ if GetFileVersionInfoW(
+ path_wide.as_ptr(),
+ 0,
+ size,
+ data.as_mut_ptr().cast::<c_void>(),
+ ) == 0
+ {
+ return Err(format!(
+ "could not read {}: {}",
+ path.display(),
+ std::io::Error::last_os_error()
+ ));
+ }
+ }
+
+ let translation_query: Vec<u16> = "\\VarFileInfo\\Translation\0".encode_utf16().collect();
+ let mut translation = std::ptr::null_mut::<c_void>();
+ let mut translation_len = 0u32;
+ unsafe {
+ if VerQueryValueW(
+ data.as_ptr().cast::<c_void>(),
+ translation_query.as_ptr(),
+ &mut translation,
+ &mut translation_len,
+ ) == 0
+ {
+ return Ok(None);
+ }
+ }
+ if translation_len < 4 || translation.is_null() {
+ return Err(format!(
+ "{} has an invalid PE translation table",
+ path.display()
+ ));
+ }
+ let translation = unsafe { std::slice::from_raw_parts(translation.cast::<u16>(), 2) };
+ let product_query = format!(
+ "\\StringFileInfo\\{:04x}{:04x}\\ProductName\0",
+ translation[0], translation[1]
+ );
+ let product_query: Vec<u16> = product_query.encode_utf16().collect();
+ let mut product = std::ptr::null_mut::<c_void>();
+ let mut product_len = 0u32;
+ unsafe {
+ if VerQueryValueW(
+ data.as_ptr().cast::<c_void>(),
+ product_query.as_ptr(),
+ &mut product,
+ &mut product_len,
+ ) == 0
+ {
+ return Ok(None);
+ }
+ }
+ if product_len == 0 || product.is_null() {
+ return Ok(None);
+ }
+ let product = unsafe {
+ std::slice::from_raw_parts(
+ product.cast::<u16>(),
+ product_len.saturating_sub(1) as usize,
+ )
+ };
+ String::from_utf16(product)
+ .map(Some)
+ .map_err(|error| format!("{} has an invalid ProductName: {error}", path.display()))
+}
pub(crate) fn is_takeover_log(name: &str) -> bool {
name == LOG_NAME
@@ -157,8 +419,8 @@ async fn resolve_verified_owner(port: u16) -> Result<Option<Owner>, String> {
let exe = process.exe().to_path_buf();
let start_time = process.start_time();
#[cfg(test)]
- let is_current_test_harness = std::env::current_exe()
- .is_ok_and(|current_exe| same_path(&exe, &current_exe));
+ let is_current_test_harness =
+ std::env::current_exe().is_ok_and(|current_exe| same_path(&exe, &current_exe));
#[cfg(not(test))]
let is_current_test_harness = false;
if !looks_like_screenpipe_exe(&exe) && !is_current_test_harness {
@@ -249,6 +511,27 @@ fn same_path(left: &Path, right: &Path) -> bool {
}
fn verify_current_session(pid: u32) -> Result<(), String> {
+ let session = query_session(pid)?;
+ if !session.is_current {
+ return Err(format!(
+ "refused to terminate pid={pid} in session {}; Enterprise is in session {}",
+ session.owner, session.current
+ ));
+ }
+ Ok(())
+}
+
+fn is_current_session(pid: u32) -> Result<bool, String> {
+ Ok(query_session(pid)?.is_current)
+}
+
+struct SessionQuery {
+ owner: u32,
+ current: u32,
+ is_current: bool,
+}
+
+fn query_session(pid: u32) -> Result<SessionQuery, String> {
use windows::Win32::System::{
RemoteDesktop::ProcessIdToSessionId, Threading::GetCurrentProcessId,
};
@@ -260,12 +543,11 @@ fn verify_current_session(pid: u32) -> Result<(), String> {
ProcessIdToSessionId(GetCurrentProcessId(), &mut current_session)
.map_err(|error| format!("could not inspect Enterprise session: {error}"))?;
}
- if owner_session != current_session {
- return Err(format!(
- "refused to terminate pid={pid} in session {owner_session}; Enterprise is in session {current_session}"
- ));
- }
- Ok(())
+ Ok(SessionQuery {
+ owner: owner_session,
+ current: current_session,
+ is_current: owner_session == current_session,
+ })
}
async fn listening_pid(port: u16) -> Result<Option<u32>, String> {
@@ -414,6 +696,124 @@ fn append_record_to(root: &Path, event: &str, cause: &str, outcome: &str) -> std
mod tests {
use super::*;
+ #[test]
+ fn enterprise_presence_fixture() {
+ use windows::core::HSTRING;
+ use windows::Win32::System::Threading::CreateMutexW;
+
+ let Ok(name) = std::env::var("SCREENPIPE_ENTERPRISE_PRESENCE_FIXTURE") else {
+ return;
+ };
+ let name = HSTRING::from(name);
+ let handle = unsafe { CreateMutexW(None, false, &name) }.unwrap();
+ // SAFETY: CreateMutexW returned an owned kernel handle, held until EOF.
+ let _handle = unsafe { OwnedHandle::from_raw_handle(handle.0 as *mut _) };
+ println!("presence-ready");
+ let _ = std::io::read_to_string(std::io::stdin());
+ }
+
+ #[cfg(not(feature = "enterprise-build"))]
+ #[tokio::test]
+ async fn consumer_blocks_until_live_enterprise_presence_exits() {
+ use std::io::{BufRead, BufReader};
+ use std::process::{Command, Stdio};
+
+ let control_port = unused_port();
+ let api_port = unused_port();
+ let name = presence_name(control_port, api_port);
+ let mut enterprise = Command::new(std::env::current_exe().unwrap())
+ .args([
+ "--exact",
+ "windows_enterprise_takeover::tests::enterprise_presence_fixture",
+ "--nocapture",
+ ])
+ .env("SCREENPIPE_ENTERPRISE_PRESENCE_FIXTURE", name)
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null())
+ .spawn()
+ .unwrap();
+ let mut output = BufReader::new(enterprise.stdout.take().unwrap());
+ let mut ready = String::new();
+ while !ready.contains("presence-ready") {
+ let mut line = String::new();
+ assert_ne!(output.read_line(&mut line).unwrap(), 0);
+ ready.push_str(&line);
+ }
+
+ assert!(enterprise_is_present(control_port, api_port).await.unwrap());
+ drop(enterprise.stdin.take());
+ assert!(enterprise.wait().unwrap().success());
+ assert!(!enterprise_is_present(control_port, api_port).await.unwrap());
+ }
+
+ #[cfg(not(feature = "enterprise-build"))]
+ #[tokio::test]
+ async fn consumer_allows_screenpipe_owner_without_product_metadata() {
+ let control_port = unused_port();
+ let api_port = unused_port();
+ let temp = tempfile::tempdir().unwrap();
+ let fixture_exe = temp.path().join("screenpipe.exe");
+ std::fs::copy(std::env::current_exe().unwrap(), &fixture_exe).unwrap();
+ remove_version_resource(&fixture_exe);
+ assert_eq!(executable_product_name(&fixture_exe).unwrap(), None);
+
+ let mut owner = spawn_owner_fixture(control_port, Some(&fixture_exe));
+ wait_for_fixture(control_port).await;
+
+ assert!(!enterprise_is_present(control_port, api_port).await.unwrap());
+ assert!(owner.try_wait().unwrap().is_none());
+ owner.kill().unwrap();
+ let _ = owner.wait().unwrap();
+ }
+
+ fn remove_version_resource(path: &Path) {
+ use std::ffi::c_void;
+
+ #[link(name = "kernel32")]
+ extern "system" {
+ fn BeginUpdateResourceW(filename: *const u16, delete_existing: i32) -> *mut c_void;
+ fn UpdateResourceW(
+ update: *mut c_void,
+ resource_type: *const u16,
+ name: *const u16,
+ language: u16,
+ data: *const c_void,
+ size: u32,
+ ) -> i32;
+ fn EndUpdateResourceW(update: *mut c_void, discard: i32) -> i32;
+ }
+
+ let path: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
+ let update = unsafe { BeginUpdateResourceW(path.as_ptr(), 0) };
+ assert!(
+ !update.is_null(),
+ "BeginUpdateResourceW failed: {}",
+ std::io::Error::last_os_error()
+ );
+ assert_ne!(
+ unsafe {
+ UpdateResourceW(
+ update,
+ 16usize as *const u16,
+ 1usize as *const u16,
+ 0x0409,
+ std::ptr::null(),
+ 0,
+ )
+ },
+ 0,
+ "UpdateResourceW failed: {}",
+ std::io::Error::last_os_error()
+ );
+ assert_ne!(
+ unsafe { EndUpdateResourceW(update, 0) },
+ 0,
+ "EndUpdateResourceW failed: {}",
+ std::io::Error::last_os_error()
+ );
+ }
+
#[test]
fn screenpipe_owner_fixture() {
let Ok(port) = std::env::var("SCREENPIPE_TAKEOVER_FIXTURE_PORT") else {
@@ -617,6 +1017,13 @@ mod tests {
"support_collection_available",
)
.unwrap();
+ append_record_to(
+ root.path(),
+ "consumer_blocked",
+ "Enterprise presence verified for control_port=11435 api_port=3030",
+ "consumer_start_aborted",
+ )
+ .unwrap();
let report =
crate::diagnostic_logs::collect_redacted_from_dirs(&[root.path().to_path_buf()])
@@ -627,6 +1034,8 @@ mod tests {
assert!(report.contains("os error 5"));
assert!(report.contains("enterprise_start_aborted"));
assert!(report.contains("startup_after_restart"));
+ assert!(report.contains("consumer_blocked"));
+ assert!(report.contains("consumer_start_aborted"));
assert!(!report.contains("[email protected]"));
}
}